分别用CNN、GRU和LSTM实现时间序列预测(2019-04-06)

卷积神经网络(CNN)、长短期记忆网络(LSTM)以及门控单元网络(GRU)是最常见的一类算法,在kaggle比赛中经常被用来做预测和回归。今天,我们就抛砖引玉,做一个简单的教程,如何用这些网络预测时间序列。因为是做一个简单教程,所以本例子中网络的层数和每层的神经元个数没有调试到最佳。根据不同的数据集,同学们可以自己调网络结构和具体参数。


1.环境搭建

我们运行的环境是下载anaconda,然后在里面安装keras,打开spyder运行程序即可。其中下载anaconda和安装keras的教程在我们另一个博客“用CNN做电能质量扰动分类(2019-03-28)”中写过了,这里就不赘述了。

2.数据集下载

下载时间序列数据集和程序。其中,网盘连接是:

https://pan.baidu.com/s/1TASK3gMZoDFvoE89LzR-5A,密码是“o0sl”。

“nihe.csv”是我自己做的一个时间序列的数据集,一共有1000行4列其中,1-3列可以认为是X,第4列认为是Y。我们现在要做的就是训练3个X和Y之间的关系,然后给定X去预测Y。

3.预测

把下载的nihe.csv文件放到spyder 的默认路径下,我的默认路径是“D:\Matlab2018a\42”,新建一个.py文件,把程序放进去,运行即可。

4.CNN,LSTM,GRU预测时间序列的程序

1)GRU的程序

#1. load dataset

from pandas import read_csv

dataset = read_csv('nihe.csv')

values = dataset.values

#2.tranform data to [0,1]

from sklearn.preprocessing importMinMaxScaler

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

XY= scaler.fit_transform(values)

X= XY[:,0:3]    

Y = XY[:,3]

#3.split into train and test sets

n_train_hours = 950

trainX = X[:n_train_hours, :]

trainY =Y[:n_train_hours]

testX = X[n_train_hours:, :]

testY =Y[n_train_hours:]

train3DX =trainX.reshape((trainX.shape[0], 1, trainX.shape[1]))

test3DX = testX.reshape((testX.shape[0],1, testX.shape[1]))

#4. Define Network

from keras.models importSequential

from keras.layers import Dense

from keras.layers.recurrentimport GRU

model = Sequential()

model.add(GRU(units=5,input_shape=(train3DX.shape[1],train3DX.shape[2]),return_sequences=True))

model.add(GRU(units=3))

model.add(Dense(units=4,kernel_initializer='normal',activation='relu'))    

model.add(Dense(units=1,kernel_initializer='normal',activation='sigmoid')) 

#最后输出层1个神经元和输出的个数对应

# 5. compile the network

model.compile(loss='mae',optimizer='adam')

# 6. fit the network

history =model.fit(train3DX,trainY, epochs=100, batch_size=10,validation_data=(test3DX,testY), verbose=2, shuffle=False)

# 7. evaluate the network

from matplotlib import pyplot

pyplot.plot(history.history['loss'],label='train')

pyplot.plot(history.history['val_loss'],label='test')

pyplot.legend()

pyplot.show()

#8. make a prediction and invertscaling for forecast

from pandas import concat

forecasttestY0 =model.predict(test3DX)

inv_yhat=np.concatenate((testX,forecasttestY0), axis=1)

inv_y =scaler.inverse_transform(inv_yhat)

forecasttestY = inv_y[:,3]

# calculate RMSE

from math import sqrt

from sklearn.metrics importmean_squared_error

actualtestY=values[n_train_hours:,3]

rmse = sqrt(mean_squared_error(forecasttestY,actualtestY))

print('Test RMSE: %.3f' % rmse)

#plot the testY and actualtestY

pyplot.plot(actualtestY,label='train')

pyplot.plot(forecasttestY,label='test')

pyplot.legend()

pyplot.show()


2)LSTM的程序

#1. load dataset

from pandas import read_csv

dataset = read_csv('nihe.csv')

values = dataset.values

#2.tranform data to [0,1]

from sklearn.preprocessing importMinMaxScaler

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

XY= scaler.fit_transform(values)

X= XY[:,0:3]   

Y = XY[:,3]

#3.split into train and test sets

n_train_hours = 950

trainX = X[:n_train_hours, :]

trainY =Y[:n_train_hours]

testX = X[n_train_hours:, :]

testY =Y[n_train_hours:]

train3DX =trainX.reshape((trainX.shape[0], 1, trainX.shape[1]))

test3DX = testX.reshape((testX.shape[0],1, testX.shape[1]))

#4. Define Network

from keras.models importSequential

from keras.layers import Dense

from keras.layers.recurrentimport LSTM

model = Sequential()

model.add(LSTM(units=5,input_shape=(train3DX.shape[1],train3DX.shape[2]),return_sequences=True))

