计算机系统应用教程网站

网站首页 > 技术文章 正文

【Python时序预测系列】LSTM实现时序数据多输入单输出多步预测

btikc 2024-12-15 11:35:43 技术文章 50 ℃ 0 评论

这是我的第321篇原创文章。

一、引言

单站点多变量输入单变量输出多步预测问题----基于LSTM实现。

多输入就是输入多个特征变量

单输出就是预测出一个标签的结果

多步就是利用过去N天预测未来M天的结果

二、实现过程

2.1 读取数据集

df=pd.read_csv("data.csv", parse_dates=["Date"], index_col=[0])
print(df.shape)
print(df.head())
fea_num = len(df.columns)

df:

2.2 划分数据集

# 拆分数据集为训练集和测试集
test_split=round(len(df)*0.20)
df_for_training=df[:-test_split]
df_for_testing=df[-test_split:]


# 绘制训练集和测试集的折线图
plt.figure(figsize=(10, 6))
plt.plot(train_data, label='Training Data')
plt.plot(test_data, label='Testing Data')
plt.xlabel('Year')
plt.ylabel('Passenger Count')
plt.title('International Airline Passengers - Training and Testing Data')
plt.legend()
plt.show()

共5203条数据,8:2划分:训练集4162,测试集1041。

训练集和测试集:

2.3 归一化

# 将数据归一化到 0~1 范围(整体一起做归一化)
scaler = MinMaxScaler(feature_range=(0,1))
df_for_training_scaled = scaler.fit_transform(df_for_training)
df_for_testing_scaled=scaler.transform(df_for_testing)

2.4 构造LSTM数据集(时序-->监督学习)

def split_series(series, n_past, n_future):
    pass

# 假设给定过去 10 天的观察结果,我们需要预测接下来的 3 天观察结果
n_past = 10
n_future = 3
n_features = fea_num
# # 将数据集转换为 LSTM 模型所需的形状(样本数,时间步长,特征数)
X_train, y_train = split_series(df_for_training_scaled,n_past, n_future)
X_train = X_train.reshape((X_train.shape[0], X_train.shape[1],n_features))
y_train = y_train.reshape((y_train.shape[0], y_train.shape[1], 1))
X_test, y_test = split_series(df_for_testing_scaled,n_past, n_future)
X_test = X_test.reshape((X_test.shape[0], X_test.shape[1],n_features))
y_test = y_test.reshape((y_test.shape[0], y_test.shape[1], 1))

print("trainX Shape-- ",X_train.shape)
print("trainY Shape-- ",y_train.shape)
print("testX Shape-- ",X_test.shape)
print("testY Shape-- ",y_test.shape)

假设给定过去 10 天的观察结果,预测接下来的 3 天观察结果:

取出df_for_training_scaled第【1-10】行第【1-5】列的10条数据作为X_train[0],取出df_for_training_scaled第【11-13】行第【1】列的3条数据作为y_train[0];

取出df_for_training_scaled第【2-11】行第【1-5】列的10条数据作为X_train[1],取出df_for_training_scaled第【12-14】行第【1】列的3条数据作为y_train[1];

取出df_for_training_scaled第【4150-4159】行第【1-5】列的10条数据作为X_train[4149],取出df_for_training_scaled第【4160-4162】行第【1】列的3条数据作为y_train[4149];

依此类推。最终构造出的训练集数量(4150)比划分时候的训练集数量(4162)少一个12(n_past+n_future-1)。

X_train是一个(4150,10,5)的三维数组,三个维度分布表示(样本数量,步长,特征数),每一个样本比如X_train[0]是一个(10,5)二维数组表示(步长,特征数),这也是seq2seq模型每一步的输入。

y_train是一个(4150,3,1)的三维数组,三个维度分布表示(样本数量,步长,标签数),每一个样本比如y_train[0]是一个(3,1)二维数组表示(步长,标签数),这也是seq2seq模型每一步的输出。

2.5 建立模拟合模型

encoder_inputs = Input(shape=(n_past, n_features))
encoder_l1 = LSTM(100, return_state=True)
encoder_outputs1 = encoder_l1(encoder_inputs)
encoder_states1 = encoder_outputs1[1:]
decoder_inputs = RepeatVector(...)(...)
decoder_l1 = LSTM(100, return_sequences=True)(...)
decoder_outputs1 = TimeDistributed(Dense(1))(decoder_l1)
model_e1d1 = Model(encoder_inputs,decoder_outputs1)
model_e1d1.summary()

这是一个多输入多输出的 seq2seq 模型:具有一个编码器层和一个解码器层的序列到序列模型。

进行训练:

reduce_lr = tf.keras.callbacks.LearningRateScheduler(lambda x: 1e-3 * 0.90 ** x)
model_e1d1.compile(optimizer=tf.keras.optimizers.Adam(), loss=tf.keras.losses.Huber())
history_e1d1=model_e1d1.fit(X_train,y_train,epochs=25,validation_data=(X_test,y_test),batch_size=32,verbose=0,callbacks=[reduce_lr])

2.6 进行预测

进行预测,上面我们分析过模型每一步的输入是一个(10,5)二维数组表示(步长,特征数),模型每一步的输出是是一个(3,1)二维数组表示(步长,标签数):

prediction_test = model.predict(testX)

如果直接model.predict(testX),testX的形状是(1029,10,5),是一个批量预测,输出prediction_test是一个(1029,3,1)的三维数组,prediction_test[0]就是第一个样本未来3天1个标签的预测结果,prediction_test[1]就是第二个样本未来3天1个标签的预测结果...

看一下第一个测试集样本的预测情况:

pred_e1d1_0 = pred_e1d1[0]
pred_e1d1_0 = np.repeat(pred_e1d1_0,fea_num, axis=-1)
pred_e1d1_0_T = scaler.inverse_transform(pred_e1d1_0)[:,0]
print(pred_e1d1_0_T)


y_test_0 = y_test[0]
y_test_0 = np.repeat(y_test_0,fea_num, axis=-1)
y_test_0_T = scaler.inverse_transform(y_test_0)[:,0]
print(y_test_0_T)

预测值(未来3天变量的预测):

真实值(未来3天变量的真值):

作者简介: 读研期间发表6篇SCI数据算法相关论文,目前在某研究院从事数据算法相关研究工作,结合自身科研实践经历持续分享关于Python、数据分析、特征工程、机器学习、深度学习、人工智能系列基础知识与案例。关注gzh:数据杂坛,获取数据和源码学习更多内容。

原文链接:

【Python时序预测系列】基于LSTM实现时序数据多输入单输出多步预测(案例+源码)

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表