python写BP神经网络
时间: 2023-10-14 22:09:38 浏览: 86
作为AI助手,我可以向您展示一个简单的Python实现BP神经网络的示例代码:
```python
import numpy as np
class NeuralNetwork:
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 sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(self, x):
return x * (1 - x)
def forward(self, X):
# 前向传播
self.z1 = np.dot(X, self.weights1) + self.bias1
self.a1 = self.sigmoid(self.z1)
self.z2 = np.dot(self.a1, self.weights2) + self.bias2
self.a2 = self.sigmoid(self.z2)
return self.a2
def backward(self, X, y, output):
# 反向传播
self.output_error = y - output
self.output_delta = self.output_error * self.sigmoid_derivative(output)
self.z2_error = self.output_delta.dot(self.weights2.T)
self.z2_delta = self.z2_error * self.sigmoid_derivative(self.a1)
# 更新权重和偏差
self.weights1 += X.T.dot(self.z2_delta)
self.bias1 += np.sum(self.z2_delta, axis=0)
self.weights2 += self.a1.T.dot(self.output_delta)
self.bias2 += np.sum(self.output_delta, axis=0)
def train(self, X, y, n_epochs):
for i in range(n_epochs):
output = self.forward(X)
self.backward(X, y, output)
def predict(self, X):
return self.forward(X)
# 训练数据
X = np.array([[0,0,1], [0,1,1], [1,0,1], [1,1,1]])
y = np.array([[0], [1], [1], [0]])
# 初始化神经网络
nn = NeuralNetwork(3, 4, 1)
# 训练网络
nn.train(X, y, 10000)
# 预测输出
print(nn.predict(X))
```
以上代码实现了一个包含一个隐藏层的BP神经网络,用于解决XOR问题。您可以根据需要修改网络结构、激活函数等参数以适应不同的问题。
阅读全文