python实现BP神经网络代码
时间: 2023-09-02 16:15:46 浏览: 107
好的,以下是一个简单的Python BP神经网络实现的代码:
```python
import numpy as np
class NeuralNetwork:
def __init__(self, input_size, hidden_size, output_size):
self.weights1 = np.random.randn(input_size, hidden_size)
self.weights2 = np.random.randn(hidden_size, output_size)
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(self, x):
return x * (1 - x)
def feed_forward(self, X):
self.hidden_layer = self.sigmoid(np.dot(X, self.weights1))
self.output = self.sigmoid(np.dot(self.hidden_layer, self.weights2))
return self.output
def backpropagation(self, X, y, output):
output_error = y - output
output_delta = output_error * self.sigmoid_derivative(output)
hidden_error = output_delta.dot(self.weights2.T)
hidden_delta = hidden_error * self.sigmoid_derivative(self.hidden_layer)
self.weights1 += X.T.dot(hidden_delta)
self.weights2 += self.hidden_layer.T.dot(output_delta)
def train(self, X, y):
output = self.feed_forward(X)
self.backpropagation(X, y, output)
X = np.array([[0,0,1], [0,1,1], [1,0,1], [1,1,1]])
y = np.array([[0,1,1,0]]).T
nn = NeuralNetwork(3, 5, 1)
for i in range(10000):
nn.train(X, y)
print(nn.feed_forward(np.array([1,0,0])))
```
这是一个简单的三层神经网络,它可以学习XOR问题。我们使用sigmoid函数作为激活函数,并使用反向传播算法来更新权重。
阅读全文