51

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

 4 years ago
source link: https://www.tuicool.com/articles/e2MJree
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

a6VZjab.png!web图片来源:Pixabay 本文的目的是演示人工神经网络(Artificial Neural Network ,ANN)和长短期记忆循环神经网络(Long Short-Term Memory Recurrent Neural Network ,LSTM RNN)工作过程,使您能够在现实生活中使用它们,并对时间序列数据建立最简单的ANN和LSTM循环神经网络。

人工神经网络(Artificial Neural Network ,ANN)

https://en.wikipedia.org/wiki/Artificial_neural_network

长短期记忆循环神经网络(Long Short-Term Memory Recurrent Neural Network ,LSTM RNN)

https://en.wikipedia.org/wiki/Long_short-term_memory

数据

CBOE(Chicago Board Options Exchange,芝加哥期权交易所)波动性指数是用来衡量标准普尔500指数期权的一种常用隐含波动率,以其代号VIX(Volatility Index,也称“恐惧指数”)而闻名。

CBOE(Chicago Board Options Exchange,芝加哥期权交易所)波动性指数

https://en.wikipedia.org/wiki/VIX

芝加哥期权交易所CBOE实时计算出VIX指数后,将其推出。

芝加哥期权交易所

https://en.wikipedia.org/wiki/Chicago_Board_Options_Exchange

可以从这里(https://ca.finance.yahoo.com/quote/%5Evix/history?ltr=1)下载波动性标准普尔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())

NnyiqyR.png!web

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

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)

MFNVbmy.png!web

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

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

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

yUNVfay.png!web

可以看出,“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']);

AbquEzB.png!web

我们将训练和测试数据缩放为[-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) RZzUZf7.png!web

我不会把整个输出结果打印出来,它早在第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)))

NjMfqqr.png!web

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])

ZFzYvue.png!web

训练早在第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)))

aeieumN.png!web

训练和测试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)

V3qmqyM.png!web

进行预测

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();

ymYzQfR.png!web

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循环神经网络,以及如何利用它们更好地预测时间序列数据。

Jupyter笔记本可以在Github上找到。星期一快乐!

原文标题:

An Introduction on Time Series Forecasting with Simple Neural Networks & LSTM

原文链接:

https://www.kdnuggets.com/2019/04/introduction-time-series-forecasting-simple-neural-networks-lstm.html


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK