You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用TimeseriesGenerator训练LSTM时出现KeyError:4的问题排查

LSTM模型KeyError:4报错原因与修复方案

报错核心原因

  1. 未定义lag变量:LSTM层的input_shape=(lag, input_features)中lag未赋值,它应当等于TimeseriesGenerator的length参数(即4),导致模型输入形状与生成器输出不匹配,触发索引错误。
  2. 目标变量格式错误:将train_data_y转为DataFrame后,TimeseriesGenerator处理标签时易因索引匹配逻辑触发KeyError,numpy数组才是更适配的标签格式。
  3. 任务与组件不匹配:
    • 用MSE损失做回归任务,但Dense层用sigmoid激活(输出限定0-1),若目标变量不在该范围会引发逻辑冲突;
    • accuracy是分类任务指标,不适合回归场景。

修复后的完整代码

import keras
import pandas as pd
import numpy as np
from keras.layers import LSTM, Dense
from keras.preprocessing.sequence import TimeseriesGenerator

# 读取数据(保留原有读取逻辑)
df = pd.DataFrame(df)

# 设置时间索引
df.index = df['PeriodStart'].astype('datetime64')
df.drop(columns=['PeriodStart'], inplace=True)

# 转换为numpy数组,避免DataFrame索引问题
train_data = df.values
train_data_y = df.iloc[:, -1].values

# 定义时序生成器参数
seq_length = 4
ts_generator = TimeseriesGenerator(train_data, train_data_y, length=seq_length, batch_size=8)

input_features = train_data.shape[1]
mse_loss = keras.losses.MeanSquaredError()

# 构建模型
model = keras.Sequential()
# 使用定义好的seq_length作为输入序列长度,LSTM默认激活为tanh,更适合该层特性
model.add(LSTM(32, input_shape=(seq_length, input_features)))
# 回归任务用线性激活(默认可不显式声明)
model.add(Dense(1))

# 替换为回归任务适用的评估指标
model.compile(loss=mse_loss, optimizer='adam', metrics=['mae'])
training_history = model.fit(ts_generator)
print(training_history)

关键修改说明

  • 将输入数据和标签转为numpy数组,消除DataFrame索引带来的匹配问题;
  • 定义seq_length变量替代未声明的lag,保证模型输入形状与生成器输出的序列长度一致;
  • 移除Dense层的sigmoid激活,适配回归任务的输出需求;
  • 将评估指标从accuracy改为mae(平均绝对误差),符合回归任务的评估逻辑。

内容的提问来源于stack exchange,提问作者abigmugofcoffee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 06:23:28