参考基于 Keras 的 LSTM 时间序列分析——以苹果股价预测为例
######################导入库##########################
import os
os.environ['KERAS_BACKEND']='tensorflow'
import keras
import tensorflow as tf
from keras import optimizers#优化器
from keras.models import Sequential, load_model
from keras.layers import Dense, LSTM
from keras.layers import Dropout
1层LSTM
def lstm_single(x,y,hidden_cell,epoch,batch_size,verbose):
#verbose=0不显示训练进度,verbose=2显示训练进度和每个epoch所需时间
model = Sequential()
model.add(LSTM(hidden_cell, input_shape=(x.shape[1],1)))
model.add(Dense(1))
adam=optimizers.Adam(learning_rate=0.01)
model.compile(loss='mean_squared_error', optimizer=adam)
model.fit(x,y, epochs=epoch, batch_size=batch_size, verbose=verbose)
#loss=model.history.history['loss']#记录模型模型的损失函数值
return model
4层LSTM
def lstm_4layer(x,y,hidden_cell,epoch,batch_size,verbose):
model = Sequential()
model.add(LSTM(units=hidden_cell,return_sequences=True,input_shape=(x.shape[1], 1)))
model.add(Dropout(0.2))#可有可无,
model.add(LSTM(units=hidden_cell,return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(units=hidden_cell,return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(units=hidden_cell))
model.add(Dropout(0.2))
model.add(Dense(units=1))
adam=optimizers.Adam(learning_rate=0.01)
model.compile(loss='mean_squared_error', optimizer=adam)
#上面两行可以用下面这行代替,但是下面这行不能修改学习率
#model.compile(optimizer='adam',loss='mean_squared_error')
model.fit(x,y,epochs=epoch,batch_size=batch_size,verbose=verbose)
return model
参数初始化
'''变量初始化'''
import numpy as np
x_train=np.random.random(size=(300,5,1))
y_train=np.random.random(300)
x_test=np.random.random(size=(100,5,1))
y_test=np.random.random(100)
hidden_cell,epoch,batch_size,verbose=5,100,1,0
#hidden_cell是隐层节点数,epoch是最大训练次数,batch_size我说不清,只知batch_size越大训练越快,但是精度下降,verbose=0不会显示训练过程,=1或者=2会显示训练过程batch_size和verbose有默认值
模型训练
x=x_train;y=y_train
hidden_cell,epoch,batch_size,verbose=5,100,1,0
model=lstm_4layer((x,y,hidden_cell,epoch,batch_size,verbose))
绘制模型训练过程损失值变化情况
plt.plot(model.history.history['loss'])
plt.xlabel('epochs')
plt.ylabel('loss')
使用训练好的模型预测
ypre=model.predict(x_test,y_test)