bp神经网络回归python源码
时间: 2023-11-10 13:02:51 浏览: 110
以下是一个使用BP神经网络进行回归的Python源码示例:
```python
import numpy as np
import matplotlib.pyplot as plt
# 定义BP神经网络类
class BPNeuralNetwork:
def __init__(self, input_size, hidden_size, output_size):
# 随机初始化权重
self.weights_ih = np.random.randn(hidden_size, input_size)
self.weights_ho = np.random.randn(output_size, hidden_size)
self.bias_h = np.random.randn(hidden_size, 1)
self.bias_o = np.random.randn(output_size, 1)
# 定义sigmoid激活函数
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
# 定义前向传播函数
def forward(self, inputs):
hidden = self.sigmoid(self.weights_ih @ inputs + self.bias_h)
output = self.sigmoid(self.weights_ho @ hidden + self.bias_o)
return output
# 定义反向传播函数
def backward(self, inputs, targets, learning_rate):
# 前向传播
hidden = self.sigmoid(self.weights_ih @ inputs + self.bias_h)
output = self.sigmoid(self.weights_ho @ hidden + self.bias_o)
# 计算误差
error = targets - output
# 更新权重和偏置
gradient_output = output * (1 - output) * error
gradient_hidden = hidden * (1 - hidden) * (self.weights_ho.T @ gradient_output)
self.weights_ho += learning_rate * gradient_output @ hidden.T
self.weights_ih += learning_rate * gradient_hidden @ inputs.T
self.bias_o += learning_rate * gradient_output
self.bias_h += learning_rate * gradient_hidden
# 定义训练函数
def train(self, inputs, targets, epochs, learning_rate):
for i in range(epochs):
for j in range(len(inputs)):
self.backward(inputs[j], targets[j], learning_rate)
# 定义预测函数
def predict(self, inputs):
return self.forward(inputs)
# 示例用法
inputs = np.array([[0], [1], [2], [3], [4], [5]])
targets = np.array([[0], [1], [4], [9], [16], [25]])
# 创建BP神经网络对象
network = BPNeuralNetwork(input_size=1, hidden_size=4, output_size=1)
# 训练网络
network.train(inputs, targets, epochs=10000, learning_rate=0.1)
# 预测并打印结果
for input in inputs:
output = network.predict(input)
print(f"Input: {input}, Predicted Output: {output}")
# 绘制拟合曲线
plt.plot(inputs, targets, 'ro', label='True')
plt.plot(inputs, [network.predict(input) for input in inputs], label='Predicted')
plt.legend()
plt.show()
```
这段代码实现了一个简单的BP神经网络进行回归的例子。首先定义了一个BPNeuralNetwork类,其中包括初始化权重、定义激活函数、前向传播函数、反向传播函数、训练函数和预测函数等方法。接下来创建了一个示例输入和目标输出,然后创建一个BP神经网络对象并对其进行训练。最后使用训练好的神经网络进行预测,并绘制出拟合曲线。
阅读全文