bp神经网络python代码
时间: 2023-09-02 13:12:18 浏览: 134
BP神经网络python代码
以下是一个简单的基于Python的BP神经网络代码示例:
```python
import numpy as np
class NeuralNetwork(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.W1 = np.random.randn(self.input_size, self.hidden_size)
self.b1 = np.zeros((1, self.hidden_size))
self.W2 = np.random.randn(self.hidden_size, self.output_size)
self.b2 = np.zeros((1, self.output_size))
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def forward(self, X):
# 前向传播
self.z1 = np.dot(X, self.W1) + self.b1
self.a1 = self.sigmoid(self.z1)
self.z2 = np.dot(self.a1, self.W2) + self.b2
self.y_hat = self.sigmoid(self.z2)
return self.y_hat
def sigmoid_derivative(self, x):
return x * (1 - x)
def backward(self, X, y, y_hat, learning_rate):
# 反向传播
error_output = y - y_hat
delta_output = error_output * self.sigmoid_derivative(y_hat)
error_hidden = np.dot(delta_output, self.W2.T)
delta_hidden = error_hidden * self.sigmoid_derivative(self.a1)
# 更新权重和偏差
self.W2 += learning_rate * np.dot(self.a1.T, delta_output)
self.b2 += learning_rate * np.sum(delta_output, axis=0, keepdims=True)
self.W1 += learning_rate * np.dot(X.T, delta_hidden)
self.b1 += learning_rate * np.sum(delta_hidden, axis=0)
def train(self, X, y, learning_rate=0.1, epochs=100):
for i in range(epochs):
y_hat = self.forward(X)
self.backward(X, y, y_hat, learning_rate)
def predict(self, X):
y_hat = self.forward(X)
predictions = np.round(y_hat)
return predictions
```
使用示例:
```python
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([[0], [1], [1], [0]])
nn = NeuralNetwork(input_size=2, hidden_size=3, output_size=1)
nn.train(X, y, epochs=1000)
print(nn.predict(X))
```
输出:
```
[[0.]
[1.]
[1.]
[0.]]
```
阅读全文