model.add(LSTM(units=3))

model.add(Dense(units=4,kernel_initializer='normal',activation='relu'))    

model.add(Dense(units=1,kernel_initializer='normal',activation='sigmoid')) 

#最后输出层1个神经元和输出的个数对应

# 5. compile the network

model.compile(loss='mae',optimizer='adam')

# 6. fit the network

history =model.fit(train3DX,trainY, epochs=100, batch_size=10,validation_data=(test3DX,testY), verbose=2, shuffle=False)

# 7. evaluate the network

from matplotlib import pyplot

pyplot.plot(history.history['loss'],label='train')

pyplot.plot(history.history['val_loss'],label='test')

pyplot.legend()

pyplot.show()

#8. make a prediction and invertscaling for forecast

from pandas import concat

import numpy as np

forecasttestY0 =model.predict(test3DX)

#forecasttestY= np.expand_dims(a,axis=1)

inv_yhat=np.concatenate((testX,forecasttestY0), axis=1)

inv_y =scaler.inverse_transform(inv_yhat)

forecasttestY = inv_y[:,3]

# calculate RMSE

from math import sqrt

from sklearn.metrics importmean_squared_error

actualtestY=values[n_train_hours:,3]

rmse =sqrt(mean_squared_error(forecasttestY, actualtestY))

print('Test RMSE: %.3f' % rmse)

#plot the testY and actualtestY

pyplot.plot(actualtestY,label='train')

pyplot.plot(forecasttestY,label='test')

pyplot.legend()

pyplot.show()



3)CNN和LSTM的合并

#1. load dataset

from pandas import read_csv

dataset = read_csv('nihe.csv')

values = dataset.values

#2.tranform data to [0,1]  3个属性,第4个是待预测量

from sklearn.preprocessing importMinMaxScaler

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

XY= scaler.fit_transform(values)

X= XY[:,0:3]   

Y = XY[:,3]

#3.split into train and test sets

950个训练集,剩下的都是验证集

n_train_hours = 950

trainX = X[:n_train_hours, :]

trainY =Y[:n_train_hours]

testX = X[n_train_hours:, :]

testY =Y[n_train_hours:]

#LSTM的输入格式要3维,因此先做变换

train3DX =trainX.reshape((trainX.shape[0], 1, trainX.shape[1]))

test3DX =testX.reshape((testX.shape[0], 1, testX.shape[1]))

#4. Define Network

from keras.models importSequential

from keras.layers import Dense

from keras.layers.recurrentimport LSTM

from keras.layers.convolutionalimport Conv1D

from keras.layers.convolutionalimport MaxPooling1D

from keras.layers import Flatten

model = Sequential()

model.add(Conv1D(filters=10,kernel_size=1, padding='same', strides=1, activation='relu',input_shape=(1,3)))

model.add(MaxPooling1D(pool_size=1))

model.add(LSTM(units=3,return_sequences=True))

model.add(Flatten())

#可以把LSTM和Flatten删除,仅保留LSTM

#model.add(LSTM(units=3)) 

model.add(Dense(5,activation='relu'))

#在lstm层之后可以添加隐含层,也可以不加,直接加输出层

#model.add(Dense(units=4,kernel_initializer='normal',activation='relu')) 

model.add(Dense(units=1,kernel_initializer='normal',activation='sigmoid'))      

 #最后输出层1个神经元和输出的个数对应

# 5. compile the network

model.compile(loss='mae',optimizer='adam')

# 6. fit the network

history =model.fit(train3DX,trainY, epochs=100, batch_size=10,validation_data=(test3DX,testY), verbose=2, shuffle=False)

# 7. evaluate the network

from matplotlib import pyplot

pyplot.plot(history.history['loss'],label='train')

pyplot.plot(history.history['val_loss'],label='test')

pyplot.legend()

pyplot.show()

#8. make a prediction and invertscaling for forecast

from pandas import concat

import numpy as np

forecasttestY0 =model.predict(test3DX)

inv_yhat=np.concatenate((testX,forecasttestY0), axis=1)

inv_y =scaler.inverse_transform(inv_yhat)

forecasttestY = inv_y[:,3]

# calculate RMSE

from math import sqrt

from sklearn.metrics importmean_squared_error

actualtestY=values[n_train_hours:,3]

rmse =sqrt(mean_squared_error(forecasttestY, actualtestY))

print('Test RMSE: %.3f' % rmse)

#plot the testY and actualtestY

pyplot.plot(actualtestY,label='train')

pyplot.plot(forecasttestY,label='test')

pyplot.legend()

pyplot.show()

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,809评论 6 513
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,189评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 167,290评论 0 359
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,399评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,425评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,116评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,710评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,629评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,155评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,261评论 3 339
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,399评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,068评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,758评论 3 332
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,252评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,381评论 1 271
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,747评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,402评论 2 358

推荐阅读更多精彩内容