Calculating Cross Entropy in TensorFlow
In addition to Don's answer (+1), this answer written by mrry may interest you, as it gives the formula to calculate the cross entropy in TensorFlow:
An alternative way to write:
xent = tf.nn.softmax_cross_entropy_with_logits(logits, labels)
...would be:
softmax = tf.nn.softmax(logits) xent = -tf.reduce_sum(labels * tf.log(softmax), 1)
However, this alternative would be (i) less numerically stable (since the softmax may compute much larger values) and (ii) less efficient (since some redundant computation would happen in the backprop). For real uses, we recommend that you use
tf.nn.softmax_cross_entropy_with_logits()
.
Like they say, you can't spell "softmax_cross_entropy_with_logits" without "softmax". Softmax of [0.45]
is [1]
, and log(1)
is 0
.
Measures the probability error in discrete classification tasks in which the classes are mutually exclusive (each entry is in exactly one class). For example, each CIFAR-10 image is labeled with one and only one label: an image can be a dog or a truck, but not both.
NOTE: While the classes are mutually exclusive, their probabilities need not be. All that is required is that each row of
labels
is a valid probability distribution. If they are not, the computation of the gradient will be incorrect.If using exclusive
labels
(wherein one and only one class is true at a time), seesparse_softmax_cross_entropy_with_logits
.WARNING: This op expects unscaled logits, since it performs a
softmax
onlogits
internally for efficiency. Do not call this op with the output ofsoftmax
, as it will produce incorrect results.
logits
andlabels
must have the same shape[batch_size, num_classes]
and the same dtype (eitherfloat16
,float32
, orfloat64
).