bp神经网络python代码
时间: 2023-08-25 13:07:36 浏览: 227
bp 神经网络算法. python代码实例
以下是一个简单的基于Python的BP神经网络示例代码:
```python
import numpy as np
# 定义sigmoid函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义BP神经网络类
class BPNeuralNetwork:
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.a2 = sigmoid(self.z2)
return self.a2
def sigmoid_derivative(self, x):
return x * (1 - x)
def backward(self, x, y, output):
# 反向传播
self.error = output - y
self.delta2 = self.error * self.sigmoid_derivative(output)
self.error_hidden = self.delta2.dot(self.weights2.T)
self.delta1 = self.error_hidden * self.sigmoid_derivative(self.a1)
# 更新权重矩阵和偏差向量
self.weights1 -= x.T.dot(self.delta1)
self.bias1 -= np.sum(self.delta1, axis=0)
self.weights2 -= self.a1.T.dot(self.delta2)
self.bias2 -= np.sum(self.delta2, axis=0)
def train(self, x, y, epochs):
for i in range(epochs):
output = self.forward(x)
self.backward(x, y, output)
def predict(self, x):
return self.forward(x)
```
使用方法:
```python
# 创建BP神经网络对象
bpnn = BPNeuralNetwork(2, 3, 1)
# 训练神经网络
x = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([[0], [1], [1], [0]])
bpnn.train(x, y, 10000)
# 预测结果
print(bpnn.predict(x))
```
输出结果:
```
[[0.02787267]
[0.98648467]
[0.98635977]
[0.02920167]]
```
这是一个简单的示例,如果需要实际应用,需要对代码进行进一步的优化和改进。
阅读全文