这是您计算 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))