python实现神经网络数据判别
时间: 2023-12-29 07:02:07 浏览: 65
以下是使用Python实现神经网络数据判别的步骤:
1.导入所需的库和数据集
```python
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
# 生成一个二分类数据集
X, y = make_classification(n_samples=1000, n_features=10, n_classes=2, random_state=123)
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=123)
```
2.定义神经网络模型
```python
class NeuralNetwork:
def __init__(self, n_inputs, n_hidden, n_outputs):
self.weights_hidden = np.random.randn(n_inputs, n_hidden)
self.bias_hidden = np.zeros((1, n_hidden))
self.weights_output = np.random.randn(n_hidden, n_outputs)
self.bias_output = np.zeros((1, n_outputs))
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def forward(self, X):
self.hidden = self.sigmoid(np.dot(X, self.weights_hidden) + self.bias_hidden)
self.output = self.sigmoid(np.dot(self.hidden, self.weights_output) + self.bias_output)
def sigmoid_derivative(self, x):
return x * (1 - x)
def backward(self, X, y, learning_rate):
error_output = y - self.output
delta_output = error_output * self.sigmoid_derivative(self.output)
error_hidden = delta_output.dot(self.weights_output.T)
delta_hidden = error_hidden * self.sigmoid_derivative(self.hidden)
self.weights_output += self.hidden.T.dot(delta_output) * learning_rate
self.bias_output += np.sum(delta_output, axis=0, keepdims=True) * learning_rate
self.weights_hidden += X.T.dot(delta_hidden) * learning_rate
self.bias_hidden += np.sum(delta_hidden, axis=0, keepdims=True) * learning_rate
def train(self, X, y, learning_rate, n_epochs):
for epoch in range(n_epochs):
self.forward(X)
self.backward(X, y, learning_rate)
def predict(self, X):
self.forward(X)
return np.round(self.output)
```
3.训练模型并进行预测
```python
# 初始化神经网络模型
nn = NeuralNetwork(n_inputs=10, n_hidden=5, n_outputs=1)
# 训练模型
nn.train(X_train, y_train, learning_rate=0.1, n_epochs=1000)
# 进行预测
y_pred = nn.predict(X_test)
```
阅读全文