python实现bp神经网络
时间: 2023-07-07 16:24:19 浏览: 100
以下是一个简单的 Python 实现 BP 神经网络的示例代码:
```python
import numpy as np
class NeuralNetwork:
def __init__(self, inputs, hidden, outputs):
self.inputs = inputs
self.hidden = hidden
self.outputs = outputs
self.weights1 = np.random.rand(self.inputs, self.hidden)
self.weights2 = np.random.rand(self.hidden, self.outputs)
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_sum = np.dot(X, self.weights1)
self.activated_hidden = self.sigmoid(self.hidden_sum)
self.output_sum = np.dot(self.activated_hidden, self.weights2)
self.activated_output = self.sigmoid(self.output_sum)
return self.activated_output
def backward(self, X, y, o):
self.o_error = y - o
self.o_delta = self.o_error * self.sigmoid_derivative(o)
self.z2_error = self.o_delta.dot(self.weights2.T)
self.z2_delta = self.z2_error * self.sigmoid_derivative(self.activated_hidden)
self.weights1 += X.T.dot(self.z2_delta)
self.weights2 += self.activated_hidden.T.dot(self.o_delta)
def train(self, X, y):
o = self.feed_forward(X)
self.backward(X, y, o)
def save_weights(self, model):
np.save(model, [self.weights1, self.weights2])
def load_weights(self, model):
self.weights1, self.weights2 = np.load(model)
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([[0], [1], [1], [0]])
NN = NeuralNetwork(2, 3, 1)
for i in range(10000):
NN.train(X, y)
if i % 500 == 0:
print("Iteration ", i)
print("Input: \n", X)
print("Actual Output: \n", y)
print("Predicted Output: \n", NN.feed_forward(X))
print("Loss: \n", np.mean(np.square(y - NN.feed_forward(X))))
print("\n")
NN.save_weights("model.npy")
```
在这个示例中,我们使用了一个包含 2 个输入、3 个隐藏单元和 1 个输出的神经网络。我们使用 sigmoid 激活函数和均方误差(MSE)作为损失函数。训练时,我们使用反向传播算法来更新权重,并使用 feed_forward 函数来进行前向传播预测。最后,我们使用 save_weights 和 load_weights 函数来保存和加载模型权重。
阅读全文