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

GRU模型输入维度不匹配报错:expected ndim=3, found ndim=2 求助

GRU模型输入尺寸不匹配问题

模型定义

model_gru = Sequential()

model_gru.add(GRU(128, activation='relu', input_shape=(50, 1), return_sequences=True))
model_gru.add(BatchNormalization())
model_gru.add(Dropout(0.2))

model_gru.add(GRU(64, activation='relu'))
model_gru.add(BatchNormalization())
model_gru.add(Dropout(0.2))

model_gru.add(Dense(32,activation='relu'))
model_gru.add(Dense(5,activation='softmax'))

print(model_gru.summary())

预测代码及报错

运行以下预测代码时出现报错:

model_gru.load_weights(r"C:\Users\Admin/gru_model.h5")
q_test_gru = model_gru.predict(test_data, verbose=0)
y_test_gru = q_test_gru.argmax(1)

报错信息:

ValueError: Input 0 of layer sequential_36 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (None, 50)


解决方法

报错原因

你的GRU模型第一层指定了input_shape=(50, 1),这要求输入必须是3维张量,格式为(批量大小, 时间步长, 特征数)。但当前test_data是2维张量(None, 50),缺少了最后一个特征维度(值为1),所以导致维度不匹配。

修复步骤

给test_data添加最后一个特征维度,有两种简单方式:

  1. 使用np.expand_dims在最后一维扩展:
import numpy as np
test_data = np.expand_dims(test_data, axis=-1)
  1. 使用reshape调整形状:
test_data = test_data.reshape(-1, 50, 1)

其中-1表示让系统自动计算批量大小,保证和原数据的样本数一致。

额外验证

确保你训练模型时,输入数据的格式也是(批量大小, 50, 1),和模型定义的输入形状一致,这样保存的权重才会和预测时的输入维度兼容。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 20:25:46