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

使用flow_from_directory训练模型时遇输入形状不兼容ValueError

问题分析与解决方案

这个错误的核心是模型输入层的预期形状和实际传入数据的形状不匹配,哪怕你设置了target_size或添加了转换层,大概率是以下几个环节出了问题,按优先级排查:


1. 先确认模型的真实输入预期

先打印模型的输入形状,搞清楚它到底要什么:

print(model_merged.input_shape)

如果输出是(None, 400, 400, 1),说明你的模型输入层是按400x400定义的——哪怕你现在代码里改了数据尺寸,模型本身的输入要求没变。这种情况要么:

  • 把数据的target_size改成(400,400);
  • 重新定义模型的输入层为Input(shape=(256,256,1)),再重新构建/加载模型。

2. 数据生成环节的隐藏问题

用ImageDataGenerator时的关键遗漏

flow_from_directory默认读取RGB三通道图片,如果你模型要单通道,必须加color_mode='grayscale'参数,否则哪怕你设置了target_size=(256,256),输出的形状也是(batch_size,256,256,3),转单通道时如果逻辑错了就会乱变形状:

train_generator = train_datagen.flow_from_directory(
    '/kaggle/working/images/',
    target_size=(256,256),
    batch_size=batch_size,
    class_mode='categorical',
    subset='training',
    color_mode='grayscale'  # 直接读成单通道,省去后续转换
)

用image_dataset_from_directory时的预处理逻辑错误

你之前加的Reshape、Resize、Permute层完全是错误的,转单通道应该用专门的方法,同时确保尺寸正确:

# 替换你原来的所有转换层逻辑
normalization_layer = tf.keras.layers.Rescaling(1./255)

def preprocess(x, y):
    x = normalization_layer(x)
    # RGB转单通道
    x = tf.image.rgb_to_grayscale(x)
    # 强制确保尺寸是256x256,防止个别图片没被正确resize
    x = tf.image.resize(x, (256,256))
    return x, y

train_ds = train_ds.map(preprocess, num_parallel_calls=AUTOTUNE)
val_ds = val_ds.map(preprocess, num_parallel_calls=AUTOTUNE)

或者更简单,直接在image_dataset_from_directory里加color_mode='grayscale',一步到位读成单通道:

train_ds = tf.keras.utils.image_dataset_from_directory(
  data_dir,
  validation_split=0.2,
  subset="training",
  seed=123,
  image_size=(img_height, img_width),
  batch_size=batch_size,
  color_mode='grayscale'  # 直接读单通道
)

3. 模型结构的衔接问题

看你更新2的模型图,要确保Model B的输入形状和Model A的输出形状完全匹配:

  • 如果Model A的输出是(None,256,256,n),那Model B的输入层必须对应这个形状,不能硬写(256,256,1);
  • 如果你是把Model A的输出作为Model B的输入,要用Model(inputs=modelA.input, outputs=modelB(modelA.output))这种方式正确拼接,避免形状错位。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 15:25:09