在卷积神经网络(tensorflow)中计算损失函数时如何获得预测?

How to get prediction when computing loss function in convolutional neural network (tensorflow)?

我按照以下步骤使用 tensorflow 构建了一个卷积神经网络: https://www.tensorflow.org/tutorials/estimators/cnn

我想用我自己的损失函数计算损失,因此需要在每个训练步骤中获得每个 class 的预测概率。 从 Tensorflow 教程中,我知道我可以使用 "tf.nn.softmax(logits)" 获得这些概率,但是这个 returns 是一个张量,我不知道如何从这个张量中提取实际的概率。谁能告诉我如何获得这些概率,以便计算损失函数?

这就是您计算 softmax 并随后获得概率的方式:

# Probabities for each element in the batch for each class.
softmax = tf.nn.softmax(logits, axis=1)
# For each element in the batch return the element that has the maximal probability
predictions = tf.argmax(softmax, axis=1)

但是,请注意,您不需要预测来计算损失函数,您需要实际概率。如果您想计算其他指标,则可以使用预测(准确度、精确度、召回率等指标)。 softmax 张量,包含每个 类 的实际概率。例如,假设您在一个批次中有 2 个元素,并且您正在尝试预测三分之一 类,softmax 将为您提供以下内容:

# Logits with random numbers
logits = np.array([[24, 23, 50], [50, 30, 32]], dtype=np.float32)
tf.nn.softmax(logits, axis=1)
# The softmax returns
# [[5.1090889e-12 1.8795289e-12 1.0000000e+00]
#  [1.0000000e+00 2.0611537e-09 1.5229979e-08]]
# If we sum the probabilites for each batch they should sum up to one
tf.reduce_sum(softmax, axis=1)
# [1. 1.]

根据您对损失函数的想象,这应该是正确的:

first_second = tf.nn.l2_loss(softmax[0] - softmax[1])
first_third = tf.nn.l2_loss(softmax[0] - softmax[2])
divide_and_add_m = tf.divide(first_second, first_third) + m
loss = tf.maximum(0.0, 1 - tf.reduce_sum(divide_and_add_m))