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

CNN模型训练报错:Shapes (None,1)与(None,24)不兼容求助

问题分析与解决方案

报错根源

你使用了categorical_crossentropy损失函数,但训练/测试标签train_y_values、test_y_values是一维整数数组(形状(N,)),而模型最后一层输出是25维概率分布(形状(N,25))。categorical_crossentropy要求标签必须是one-hot编码的二维数组(形状(N,25)),因此出现形状不兼容的错误。

另外补充:你的输入图像train_img形状为(27455,28,28),但模型输入要求是(28,28,1),需要先补充通道维度,否则也会触发输入不匹配错误。


解决方案(二选一即可)

方案1:替换损失函数为稀疏分类交叉熵

直接使用sparse_categorical_crossentropy,该损失函数专门适配一维整数标签的多分类任务,无需修改标签格式:

model.compile(loss=tf.keras.losses.sparse_categorical_crossentropy,
              optimizer=tf.keras.optimizers.Adadelta(), 
              metrics=['accuracy'])

同时补充图像通道维度:

import tensorflow as tf
train_img = train_img[..., tf.newaxis]
test_img = test_img[..., tf.newaxis]

方案2:将标签转换为One-Hot编码

如果坚持使用categorical_crossentropy,需要把一维整数标签转为one-hot编码的二维数组:

import tensorflow as tf

# 转换标签为one-hot格式(num_classes需与模型最后一层神经元数一致)
train_y_onehot = tf.keras.utils.to_categorical(train_y_values, num_classes=25)
test_y_onehot = tf.keras.utils.to_categorical(test_y_values, num_classes=25)

# 补充图像通道维度
train_img = train_img[..., tf.newaxis]
test_img = test_img[..., tf.newaxis]

# 使用转换后的标签训练
model.fit(train_img, train_y_onehot, batch_size=64, epochs=5, 
          verbose=1, validation_data=(test_img, test_y_onehot))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 18:26:17