如何将输出张量转换为单热张量?

jol*_*lly 5 python tensorflow

我需要计算softmax输出与目标的损失.我的目标是[0,0,1],输出是[0.3,0.3,0.4]为此目的,预测是正确的.但是,低于类型的成本函数不能解释这种准确性

self._output = output = tf.nn.softmax(y)
self._cost = cost = tf.reduce_mean(tf.square( output - tf.reshape(self._targets, [-1])))
Run Code Online (Sandbox Code Playgroud)

如何在TF本身轻松地将输出[0.3,0.3,0.4]转换为[0,0,1]?

kev*_*man 12

用于比较两个概率分布的典型损失函数称为交叉熵.TensorFlow具有tf.nn.softmax_cross_entropy_with_logits函数,可实现该丢失.在您的情况下,您可以简单地做:

self._cost = tf.nn.softmax_cross_entropy_with_logits(
                 y, tf.reshape(self._targets, [-1]))
Run Code Online (Sandbox Code Playgroud)

但是如果你真的想要转换[0.3, 0.3, 0.4]为一个单一的表示用于不同的目的,你可以使用tf.one_hot如下函数:

sess = tf.InteractiveSession()
a = tf.constant([0.3, 0.3, 0.4])
one_hot_a = tf.one_hot(tf.nn.top_k(a).indices, tf.shape(a)[0])
print(one_hot_a.eval())
# prints [[ 0.  0.  1.]]
Run Code Online (Sandbox Code Playgroud)