当前位置:   article > 正文

【Python时序预测系列】基于多层LSTM实现多变量时间序列预测(案例+源码)_lstm 分类 python 代码

lstm 分类 python 代码

这是我的第260篇原创文章。

一、引言

      单站点多变量单步预测问题----基于多层LSTM实现多变量时间序列预测股票价格。

二、实现过程

2.1 读取数据集

  1. df=pd.read_csv("data.csv", parse_dates=["Date"], index_col=[0])
  2. print(df.shape)
  3. print(df.head())
  4. fea_num = len(df.columns)

df:

图片

2.2 划分数据集

  1. # 拆分数据集为训练集和测试集
  2. test_split=round(len(df)*0.20)
  3. df_for_training=df[:-test_split]
  4. df_for_testing=df[-test_split:]
  5. # 绘制训练集和测试集的折线图
  6. plt.figure(figsize=(10, 6))
  7. plt.plot(train_data, label='Training Data')
  8. plt.plot(test_data, label='Testing Data')
  9. plt.xlabel('Year')
  10. plt.ylabel('Passenger Count')
  11. plt.title('International Airline Passengers - Training and Testing Data')
  12. plt.legend()
  13. plt.show()

共5203条数据,8:2划分:训练集4162,测试集1041。

训练集和测试集:

图片

2.3 归一化

  1. # 将数据归一化到 0~1 范围
  2. scaler = MinMaxScaler(feature_range=(0,1))
  3. df_for_training_scaled = scaler.fit_transform(df_for_training)
  4. df_for_testing_scaled=scaler.transform(df_for_testing)

2.4 构造LSTM数据集(时序-->监督学习)

  1. def createXY(dataset,n_past):
  2. pass
  3. window_size = 30
  4. trainX,trainY=createXY(df_for_training_scaled,window_size)
  5. testX,testY=createXY(df_for_testing_scaled,window_size)
  6. # 将数据集转换为 LSTM 模型所需的形状(样本数,时间步长,特征数)
  7. trainX = np.reshape(trainX, (trainX.shape[0], window_size, 5))
  8. testX = np.reshape(testX, (testX.shape[0], window_size, 5))
  9. print("trainX Shape-- ",trainX.shape)
  10. print("trainY Shape-- ",trainY.shape)
  11. print("testX Shape-- ",testX.shape)
  12. print("testY Shape-- ",testY.shape)

滑动窗口设置为30:

图片

2.5 建立模拟合模型

  1. my_model = Sequential()
  2. my_model.add(Input(shape=(window_size, fea_num)))
  3. my_model.add(LSTM(50, return_sequences=True))
  4. my_model.add(Dropout(0.2))
  5. my_model.add(LSTM(50))
  6. my_model.add(Dropout(0.2))
  7. my_model.add(Dense(1))
  8. my_model.compile(loss='mse', optimizer='adam', metrics=['accuracy'])
  9. my_model.summary()
  10. my_model.fit(trainX, trainY)

图片

2.6 进行预测

  1. prediction_test=my_model.predict(testX)
  2. prediction_train=my_model.predict(trainX)

2.7 预测效果展示

  1. plt.plot(df_for_training.index[window_size:,], original_train, color = 'red', label = '真实值')
  2. plt.plot(df_for_training.index[window_size:,], pred_train, color = 'blue', label = '预测值')
  3. plt.title('Stock Price Prediction')
  4. plt.xlabel('Time')
  5. plt.xticks(rotation=45)
  6. plt.ylabel('Stock Price')
  7. plt.legend()
  8. plt.show()

训练集真实值与预测值:

图片

  1. plt.plot(df_for_testing.index[window_size:,], original_test, color = 'red', label = '真实值')
  2. plt.plot(df_for_testing.index[window_size:,], pred_test, color = 'blue', label = '预测值')
  3. plt.title('Stock Price Prediction')
  4. plt.xlabel('Time')
  5. plt.xticks(rotation=45)
  6. plt.ylabel('Stock Price')
  7. plt.legend()
  8. plt.show()

测试集真实值与预测值:

图片

2.8 评估指标

图片

作者简介:

读研期间发表6篇SCI数据挖掘相关论文,现在某研究院从事数据算法相关科研工作,结合自身科研实践经历不定期分享关于Python、机器学习、深度学习、人工智能系列基础知识与应用案例。致力于只做原创,以最简单的方式理解和学习,关注我一起交流成长。需要数据集和源码的小伙伴可以关注底部公众号添加作者微信。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/612993
推荐阅读
相关标签
  

闽ICP备14008679号