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

LSTM多分类任务Reshape函数偶发失效、DataFrame无reshape属性报错求解

问题重现代码
Xres1.shape
# 输出:(291676, 15)

yres1.shape
# 输出:(291676,)

n_samples, n_feats = Xres1.shape[0], Xres1.shape[1]

Xres1 = Xres1.reshape((n_samples, n_feats, 1))

yres1 = to_categorical(yres1, 4)

model = Sequential()

model.add(LSTM(n_feats, input_shape=(n_feats, 1)))

model.add(Dense(20))
model.add(Dense(60))
model.add(Dense(80))
model.add(Dense(90))
model.add(Dense(4, activation='softmax'))

model.compile(loss='categorical_crossentropy', optimizer='adam')

model.fit(Xres1, yres1, epochs=300, batch_size=15, verbose=2)
报错信息

AttributeError: DataFrame object has no attribute reshape

报错原因

报错的核心是Xres1变量类型不稳定:

  • 运行正常时,Xres1是Numpy数组,Numpy数组原生支持reshape方法
  • 报错时,Xres1是Pandas的DataFrame对象,DataFrame本身没有内置reshape方法
    偶发的原因通常是上游数据处理逻辑的输出类型不统一,部分流程返回DataFrame,部分流程返回Numpy数组。
修复方案

优先选择第一种方案,兼容性最高:

  • 方案一:调用reshape前统一转换为Numpy数组
    将reshape相关代码修改为如下形式即可,Pandas 0.24及以上版本推荐用to_numpy()方法:
    # 替换原有的Xres1 = Xres1.reshape((n_samples, n_feats, 1))
    Xres1 = Xres1.to_numpy().reshape((n_samples, n_feats, 1))
    # 低版本Pandas可以用values属性替代
    # Xres1 = Xres1.values.reshape((n_samples, n_feats, 1))
    
    如果后续to_categorical也出现偶发报错,可以用同样方法处理yres1:
    yres1 = to_categorical(yres1.to_numpy(), 4)
    
  • 方案二:上游数据输出时统一类型
    在生成Xres1的处理环节就直接转换为Numpy数组,后续所有处理逻辑都不再保留DataFrame结构,从根源避免类型混乱。
  • 排查方案:如果需要定位上游哪个环节修改了变量类型,可以在reshape代码前加一行类型打印,出问题时快速定位:
    print(type(Xres1))
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 03:06:03