spyder 写BP神经网络代码
时间: 2023-11-04 10:05:58 浏览: 157
神经网络BP代码
下面是使用Spyder编写BP神经网络代码的示例:
```python
import numpy as np
# 定义sigmoid函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义BP神经网络类
class BPNeuralNetwork(object):
def __init__(self, input_size, hidden_size, output_size):
# 输入层、隐藏层、输出层的大小
self.input_size = input_size
self.hidden_size = hidden_size
self.output_size = output_size
# 初始化权重和偏置
self.weights1 = np.random.randn(self.input_size, self.hidden_size)
self.bias1 = np.random.randn(self.hidden_size)
self.weights2 = np.random.randn(self.hidden_size, self.output_size)
self.bias2 = np.random.randn(self.output_size)
# 前向传播
def forward(self, X):
self.z1 = np.dot(X, self.weights1) + self.bias1
self.a1 = sigmoid(self.z1)
self.z2 = np.dot(self.a1, self.weights2) + self.bias2
self.output = sigmoid(self.z2)
return self.output
# 反向传播
def backward(self, X, y, output, learning_rate):
delta_output = (output - y) * output * (1 - output)
delta_hidden = np.dot(delta_output, self.weights2.T) * self.a1 * (1 - self.a1)
self.weights2 -= learning_rate * np.dot(self.a1.T, delta_output)
self.bias2 -= learning_rate * np.sum(delta_output, axis=0)
self.weights1 -= learning_rate * np.dot(X.T, delta_hidden)
self.bias1 -= learning_rate * np.sum(delta_hidden, axis=0)
# 训练函数
def train(self, X, y, epochs, learning_rate):
for i in range(epochs):
output = self.forward(X)
self.backward(X, y, output, learning_rate)
# 预测函数
def predict(self, X):
output = self.forward(X)
return np.round(output)
```
使用示例:
```python
# 创建一个BP神经网络实例
nn = BPNeuralNetwork(2, 3, 1)
# 训练数据
X_train = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y_train = np.array([[0], [1], [1], [0]])
# 训练BP神经网络
nn.train(X_train, y_train, epochs=10000, learning_rate=0.1)
# 预测
X_test = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y_pred = nn.predict(X_test)
print(y_pred)
```
阅读全文