用Python做一个BP神经网络预测模型
时间: 2024-02-01 20:04:38 浏览: 86
好的,以下是使用 Python 实现 BP 神经网络预测模型的代码:
首先,我们需要导入相关的库和数据:
```python
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
# 读取数据
data = pd.read_csv('data.csv')
X = data.iloc[:, :-1].values
y = data.iloc[:, -1].values
# 将数据进行归一化处理
scaler = MinMaxScaler()
X = scaler.fit_transform(X)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
```
然后,我们需要定义神经网络模型,并使用反向传播算法进行训练:
```python
class NeuralNetwork:
def __init__(self, layers):
self.layers = layers
self.weights = [np.random.randn(self.layers[i], self.layers[i-1]) for i in range(1, len(self.layers))]
self.biases = [np.random.randn(self.layers[i], 1) for i in range(1, len(self.layers))]
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(self, x):
return x * (1 - x)
def feedforward(self, X):
a = X.T
for i in range(len(self.weights)):
z = np.dot(self.weights[i], a) + self.biases[i]
a = self.sigmoid(z)
return a
def backpropagation(self, X, y):
a = [X.T]
z = []
for i in range(len(self.weights)):
z.append(np.dot(self.weights[i], a[-1]) + self.biases[i])
a.append(self.sigmoid(z[-1]))
delta = [2 * (a[-1] - y.reshape(-1, 1)) * self.sigmoid_derivative(a[-1])]
for i in range(len(self.weights)-1, -1, -1):
delta.insert(0, np.dot(self.weights[i].T, delta[0]) * self.sigmoid_derivative(a[i]))
return delta, z, a
def train(self, X_train, y_train, learning_rate, epochs):
for epoch in range(epochs):
for i in range(X_train.shape[0]):
delta, z, a = self.backpropagation(X_train[i], y_train[i])
for j in range(len(self.weights)):
self.weights[j] -= learning_rate * np.dot(delta[j], a[j].T)
self.biases[j] -= learning_rate * delta[j]
def predict(self, X_test):
y_pred = []
for i in range(X_test.shape[0]):
y_pred.append(self.feedforward(X_test[i]))
return np.array(y_pred).reshape(-1, 1)
```
最后,我们可以使用定义好的神经网络模型进行预测:
```python
# 定义神经网络模型
nn = NeuralNetwork([X.shape[1], 10, 1])
# 训练模型
nn.train(X_train, y_train, learning_rate=0.01, epochs=100)
# 预测测试集数据
y_pred = nn.predict(X_test)
# 输出预测结果
print(y_pred)
```
当然,这只是一个简单的 BP 神经网络预测模型,如果你需要更加精确的预测结果,可以尝试使用其他的神经网络模型或者进行模型调参。
阅读全文