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

如何输出CNN模型训练结果?35分类模型代码问题排查

多类别CNN模型训练的问题修正与结果查看指南

一、原代码的核心问题

  • 输出层配置错误:原代码最后一层Dense(1, activation='sigmoid')是二分类专属配置。35分类场景下,需要输出35个类别的概率分布,应改为Dense(35, activation='softmax'),softmax会将输出归一化为总和为1的概率值。
  • 损失函数不匹配:binary_crossentropy仅适用于二分类任务,多分类需根据标签格式选择:
    • 若标签是整数编码(如0-34的整数,每个数字对应一个类别),使用sparse_categorical_crossentropy;
    • 若标签是独热编码(如[1,0,...,0]表示第1类),使用categorical_crossentropy。
  • 优化器未导入:代码中直接使用RMSprop但未提前导入,需添加from tensorflow.keras.optimizers import RMSprop。
  • steps_per_epoch设置不合理:该参数应等于训练集总样本数除以batch大小,而非固定写16,否则可能导致训练轮次不完整。

二、修正后的完整代码

假设你的训练集标签为整数编码(多分类任务中最常用的标签格式),修正后的代码如下:

from tensorflow.keras.optimizers import RMSprop
import tensorflow as tf

model = tf.keras.models.Sequential([ 
    tf.keras.layers.Conv2D(16,(3,3),activation = 'relu',input_shape = (200,200,3)),
    tf.keras.layers.MaxPool2D(2,2),
    tf.keras.layers.Conv2D(32,(3,3), activation = 'relu'),
    tf.keras.layers.MaxPool2D(2,2),
    tf.keras.layers.Conv2D(64,(3,3), activation = 'relu'),
    tf.keras.layers.MaxPool2D(2,2),
    tf.keras.layers.Conv2D(128,(3,3), activation = 'relu'),
    tf.keras.layers.MaxPool2D(2,2),
    tf.keras.layers.Conv2D(256,(3,3), activation = 'relu'),
    tf.keras.layers.MaxPool2D(2,2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(512, activation = 'relu', name ='layer1'),
    # 适配35分类的输出层
    tf.keras.layers.Dense(35, activation = 'softmax')
])

# 对应整数编码标签,使用稀疏交叉熵损失
model.compile(loss = 'sparse_categorical_crossentropy',
              optimizer = RMSprop(learning_rate=0.001),
              metrics = ['accuracy'])

# steps_per_epoch设为训练集batch的数量,若train_dataset是按batch划分的Dataset,直接用len即可
model_fit= model.fit(train_dataset, 
                     steps_per_epoch = len(train_dataset),
                     epochs = 100,
                     # 建议添加验证集监控过拟合
                     # validation_data=val_dataset,
                     # validation_steps=len(val_dataset)
                     )

三、训练完成后查看结果的方法

1. 可视化训练历史

model_fit.history存储了每轮训练的损失和准确率数据,可通过matplotlib直观展示:

import matplotlib.pyplot as plt

# 绘制准确率变化曲线
plt.plot(model_fit.history['accuracy'], label='训练准确率')
# 若添加了验证集,可同时绘制验证准确率
# plt.plot(model_fit.history['val_accuracy'], label='验证准确率')
plt.xlabel('训练轮次')
plt.ylabel('准确率')
plt.legend()
plt.show()

# 绘制损失变化曲线
plt.plot(model_fit.history['loss'], label='训练损失')
# plt.plot(model_fit.history['val_loss'], label='验证损失')
plt.xlabel('训练轮次')
plt.ylabel('损失值')
plt.legend()
plt.show()

2. 评估模型泛化能力

用测试集评估模型在 unseen 数据上的性能:

# 假设你已准备好test_dataset测试集
test_loss, test_acc = model.evaluate(test_dataset)
print(f"测试集损失: {test_loss:.4f}")
print(f"测试集准确率: {test_acc:.4f}")

3. 执行样本预测

对单个或批量样本进行预测,获取预测类别:

# 从测试集中取一批样本
for images, labels in test_dataset.take(1):
    predictions = model.predict(images)
    # 取概率最大的类别索引
    predicted_classes = tf.argmax(predictions, axis=1)
    print(f"真实标签: {labels.numpy()}")
    print(f"预测标签: {predicted_classes.numpy()}")

4. 保存与加载模型

训练完成后保存模型,方便后续复用:

# 保存为HDF5格式
model.save('35_class_cnn_model.h5')

# 后续加载模型
loaded_model = tf.keras.models.load_model('35_class_cnn_model.h5')

内容的提问来源于stack exchange,提问作者Nguyễn Khang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 20:06:33