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

RNN LSTM序列分类模型输入形状不兼容问题求助

解决LSTM输入形状不匹配的问题

错误核心

你的LSTM层定义的输入形状是(time_steps, features)即(14,10),但你将输入数据Xreshape成了(7263,140,1)——这相当于把每个样本的14个时间步、10个特征,错误转换成了140个时间步、每个时间步1个特征,完全不符合模型的输入要求,因此触发形状不兼容报错。

解决方案

修改X的reshape语句,将原始140列数据(14时间步×10特征)正确转换为(样本数, 时间步, 特征数)的格式:

修改后的核心代码片段

X = final_vectorized.loc[:, final_vectorized.columns != 'converted'].values
# 关键修正:将(7263,140)转换为(7263,14,10),对应14个时间步、每个时间步10个特征
X = np.reshape(X, (7263, time_steps, features))

完整修正代码

epochs = 10
batch_size = 10000
time_steps = 14
features = 10

X = final_vectorized.loc[:, final_vectorized.columns != 'converted'].values
# 修正reshape维度
X = np.reshape(X, (7263, time_steps, features))
Y = final_vectorized.loc[:, 'converted'].values

train_X1 = X[0:2500, :, :]
train_X2 = X[4000:6500, :, :]
train_X = np.concatenate((train_X1, train_X2), axis=0)
# 修正切片:原2501:3999会漏掉第2500个样本,改为2500:4000保证划分无遗漏
test_X = X[2500:4000, :, :]
train_Y1 = Y[0:2500]
train_Y2 = Y[4000:6500]
train_Y = np.concatenate((train_Y1, train_Y2), axis=0)
test_Y = Y[2500:4000]

model = Sequential()
model.add(LSTM(100, dropout=0.2, input_shape=(time_steps, features)))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
print(model.summary())
model.fit(train_X, train_Y, validation_data=(test_X, test_Y), epochs=epochs, batch_size=batch_size)

额外说明

  • 切片索引修正:原代码中test_X=X[2501:3999,:,:]会跳过第2500个样本,改成2500:4000后,训练集(0-2499、4000-6499)和测试集(2500-3999)的划分无遗漏且不重叠。
  • 维度验证:修改后X的形状应为(7263,14,10),与LSTM层要求的输入形状(14,10)(批量维度None自动适配)完全匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 20:48:18