
本文详解为何将多张图像作为 python 列表传入 model.fit() 会报错,并提供正确构建批量输入张量的方法,包括形状调整、数据拼接与标签对齐等关键步骤。
在使用 TensorFlow/Keras 构建 Sequential 模型时,一个常见误区是将多张图像误组织为 Python 列表(如 [img1, img2]),然后直接传给 model.fit(x=...)。这会导致类似以下错误:
ValueError: Layer "sequential_28" expects 1 input(s), but it received 2 input tensors.
根本原因:Keras 将列表中的每个元素视为独立输入流(即模型需设计为多输入架构),而非同一输入通道下的两个样本。而你的 Sequential 模型仅定义了单个 InputLayer,因此只接受一个四维张量,其形状应为 (batch_size, height, width, channels)。
✅ 正确做法是将所有图像沿 batch 维度(axis=0)堆叠,形成统一的 NumPy 数组。例如:
# 确保每张图已是 (1, H, W, C) 形状(含 batch 维) template_array = template_array.reshape((1, 549, 549, 3)) actual_array = actual_array.reshape((1, 549, 549, 3)) # ✅ 正确:沿第 0 轴拼接 → 得到 (2, 549, 549, 3) train_x = np.concatenate([template_array, actual_array], axis=0) # ✅ 标签也需严格对齐:(2,) 或 (2, 2)(one-hot) y_train = np.array([1, 0]) # shape: (2,) # 若使用 categorical_crossentropy,需转为 one-hot: y_train = tf.keras.utils.to_categorical(y_train, num_classes=2) # → (2, 2)
⚠️ 注意事项:
- InputLayer(input_shape=(template_array.shape)) 写法错误:input_shape 应排除 batch 维,即写为 input_shape=(549, 549, 3);
- y_train.reshape(1,2) 会得到 (1,2) 形状,但样本数是 2,标签必须是 (2,) 或 (2,2);
- 实际训练中,建议使用 tf.data.Dataset 或标准 NumPy 数组,避免手动管理维度;
- 多图训练前务必验证 train_x.ndim == 4 且 train_x.shape[0] == len(y_train)。
完整修正后的训练调用如下:
model.fit(
x=train_x, # shape: (2, 549, 549, 3)
y=y_train, # shape: (2, 2) for categorical_crossentropy
epochs=10,
batch_size=2,
verbose=1
)总结:Keras 的 fit() 方法要求 x 是单个张量(非列表),其第一维代表 batch size;多图训练 = 堆叠图像 → 扩展 batch 维 → 对齐标签 → 一次馈送。掌握这一数据组织逻辑,是规模化训练的基础。










