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

Softmax输出置信度判定及Keras双输出模型实现咨询

多类别分类任务的置信度判定与Keras双输出模型实现

一、无额外类别时的置信度判定方法

针对异类样本(如岩石图像)的结果可靠性判断,无需新增无标签类,可采用以下几种实用方案:

  • 最大概率阈值法:设定一个经验阈值(如0.7~0.9),仅当softmax输出的最大概率超过该阈值时,才认为结果可靠。注意需用包含异类样本的验证集调优阈值,避免同类样本被误拒。
  • Logits最大值判定:直接使用pre-softmax层的输出(logits,未归一化的线性输出)的最大值作为置信度指标。异类样本的logits最大值通常远低于同类样本,因为模型对异类无针对性激活,设定合理阈值即可有效区分。
  • 熵值分析:计算softmax输出的熵值,公式为 H = -Σ(p_i * log(p_i))。熵值越高,说明概率分布越均匀,模型对结果越不确定;熵值越低,分布越集中,结果越可靠。可通过验证集确定熵值的判定阈值。
  • 温度校准softmax:推理时引入温度参数T,将softmax计算改为 softmax(logits/T)。当T>1时,概率分布会更平缓,异类样本的最大概率会被显著降低,结合阈值更容易筛选出可靠结果。

二、Keras函数式API实现双输出且冻结pre-softmax层权重

完全可以实现同时输出pre-softmax(logits)和softmax结果,且训练时不更新pre-softmax层的权重,具体代码示例如下:

1. 模型构建

from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense, Activation
from tensorflow.keras.models import Model

# 输入尺寸根据你的任务调整
img_height, img_width = 224, 224
num_classes = 10  # 你的目标类别数

# 输入层
input_layer = Input(shape=(img_height, img_width, 3))

# CNN特征提取部分(根据你的现有模型调整)
x = Conv2D(32, (3, 3), activation='relu')(input_layer)
x = MaxPooling2D(pool_size=(2, 2))(x)
x = Conv2D(64, (3, 3), activation='relu')(x)
x = MaxPooling2D(pool_size=(2, 2))(x)
x = Flatten()(x)
x = Dense(128, activation='relu')(x)

# Pre-softmax层(logits,线性激活)
pre_softmax_layer = Dense(num_classes, activation=None, name='pre_softmax')(x)
# 冻结该层权重,训练时不更新
pre_softmax_layer.trainable = False

# Softmax输出层
softmax_output = Activation('softmax', name='softmax_output')(pre_softmax_layer)

# 构建双输出模型
model = Model(inputs=input_layer, outputs=[pre_softmax_layer, softmax_output])

2. 模型编译与训练

编译时只需关注softmax输出的损失,pre-softmax输出可设置无损失或损失权重为0:

model.compile(optimizer='adam',
              loss={'softmax_output': 'categorical_crossentropy',
                    'pre_softmax': None},  # 忽略pre-softmax的损失
              metrics={'softmax_output': 'accuracy'})

# 训练模型(假设你的训练数据为x_train, y_train,y_train为one-hot编码)
model.fit(x_train, 
          {'softmax_output': y_train, 'pre_softmax': y_train},  # pre-softmax的标签可随便传,因为损失被忽略
          epochs=20,
          batch_size=32,
          validation_split=0.1)

3. 推理使用

推理时会同时得到logits和softmax结果:

logits, softmax_probs = model.predict(test_image)

内容的提问来源于stack exchange,提问作者mahdi bazzi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 16:48:26