首页 > 解决方案 > 使用二元交叉熵将 DNN 的输出解释为损失

问题描述

我有一个 Tensorflow 图像分类 DNN,它使用二进制交叉熵作为其损失,并在 tf.keras.preprocessing.image_dataset_from_directory 调用中使用相应的标签模式二进制。当我训练模型并对图像进行推理时,预测输出类似于 [[-3.5601902]] 或 [[2.1026382]]。我如何解释它以获取模型分配图像的两个类中的哪一个。我认为答案将是 softmax 函数的实现,但我没有做对。

调用 tf.keras.preprocessing.image_dataset:

train_ds = tf.keras.preprocessing.image_dataset_from_directory(
images_directory,
label_mode="binary",
validation_split=0.2,
subset="training",
seed=123,
image_size=(img_height, img_width),
batch_size=batch_size)

val_ds = tf.keras.preprocessing.image_dataset_from_directory(
images_directory,
label_mode="binary",
validation_split=0.2,
subset="validation",
seed=123,
image_size=(img_height, img_width),
batch_size=batch_size)

和模型

model = Sequential([
layers.experimental.preprocessing.Rescaling(1./255, input_shape=(img_height, img_width, 3)),
layers.Conv2D(16, 3, padding='same', activation='relu'),
layers.MaxPooling2D(),
layers.Conv2D(32, 3, padding='same', activation='relu'),
layers.MaxPooling2D(),
layers.Conv2D(64, 3, padding='same', activation='relu'),
layers.MaxPooling2D(),
layers.Flatten(),
layers.Dense(128, activation='relu'),
layers.Dense(num_classes)
])

model.compile(optimizer='adam',
          loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
          metrics=['accuracy'])

对模型的任何输入也将不胜感激。

标签: pythontensorflowmachine-learning

解决方案


您想要实现的目标有点令人困惑。

如果你正在做一个二元分类(我相信你是),你的输出层的大小不应该是“num_classes”,它应该是 1 并带有激活函数的 sigmod。如果你这样做了,输出“p”将是第 1 类的概率,而 1-“p”是第 0 类的概率。似乎你将一些多分类方法与二元分类混合在一起。

我想关于这些值唯一可以说的是它们是 logit 输出。


推荐阅读