这是我的第238篇原创文章。
一、引言
多层长短期记忆网络(Multiple Layer Long Short-Term Memory,简称多层LSTM)是一种深度学习模型,通常用于处理序列数据。在多层LSTM中,多个LSTM层依次堆叠在一起,前一层的输出作为后一层的输入。每一层都可以学习不同抽象级别的特征表示,使得模型能够更好地理解数据的复杂结构和模式。
通过堆叠多个LSTM层,模型可以学习更加复杂和抽象的序列特征,从而提高模型的表达能力和预测性能。然而,需要注意的是,增加层数也会增加模型的复杂度和训练时间,有时也可能导致过拟合问题,因此在实际应用中需要进行适当的调参和模型选择。
二、实现过程
2.1 读取数据集
# 读取数据集
data = pd.read_csv('data.csv')
# 将日期列转换为日期时间类型
data['Month'] = pd.to_datetime(data['Month'])
# 将日期列设置为索引
data.set_index('Month', inplace=True)
data:
2.2 划分数据集
# 拆分数据集为训练集和测试集
train_size = int(len(data) * 0.8)
train_data = data[:train_size]
test_data = data[train_size:]
# 绘制训练集和测试集的折线图
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()
共144条数据,8:2划分:训练集115,测试集29。
训练集和测试集:
2.3 归一化
# 将数据归一化到 0~1 范围
scaler = MinMaxScaler()
train_data_scaler = scaler.fit_transform(train_data.values.reshape(-1, 1))
test_data_scaler = scaler.transform(test_data.values.reshape(-1, 1))
2.4 构造数据集
# 定义滑动窗口函数
def create_dataset(data, look_back=1):
pass
# 定义滑动窗口大小
window_size = 2
# 创建滑动窗口数据集
X_train, Y_train = create_sliding_windows(train_data_scaler, window_size)
X_test, Y_test = create_sliding_windows(test_data_scaler, window_size)
# 将数据集转换为 LSTM 模型所需的形状(样本数,时间步长,特征数)
X_train = np.reshape(X_train, (X_train.shape[0], window_size, 1))
X_test = np.reshape(X_test, (X_test.shape[0], window_size, 1))
2.5 建立模拟合模型进行预测
# 构建 多层LSTM 模型
model = Sequential()
model.add(LSTM(4, input_shape=(window_size, 1), return_sequences=True))
model.add(LSTM(4))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
# 训练 多层LSTM 模型
model.fit(X_train, Y_train, epochs=100, batch_size=32)
# 使用 多层LSTM 模型进行预测
train_predictions = model.predict(X_train)
test_predictions = model.predict(X_test)
# 反归一化预测结果
train_predictions = scaler.inverse_transform(train_predictions)
test_predictions = scaler.inverse_transform(test_predictions)
test_predictions:
2.6 预测效果展示
# 绘制测试集预测结果的折线图
plt.figure(figsize=(10, 6))
plt.plot(test_data, label='Actual')
plt.plot(list(test_data.index)[-len(test_predictions):], test_predictions, label='Predicted')
plt.xlabel('Month')
plt.ylabel('Passengers')
plt.title('Actual vs Predicted')
plt.legend()
plt.show()
测试集真实值与预测值:
# 绘制原始数据、训练集预测结果和测试集预测结果的折线图
plt.figure(figsize=(10, 6))
plt.plot(data, label='Actual')
plt.plot(list(train_data.index)[look_back:train_size], train_predictions, label='Training Predictions')
plt.plot(list(test_data.index)[-(len(test_data)-look_back):], test_predictions, label='Testing Predictions')
plt.xlabel('Year')
plt.ylabel('Passenger Count')
plt.title('International Airline Passengers - Actual vs Predicted')
plt.legend()
plt.show()
原始数据、训练集预测结果和测试集预测结果:
作者简介:
读研期间发表6篇SCI数据挖掘相关论文,现在某研究院从事数据算法相关科研工作,结合自身科研实践经历不定期分享关于Python、机器学习、深度学习、人工智能系列基础知识与应用案例。致力于只做原创,以最简单的方式理解和学习,关注我一起交流成长。需要数据集和源码的小伙伴可以关注底部公众号添加作者微信。