BP神经网络回归预测模型python代码
时间: 2024-04-18 12:21:57 浏览: 211
BP神经网络是一种常用的机器学习算法,用于回归预测模型。下面是一个简单的BP神经网络回归预测模型的Python代码示例:
```python
import numpy as np
# 定义BP神经网络类
class BPNeuralNetwork:
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.weights1 = np.random.randn(self.input_size, self.hidden_size)
self.bias1 = np.zeros((1, self.hidden_size))
self.weights2 = np.random.randn(self.hidden_size, self.output_size)
self.bias2 = np.zeros((1, 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 forward(self, X):
self.hidden_layer_output = self.sigmoid(np.dot(X, self.weights1) + self.bias1)
self.output = np.dot(self.hidden_layer_output, self.weights2) + self.bias2
# 定义反向传播函数
def backward(self, X, y, learning_rate):
# 计算输出层的误差
output_error = y - self.output
output_delta = output_error
# 计算隐藏层的误差
hidden_error = np.dot(output_delta, self.weights2.T)
hidden_delta = hidden_error * self.sigmoid_derivative(self.hidden_layer_output)
# 更新权重和偏置
self.weights2 += learning_rate * np.dot(self.hidden_layer_output.T, output_delta)
self.bias2 += learning_rate * np.sum(output_delta, axis=0, keepdims=True)
self.weights1 += learning_rate * np.dot(X.T, hidden_delta)
self.bias1 += learning_rate * np.sum(hidden_delta, axis=0, keepdims=True)
# 定义训练函数
def train(self, X, y, epochs, learning_rate):
for epoch in range(epochs):
self.forward(X)
self.backward(X, y, learning_rate)
# 定义预测函数
def predict(self, X):
self.forward(X)
return self.output
# 创建BP神经网络对象
input_size = 2
hidden_size = 3
output_size = 1
bpnn = BPNeuralNetwork(input_size, hidden_size, output_size)
# 构造训练数据
X_train = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y_train = np.array([, , , ])
# 训练模型
epochs = 10000
learning_rate = 0.1
bpnn.train(X_train, y_train, epochs, learning_rate)
# 预测新数据
X_test = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
predictions = bpnn.predict(X_test)
print(predictions)
```
这段代码实现了一个简单的BP神经网络回归预测模型。其中,`input_size`表示输入层的大小,`hidden_size`表示隐藏层的大小,`output_size`表示输出层的大小。通过调整这些参数,可以构建不同规模的神经网络模型。训练数据`X_train`和`y_train`用于训练模型,`epochs`表示训练的迭代次数,`learning_rate`表示学习率。最后,使用训练好的模型对新数据`X_test`进行预测,并输出预测结果。
阅读全文