bp神经网络预测python源代码
时间: 2023-09-23 07:12:32 浏览: 113
BP神经网络预测代码
以下是一个使用BP神经网络进行预测的Python示例代码:
```python
import numpy as np
# 构造训练数据
train_data = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
train_label = np.array([[0], [1], [1], [0]])
# 定义BP神经网络
class BPNeuralNetwork():
def __init__(self, input_size, hidden_size, output_size, learning_rate):
self.input_size = input_size
self.hidden_size = hidden_size
self.output_size = output_size
self.learning_rate = learning_rate
# 初始化权重
self.weights_input_hidden = np.random.randn(self.input_size, self.hidden_size)
self.weights_hidden_output = np.random.randn(self.hidden_size, self.output_size)
# sigmoid函数
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
# sigmoid函数的导数
def sigmoid_derivative(self, x):
return x * (1 - x)
# 训练网络
def train(self, data, label):
for i in range(len(data)):
# 前向传播
hidden = self.sigmoid(np.dot(data[i], self.weights_input_hidden))
output = self.sigmoid(np.dot(hidden, self.weights_hidden_output))
# 反向传播
output_error = label[i] - 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 += self.learning_rate * hidden.reshape(-1, 1) * output_delta
self.weights_input_hidden += self.learning_rate * data[i].reshape(-1, 1) * hidden_delta
# 预测
def predict(self, data):
hidden = self.sigmoid(np.dot(data, self.weights_input_hidden))
output = self.sigmoid(np.dot(hidden, self.weights_hidden_output))
return output
# 构造BP神经网络
bp_nn = BPNeuralNetwork(2, 4, 1, 0.1)
# 训练BP神经网络
for i in range(10000):
bp_nn.train(train_data, train_label)
# 预测
print(bp_nn.predict(np.array([0, 0])))
print(bp_nn.predict(np.array([0, 1])))
print(bp_nn.predict(np.array([1, 0])))
print(bp_nn.predict(np.array([1, 1])))
```
该示例代码使用BP神经网络来预测XOR运算的结果。代码中首先构造了训练数据和标签,然后定义了一个BPNeuralNetwork类,该类包含了sigmoid函数、sigmoid函数的导数、训练和预测方法。在训练方法中,使用前向传播计算输出值,使用反向传播计算误差并更新权重。在预测方法中,使用前向传播计算输出值。最后,对训练好的BP神经网络进行预测并输出结果。
阅读全文