tf.nn.softmax_cross_entropy_with_logits函数
tf.nn.softmax_cross_entropy_with_logits函数在TensorFlow中计算分类问题交叉熵损失函数时会用到。
这个函数的返回值不是一个数,而是一个向量。如果要求最终的交叉熵损失,我们需要再做一步tf.reduce_sum操作,即对向量中的所有元素求和。
让我们以具体示例来说明tf.nn.softmax_cross_entropy_with_logits函数是怎样工作的:
#--coding:utf-8-- """ @author:taoshouzheng @time:2019/3/25 20:29 @email:tsz1216@sina.com """
import tensorflow as tf
"""定义计算图中的计算"""
神经网络的最后一层的输出:三条样本在神经网络中的输出
logits = tf.constant([[1.0, 2.0, 3.0], [1.0, 2.0, 3.0], [1.0, 2.0, 3.0]]) # 常量
样本的真实标签,用one-hot编码形式表示:三条样本的真实标签
y_ = tf.constant([[0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0]])
1(1):softmax操作
y = tf.nn.softmax(logits)
1(2):cross_entropy操作
y_mul = -(y_ * tf.log(y)) # 所有样本的真实标签乘以其预测概率的对数 cross_entropy = tf.reduce_sum(y_mul) # 计算所有元素之和作为损失函数
