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

Keras多输入模型训练报层输入形状不兼容ValueError如何解决

TensorFlow Keras多输入模型维度不匹配错误排查

问题现象

执行模型训练语句时抛出维度不匹配错误:

model_history = model_final.fit([X_weather, X_soil], y,batch_size=16, epochs=100)

报错信息:

ValueError: Input 0 of layer "model_1" is incompatible with the layer: expected shape=(None, 5312), found shape=(None, 168)

已知输入数据原始维度:

X_weather.shape
# 输出 (25345, 168)
X_soil.shape
# 输出 (25345, 66)

错误根因

共有2处核心错误导致该问题:

  • 模型实例化时入参配置错误:构建Model对象时,inputs参数错误传入了经过网络层计算后的中间张量model_1D、model_s,而非最初定义的原始输入层input1、input2。此时模型会将经过Flatten层输出、维度为5312的model_1D作为第一个输入端口,和传入的shape为(None,168)的X_weather维度完全不匹配,直接触发报错。
  • 输入数据缺少Conv1D要求的通道维度:代码中定义输入层shape为(168,1)、(66,1),要求输入是3维格式(样本数, 序列长度, 特征通道数),但原始X_weather、X_soil均为2维格式,缺少最后一维的通道维度,即使修正模型入参也会触发维度不匹配问题。

修正步骤

  1. 修正Model实例化的输入参数,将inputs替换为最初定义的两个原始输入层:
    把原代码中
    model_final = Model(inputs=[model_1D, model_s], outputs=[output])
    
    修改为
    model_final = Model(inputs=[input1, input2], outputs=[output])
    
  2. 为输入数据补充最后一维通道,匹配输入层形状要求,在训练前执行以下代码处理数据:
    import numpy as np
    X_weather = np.expand_dims(X_weather, axis=-1)
    X_soil = np.expand_dims(X_soil, axis=-1)
    
    处理后数据维度为:X_weather (25345,168,1)、X_soil (25345,66,1),和输入层定义完全对齐。

修正后完整可运行核心代码

input1 = Input(shape=(168,1))
input2 = Input(shape=(66,1))
model_1D = Conv1D(16, kernel_size= 9 , strides=1, activation='relu')(input1)
model_1D = tf.keras.layers.AveragePooling1D(pool_size= 2, strides=2)(model_1D)
model_1D = Conv1D(32, kernel_size= 3 , strides=1, activation='relu')(model_1D)
model_1D = tf.keras.layers.AveragePooling1D(pool_size= 2, strides=2)(model_1D)
model_1D = Conv1D(48, kernel_size= 3 , strides=1, activation='relu')(model_1D)
model_1D = tf.keras.layers.AveragePooling1D(pool_size= 2, strides=2)(model_1D)
model_1D = Conv1D(64, kernel_size= 3 , strides=1, activation='relu')(model_1D)
model_1D = tf.keras.layers.AveragePooling1D(pool_size= 2, strides=2)(model_1D)
model_1D = Flatten()(model_1D)
model_s = Dense(10 , activation='relu')(input2)
model_s = Dense(10 , activation='relu')(model_s)
model_s = Flatten()(model_s)
merged = Concatenate()([model_1D, model_s])
output = Dense(128, activation='relu')(merged)
output = Dense(32 , activation='relu')(output)
output = Dense(1 , activation='relu')(output)
# 修正模型入参
model_final = Model(inputs=[input1, input2], outputs=[output])

model_final.compile(
    optimizer = RMSprop(learning_rate=0.02,rho=0.9,epsilon=None,decay=0),
    loss = 'mean_squared_error',
    metrics=['accuracy']
)

# 补充数据维度
import numpy as np
X_weather = np.expand_dims(X_weather, axis=-1)
X_soil = np.expand_dims(X_soil, axis=-1)

model_history = model_final.fit([X_weather, X_soil], y,batch_size=16, epochs=100)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 02:39:09