python代码实现BP神经网络时间序列预测多维数据输出
时间: 2023-07-31 17:04:59 浏览: 307
神经网络时间序列预测 python
4星 · 用户满意度95%
下面是一个简单的Python代码实现BP神经网络时间序列预测多维数据输出:
```python
import numpy as np
import pandas as pd
# 读取数据
data=pd.read_csv('./data.csv')
data=data.values
# 数据预处理
def preprocess(data):
data=data.astype(float)
max_data=np.max(data,axis=0)
min_data=np.min(data,axis=0)
data=(data-min_data)/(max_data-min_data)
return data,max_data,min_data
# 构造训练集和测试集
def create_dataset(dataset, look_back=1, look_forward=1):
X, Y = [], []
for i in range(len(dataset)-look_back-look_forward+1):
a = dataset[i:(i+look_back), :]
X.append(a)
Y.append(dataset[(i+look_back):(i+look_back+look_forward), :])
return np.array(X), np.array(Y)
# 设置随机种子,确保每次训练结果一致
np.random.seed(7)
# 数据预处理
data,max_data,min_data=preprocess(data)
# 构造训练集和测试集
look_back = 3
look_forward = 2
train_size = int(len(data) * 0.67)
test_size = len(data) - train_size
train, test = data[0:train_size,:], data[train_size:len(data),:]
trainX, trainY = create_dataset(train, look_back, look_forward)
testX, testY = create_dataset(test, look_back, look_forward)
# 创建BP神经网络模型
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Flatten
from keras.layers import LSTM
from keras.layers import TimeDistributed
from keras.layers import Dropout
model = Sequential()
model.add(LSTM(64, input_shape=(look_back, trainX.shape[2]), return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(32))
model.add(Dropout(0.2))
model.add(Dense(look_forward*trainY.shape[2]))
# 模型编译
model.compile(loss='mean_squared_error', optimizer='adam')
# 模型训练
model.fit(trainX, trainY.reshape(trainY.shape[0],look_forward*trainY.shape[2]), epochs=100, batch_size=16, verbose=2)
# 模型预测
trainPredict = model.predict(trainX)
testPredict = model.predict(testX)
# 反归一化
trainPredict=trainPredict*(max_data-min_data)+min_data
trainY=trainY*(max_data-min_data)+min_data
testPredict=testPredict*(max_data-min_data)+min_data
testY=testY*(max_data-min_data)+min_data
# 输出结果
print('Train Mean Absolute Error:', np.mean(np.abs(trainPredict - trainY)))
print('Train Root Mean Squared Error:',np.sqrt(np.mean(np.square(trainPredict - trainY))))
print('Test Mean Absolute Error:', np.mean(np.abs(testPredict - testY)))
print('Test Root Mean Squared Error:',np.sqrt(np.mean(np.square(testPredict - testY))))
```
其中,`data.csv`为输入数据文件,`look_back`为历史时间步长,`look_forward`为预测时间步长。在代码中,我们使用LSTM神经网络模型进行时间序列预测,并使用均方误差作为损失函数进行模型训练。最后,我们输出模型的训练和测试结果。
阅读全文