bp神经网络算法python
时间: 2023-09-29 22:04:23 浏览: 126
BP神经网络算法(Backpropagation)是一种常用的人工神经网络算法,用于训练多层前馈神经网络。在Python中,有很多库可以用来实现BP神经网络算法,比如TensorFlow、Keras、PyTorch等。下面是一个使用Python实现BP神经网络算法的例子:
```python
import numpy as np
# 定义激活函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义BP神经网络类
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.weights2 = np.random.randn(self.hidden_size, self.output_size)
def forward(self, X):
# 前向传播
self.hidden_layer = sigmoid(np.dot(X, self.weights1))
self.output_layer = sigmoid(np.dot(self.hidden_layer, self.weights2))
return self.output_layer
def backward(self, X, y, output, learning_rate):
# 反向传播
self.output_error = y - output
self.output_delta = self.output_error * (output * (1 - output))
self.hidden_error = np.dot(self.output_delta, self.weights2.T)
self.hidden_delta = self.hidden_error * (self.hidden_layer * (1 - self.hidden_layer))
# 更新权重
self.weights2 += learning_rate * np.dot(self.hidden_layer.T, self.output_delta)
self.weights1 += learning_rate * np.dot(X.T, self.hidden_delta)
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):
return self.forward(X)
# 示例数据
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([[0], [1], [1], [0]])
# 创建BP神经网络对象并进行训练
nn = NeuralNetwork(2, 4, 1)
nn.train(X, y, epochs=10000, learning_rate=0.1)
# 测试预测
print(nn.predict(X))
```
以上是一个简单的BP神经网络算法的实现,你可以根据自己的需求进行修改和扩展。希望对你有帮助!
阅读全文