CNN模型训练报错:conv2d_6层输入不兼容问题求助
CNN二分类训练报错解决
问题描述
训练CNN模型对1896个文件的二分类数据集进行分类时,训练阶段出现输入维度不匹配报错。
定义的参数
IMAGE_SIZE_1 = 1280 IMAGE_SIZE_2 = 720 BATCH_SIZE=30 EPOCHS = 20 CHANNELS = 2
预处理与数据增强代码
resize_and_rescale = tf.keras.Sequential([ layers.experimental.preprocessing.Resizing(IMAGE_SIZE_1,IMAGE_SIZE_2), layers.experimental.preprocessing.Rescaling(1.0/255) ])
data_argumentation = tf.keras.Sequential([ layers.experimental.preprocessing.RandomFlip("horizontal_and_vertical"), layers.experimental.preprocessing.RandomRotation(0.2) ])
模型构建代码
input_shape = ( BATCH_SIZE,IMAGE_SIZE_1, IMAGE_SIZE_2, CHANNELS) n_classes = 2 model = models.Sequential([ resize_and_rescale, data_argumentation, #Input layer layers.Conv2D(35, (3,3), activation="relu", input_shape = input_shape), layers.MaxPooling2D((2,2)), #Pooling layers.Conv2D(64, (3,3), activation="relu"), layers.MaxPooling2D((2,2)), layers.Conv2D(64, (3,2), activation="relu"), layers.MaxPooling2D((2,2)), layers.Conv2D(64, (3,3), activation="relu"), layers.MaxPooling2D((2,2)), #Flatenning layers.Flatten(), layers.Dense(64,activation="relu"), #Output LAyer layers.Dense(n_classes, activation="softmax") ])
编译与训练代码
model.compile( optimizer="adam", loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False), metrics=["accuracy"])
history = model.fit( train_ds, epochs=EPOCHS, verbose=1, batch_size = BATCH_SIZE, validation_data=val_ds)
报错信息
ValueError: Exception encountered when calling layer 'sequential_3' (type Sequential).
Input 0 of layer "conv2d_6" is incompatible with the layer: expected axis -1 of input shape to have value 2, but received input with shape (None, 1280, 720, 3)
Call arguments received by layer 'sequential_3' (type Sequential):
• inputs=tf.Tensor(shape=(None, 1280, 720, 3), dtype=float32)
• training=True
• mask=None
报错原因
- 通道数不匹配:你定义
CHANNELS=2,但实际输入的是3通道RGB图像,导致Conv2D层期望输入通道为2,却接收到3通道数据。 - input_shape定义错误:Keras中
input_shape不需要包含批量大小(BATCH_SIZE),正确格式应为(高, 宽, 通道数),错误加入BATCH_SIZE会导致输入维度校验失败。
修复方案
1. 修正input_shape定义
移除input_shape中的BATCH_SIZE,同时根据实际数据调整CHANNELS参数:
# 如果是RGB图像,将CHANNELS改为3;如果是自定义2通道数据,保持CHANNELS=2 CHANNELS = 3 input_shape = (IMAGE_SIZE_1, IMAGE_SIZE_2, CHANNELS)
2. 规范模型输入层写法
建议在模型开头显式添加Input层,替代在Conv2D层中指定input_shape,让输入逻辑更清晰:
model = models.Sequential([ layers.Input(shape=input_shape), # 显式指定输入形状 resize_and_rescale, data_argumentation, layers.Conv2D(35, (3,3), activation="relu"), layers.MaxPooling2D((2,2)), layers.Conv2D(64, (3,3), activation="relu"), layers.MaxPooling2D((2,2)), layers.Conv2D(64, (3,2), activation="relu"), layers.MaxPooling2D((2,2)), layers.Conv2D(64, (3,3), activation="relu"), layers.MaxPooling2D((2,2)), layers.Flatten(), layers.Dense(64,activation="relu"), layers.Dense(n_classes, activation="softmax") ])
3. 确认数据集加载的通道数
检查数据集加载代码,确保加载的图像通道数与CHANNELS一致:
# 示例:加载RGB图像(3通道) train_ds = tf.keras.utils.image_dataset_from_directory( train_dir, image_size=(IMAGE_SIZE_1, IMAGE_SIZE_2), batch_size=BATCH_SIZE, color_mode="rgb" # 若为灰度图,改为"grayscale"对应1通道 )
内容的提问来源于stack exchange,提问作者Rafael Vieira
相关产品推荐
相关产品推荐

