TensorFlow Sequential模型多图像训练报错及批量传参咨询
问题:TensorFlow Sequential模型批量传入图像训练报错
场景描述
传入多张尺寸一致的图像训练Sequential模型时触发报错,但单张图像训练完全正常。
报错信息
ValueError: Layer "sequential_28" expects 1 input(s), but it received 2 input tensors. Inputs received: [<tf.Tensor 'IteratorGetNext:0' shape=(None, 549, 549, 3) dtype=float32>, <tf.Tensor 'IteratorGetNext:1' shape=(None, 549, 549, 3) dtype=float32>]
相关代码
import tensorflow as tf import matplotlib.pyplot as plt import numpy as np from tensorflow import keras from tensorflow.keras import layers, datasets, models # Load the template image template_image = tf.keras.preprocessing.image.load_img('Template.jpg') template_array = tf.keras.preprocessing.image.img_to_array(template_image) # Load the actual image actual_image = tf.keras.preprocessing.image.load_img('Actual.jpg') actual_array = tf.keras.preprocessing.image.img_to_array(actual_image) # Create a model model = tf.keras.Sequential([ layers.InputLayer(input_shape=(template_array.shape)), layers.Conv2D(16, (3, 3), activation='relu'), layers.MaxPooling2D((2, 2)), layers.Conv2D(32, (3, 3), activation='relu'), layers.MaxPooling2D((2, 2)), layers.Flatten(), layers.Dense(64, activation='relu'), layers.Dense(2, activation='softmax'), ]) # Compile the model model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) model.summary() for layer in model.layers: print(layer.output_shape) template_array = template_array.reshape((1, 549, 549, 3)) actual_array = actual_array.reshape((1, 549, 549, 3)) train_x = [template_array, actual_array] y_train = np.array([1,0]) y_train = y_train.reshape(1,2) train_y = [y_train, y_train] print("X shape is: ") print(template_array.shape) print("Y shape is: ") print(y_train) # Train the model model.fit(x=train_x, y=train_y, epochs=10) # Make predictions predictions = model.predict([actual_array]) # Check for incorrect or missing parts for i in range(len(predictions)): if predictions[i][0] > predictions[i][1]: print('Part {} is missing or incorrect'.format(i))
问题根源
你错误地将训练数据封装成了多个单样本张量的列表,而Sequential单输入模型只接受形状为(样本数, 高度, 宽度, 通道数)的单一批量张量。标签数据也被错误封装成列表,不符合批量训练的格式要求。
解决方案
修改数据准备逻辑,将多个单样本张量合并为一个批量张量,同时调整标签为匹配的独热编码格式:
# 合并两个单样本图像为批量张量,最终shape=(2, 549, 549, 3) train_x = np.concatenate([template_array, actual_array], axis=0) # 调整标签为独热编码格式,每个样本对应一个分类数组,shape=(2, 2) # 这里假设template对应类别[1,0],actual对应[0,1],可根据你的实际需求修改 y_train = np.array([[1, 0], [0, 1]]) # 训练模型,直接传入批量张量 model.fit(x=train_x, y=y_train, epochs=10) # 预测时可直接传入单张或批量张量,无需包裹列表 predictions = model.predict(actual_array)
关键说明
- 批量数据格式:使用
np.concatenate在第0轴(样本轴)合并单样本张量,生成符合模型要求的批量输入。 - 标签格式:由于使用
categorical_crossentropy损失,标签必须是独热编码,每个样本对应长度为类别数的数组,批量标签形状为(样本数, 类别数)。 - 模型输入要求:Sequential单输入模型的
fit方法只接受单一输入张量,不能传入多张量列表。
内容的提问来源于stack exchange,提问作者Eren Ackerman
相关产品推荐
相关产品推荐

