tensorflow里提供了两个方便计算交叉熵的函数
import tensorflow as tf
#使用tf.nn.sparse_softmax_cross_entropy_with_logits时,labels为类别号
labels=tf.constant([2,0]) #labels的空间大小为3,样本为2和0
predict_logits=tf.constant([[2.0,-1.0,3.0],[1.0,0.0,-0.5]])
loss1=tf.nn.sparse_softmax_cross_entropy_with_logits(labels=labels,logits=predict_logits)
#使用tf.nn.softmax_cross_entropy_with_logits需要将labels以概率分布(即one-hot编码)的形式给出
labels=tf.constant([[0.0,0.0,1.0],[1.0,0.0,0.0]])
loss2=tf.nn.softmax_cross_entropy_with_logits(labels=labels,logits=predict_logits)
sess=tf.Session()
print(sess.run(loss1))
print(sess.run(loss2))
输出:[0.32656264 0.4643688 ]