如何在卷积神经网络(tensorflow)计算损失函数时,你得到的预测?

问题描述 投票:0回答:1

我内置有tensorflow卷积神经网络通过以下步骤:https://www.tensorflow.org/tutorials/estimators/cnn

我想计算我自己的损失函数的损失,因此需要得到每个类的预测出现概率在每个训练阶段。从Tensorflow教程中,我知道我可以得到这些出现概率与“tf.nn.softmax(logits)”,然而,这会返回一个张量,我不知道如何从这个张量提取实际出现概率。谁能告诉我怎样才能得到这些出现概率,所以我可以计算我的损失函数?

python tensorflow conv-neural-network prediction loss-function
1个回答
0
投票

这是你如何计算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))
© www.soinside.com 2019 - 2024. All rights reserved.