BP神经网络模型的代码
时间: 2023-07-09 13:52:35 浏览: 81
以下是一个简单的BP神经网络模型的Python代码,包括前向传播和反向传播:
```python
import numpy as np
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.weights_input_hidden = np.random.randn(self.input_size, self.hidden_size)
self.bias_hidden = np.random.randn(self.hidden_size)
self.weights_hidden_output = np.random.randn(self.hidden_size, self.output_size)
self.bias_output = np.random.randn(self.output_size)
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def forward(self, inputs):
# 前向传播
hidden = self.sigmoid(np.dot(inputs, self.weights_input_hidden) + self.bias_hidden)
output = self.sigmoid(np.dot(hidden, self.weights_hidden_output) + self.bias_output)
return output
def sigmoid_derivative(self, x):
return x * (1 - x)
def backward(self, inputs, targets, learning_rate):
# 反向传播
hidden = self.sigmoid(np.dot(inputs, self.weights_input_hidden) + self.bias_hidden)
output = self.sigmoid(np.dot(hidden, self.weights_hidden_output) + self.bias_output)
output_error = targets - output
output_delta = output_error * self.sigmoid_derivative(output)
hidden_error = np.dot(output_delta, self.weights_hidden_output.T)
hidden_delta = hidden_error * self.sigmoid_derivative(hidden)
self.weights_hidden_output += learning_rate * np.dot(hidden.T, output_delta)
self.bias_output += learning_rate * np.sum(output_delta, axis=0)
self.weights_input_hidden += learning_rate * np.dot(inputs.T, hidden_delta)
self.bias_hidden += learning_rate * np.sum(hidden_delta, axis=0)
def train(self, inputs, targets, num_epochs, learning_rate):
for i in range(num_epochs):
self.backward(inputs, targets, learning_rate)
def predict(self, inputs):
return self.forward(inputs)
```
使用方法:
```python
# 创建神经网络模型
nn = NeuralNetwork(input_size=2, hidden_size=4, output_size=1)
# 训练模型
inputs = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
targets = np.array([[0], [1], [1], [0]])
nn.train(inputs, targets, num_epochs=10000, learning_rate=0.1)
# 预测
print(nn.predict(np.array([[0, 0], [0, 1], [1, 0], [1, 1]])))
```
阅读全文