irpas技术客

时间序列预测——LSTM模型(附代码实现)_噜噜啦啦咯_lstm时间序列预测

大大的周 2741

目录

模型原理

模型实现

导入所需要的库

设置随机数种子

导入数据集

打印前五行数据进行查看

数据处理

归一化处理

查看归一化处理后的数据

将时间序列转换为监督学习问题

打印数据前五行

?划分训练集和测试集

查看划分后的数据维度

搭建LSTM模型

?得到损失图

模型预测

画图展示

得到预测图像?

回归评价指标


模型原理

????????长短时记忆网络( Long short-term memory,LSTM )是一种循环神经网络 (Recurrent neural network, RNN)的特殊变体,具有“门”结构,通过门单元的逻辑控制决定数据是否更新或是选择丢弃,克服了 RNN 权重影响过大、容易产生梯度消失和爆炸的缺点,使网络可以更好、更快地收敛,能够有效提高预测精度。LSTM 拥有三个门, 分别为遗忘门、输入门、输出门,以此决定每一时刻信息记忆与遗忘。输入门决定有多少新的信息加入到细胞当中,遗忘门控制每一时刻信息是否会被遗忘,输出门决定每一时刻是否有信息输出。其基本结构如图所示。

公式如下:

(1)遗忘门

(2)输入门

(3)单元

(4)输出门

(5)最终输出

模型实现 导入所需要的库 import matplotlib.pyplot as plt from pandas import read_csv from pandas import DataFrame from pandas import concat from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.models import Sequential from tensorflow.keras.layers import LSTM,Dense,Dropout from numpy import concatenate from sklearn.metrics import mean_squared_error,mean_absolute_error,r2_score from math import sqrt 设置随机数种子 import tensorflow as tf tf.random.set_seed(2) 导入数据集 qy_data=read_csv(r'C:\Users\HUAWEI\Desktop\abc.csv',parse_dates=['num'],index_col='num') qy_data.index.name='num' #选定索引列 打印前五行数据进行查看

数据处理 # 获取DataFrame中的数据,形式为数组array形式 values = qy_data.values # 确保所有数据为float类型 values = values.astype('float32') 归一化处理

使用MinMaxScaler缩放器,将全部数据都缩放到[0,1]之间,加快收敛。

scaler = MinMaxScaler(feature_range=(0, 1)) scaled = scaler.fit_transform(values) 查看归一化处理后的数据

??

将时间序列转换为监督学习问题

将时间序列形式的数据转换为监督学习集的形式,例如:[[10],[11],[12],[13],[14]]转换为[[0,10],[10,11],[11,12],[12,13],[13,14]],即把前一个数作为输入,后一个数作为对应输出。

def series_to_supervised(data, n_in=1, n_out=1, dropnan=True): n_vars = 1 if type(data) is list else data.shape[1] df = DataFrame(data) cols, names = list(), list() # input sequence (t-n, ... t-1) for i in range(n_in, 0, -1): cols.append(df.shift(i)) names += [('var%d(t-%d)' % (j + 1, i)) for j in range(n_vars)] # forecast sequence (t, t+1, ... t+n) for i in range(0, n_out): cols.append(df.shift(-i)) if i == 0: names += [('var%d(t)' % (j + 1)) for j in range(n_vars)] else: names += [('var%d(t+%d)' % (j + 1, i)) for j in range(n_vars)] # put it all together agg = concat(cols, axis=1) agg.columns = names # drop rows with NaN values if dropnan: agg.dropna(inplace=True) return agg reframed = series_to_supervised(scaled, 2, 1) 打印数据前五行

??

?划分训练集和测试集 # 划分训练集和测试集 values = reframed.values trainNum = int(len(values) * 0.7) train = values[:trainNum,:] test = values[trainNum:, :] 查看划分后的数据维度 print(train_X.shape, train_y.shape) print(test_X.shape, test_y.shape)

?

搭建LSTM模型

初始化LSTM模型,设置神经元核心的个数,迭代次数,优化器等等

model = Sequential() model.add(LSTM(27, input_shape=(train_X.shape[1], train_X.shape[2]))) model.add(Dropout(0.5)) model.add(Dense(15,activation='relu'))#激活函数 model.compile(loss='mae', optimizer='adam') history = model.fit(train_X, train_y, epochs=95, batch_size=2, validation_data=(test_X, test_y), verbose=2,shuffle=False) ?得到损失图

????????

模型预测 y_predict = model.predict(test_X) test_X = test_X.reshape((test_X.shape[0], test_X.shape[2])) 画图展示 plt.figure(figsize=(10,8),dpi=150) plt.plot(inv_y,color='red',label='Original') plt.plot(inv_y_predict,color='green',label='Predict') plt.xlabel('the number of test data') plt.ylabel('Soil moisture') plt.legend() plt.show() 得到预测图像?

将测试集的y值和预测值绘制在同一张图表中

??

回归评价指标 # calculate MSE 均方误差 mse=mean_squared_error(inv_y,inv_y_predict) # calculate RMSE 均方根误差 rmse = sqrt(mean_squared_error(inv_y, inv_y_predict)) #calculate MAE 平均绝对误差 mae=mean_absolute_error(inv_y,inv_y_predict) #calculate R square r_square=r2_score(inv_y,inv_y_predict) print('均方误差MSE: %.6f' % mse) print('均方根误差RMSE: %.6f' % rmse) print('平均绝对误差MAE: %.6f' % mae) print('R_square: %.6f' % r_square)


1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,会注明原创字样,如未注明都非原创,如有侵权请联系删除!;3.作者投稿可能会经我们编辑修改或补充;4.本站不提供任何储存功能只提供收集或者投稿人的网盘链接。

标签: #LSTM时间序列预测 #长短时记忆网络 #LONG #Shortterm #memoryLSTM #是一种循环神经网络 #Recurrent #Neural