前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >独家 | 教你使用简单神经网络和LSTM进行时间序列预测(附代码)

独家 | 教你使用简单神经网络和LSTM进行时间序列预测(附代码)

作者头像
数据派THU
发布2019-05-21 22:50:54
3.4K0
发布2019-05-21 22:50:54
举报
文章被收录于专栏:数据派THU数据派THU

下载波动性标准普尔500数据集,时间范围是:2011年2月11日至2019年2月11日。我的目标是采用ANN和LSTM来预测波动性标准普尔500时间序列。

首先,我们需要导入以下库:

import pandas as pd

import numpy as np

%matplotlib inline

import matplotlib.pyplot as plt

from sklearn.preprocessing import MinMaxScaler

from sklearn.metrics import r2_score

from keras.models import Sequential

from keras.layers import Dense

from keras.callbacks import EarlyStopping

from keras.optimizers import Adam

from keras.layers import LSTM

并将数据加载到Pandas 的dataframe中。

df = pd.read_csv("vix_2011_2019.csv")

我们可以快速浏览前几行。

print(df.head())

删除不需要的列,然后将“日期”列转换为时间数据类型,并将“日期”列设置为索引。

df.drop(['Open', 'High', 'Low', 'Close', 'Volume'], axis=1, inplace=True)

df['Date'] = pd.to_datetime(df['Date'])

df = df.set_index(['Date'], drop=True)

df.head(10)

接下来,我们绘制一个时间序列线图。

plt.figure(figsize=(10, 6))

df['Adj Close'].plot();

可以看出,“Adj close”数据相当不稳定,既没有上升趋势,也没有下降趋势。

按日期“2018–01–01”将数据拆分为训练集和测试集,即在此日期之前的数据是训练数据,此之后的数据是测试数据,我们再次将其可视化。

split_date = pd.Timestamp('2018-01-01')

df = df['Adj Close']

train = df.loc[:split_date]

test = df.loc[split_date:]

plt.figure(figsize=(10, 6))

ax = train.plot()

test.plot(ax=ax)

plt.legend(['train', 'test']);

我们将训练和测试数据缩放为[-1,1]。

scaler = MinMaxScaler(feature_range=(-1, 1))

train_sc = scaler.fit_transform(train)

test_sc = scaler.transform(test)

获取训练和测试数据。

X_train = train_sc[:-1]

y_train = train_sc[1:]

X_test = test_sc[:-1]

y_test = test_sc[1:]

用于时间序列预测的简单人工神经网络

  • 我们创建一个序列模型。
  • 通过.add()方法添加层。
  • 将“input_dim”参数传递到第一层。
  • 激活函数为线性整流函数Relu(Rectified Linear Unit,也称校正线性单位)。
  • 通过compile方法完成学习过程的配置。
  • 损失函数是mean_squared_error,优化器是Adam。
  • 当监测到loss停止改进时,结束训练。
  • patience =2,表示经过数个周期结果依旧没有改进,此时可以结束训练。
  • 人工神经网络的训练时间为100个周期,每次用1个样本进行训练。

nn_model = Sequential()

nn_model.add(Dense(12, input_dim=1, activation='relu'))

nn_model.add(Dense(1))

nn_model.compile(loss='mean_squared_error', optimizer='adam')

early_stop = EarlyStopping(monitor='loss', patience=2, verbose=1)

history = nn_model.fit(X_train, y_train, epochs=100, batch_size=1, verbose=1, callbacks=[early_stop], shuffle=False)

我不会把整个输出结果打印出来,它早在第19个周期就停了下来。

y_pred_test_nn = nn_model.predict(X_test)

y_train_pred_nn = nn_model.predict(X_train)

print("The R2 score on the Train set is:\t{:0.3f}".format(r2_score(y_train, y_train_pred_nn)))

print("The R2 score on the Test set is:\t{:0.3f}".format(r2_score(y_test, y_pred_test_nn)))

LSTM

LSTM网络的构建和模型编译和人工神经网络相似。

  • LSTM有一个可见层,它有1个输入。
  • 隐藏层有7个LSTM神经元。
  • 输出层进行单值预测。
  • LSTM神经元使用Relu函数进行激活。
  • LSTM的训练时间为100个周期,每次用1个样本进行训练。

lstm_model = Sequential()

lstm_model.add(LSTM(7, input_shape=(1, X_train_lmse.shape[1]), activation='relu', kernel_initializer='lecun_uniform', return_sequences=False))

lstm_model.add(Dense(1))

lstm_model.compile(loss='mean_squared_error', optimizer='adam')

early_stop = EarlyStopping(monitor='loss', patience=2, verbose=1)

history_lstm_model = lstm_model.fit(X_train_lmse, y_train, epochs=100, batch_size=1, verbose=1, shuffle=False, callbacks=[early_stop])

训练早在第10个周期就停了下来。

y_pred_test_lstm = lstm_model.predict(X_test_lmse)

y_train_pred_lstm = lstm_model.predict(X_train_lmse)

print("The R2 score on the Train set is:\t{:0.3f}".format(r2_score(y_train, y_train_pred_lstm)))

print("The R2 score on the Test set is:\t{:0.3f}".format(r2_score(y_test, y_pred_test_lstm)))

训练和测试R^2均优于人工神经网络模型。

比较模型

我们比较了两种模型的测试MSE

nn_test_mse = nn_model.evaluate(X_test, y_test, batch_size=1)

lstm_test_mse = lstm_model.evaluate(X_test_lmse, y_test, batch_size=1)

print('NN: %f'%nn_test_mse)

print('LSTM: %f'%lstm_test_mse)

进行预测

nn_y_pred_test = nn_model.predict(X_test)

lstm_y_pred_test = lstm_model.predict(X_test_lmse)

plt.figure(figsize=(10, 6))

plt.plot(y_test, label='True')

plt.plot(y_pred_test_nn, label='NN')

plt.title("NN's Prediction")

plt.xlabel('Observation')

plt.ylabel('Adj Close Scaled')

plt.legend()

plt.show();

plt.figure(figsize=(10, 6))

plt.plot(y_test, label='True')

plt.plot(y_pred_test_lstm, label='LSTM')

plt.title("LSTM's Prediction")

plt.xlabel('Observation')

plt.ylabel('Adj Close scaled')

plt.legend()

plt.show();

就是这样!在这篇文章中,我们发现了如何采用python语言基于Keras深度学习网络框架,开发用于时间序列预测的人工神经网络和LSTM循环神经网络,以及如何利用它们更好地预测时间序列数据。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-05-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 数据派THU 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 用于时间序列预测的简单人工神经网络
  • LSTM
  • 比较模型
  • 进行预测
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档