交叉熵cross_entropy的几种使用形式

1. 交叉熵:
交叉熵公式

2. logits:神经网络最后一层的输出

下面看实际中的3种用法:
1.根据定义手动求
2.使用sparse_softmax_cross_entropy_with_logits
3.使用softmax_cross_entropy_with_logits

其中2和3的区别在于sparse要求输入是实数,比如[2,4,6, 344],然后对实数做one_hot,而softmax_cross_entropy_with_logits要求是one_hot输入,即[0,0,1],[0,1,0]等。其它的处理方式一样

import tensorflow as tf

logits = tf.Variable([[0.3, 0.4, 0.6], [0.4, 0.4, 0.5]], dtype=tf.float32)  #shape = (2,3),假设是模型产生的
y = tf.nn.softmax(logits)#做softmax用于手动求交叉熵
y_true = [2, 1] #shape = (2,)用于sparse
y_true_one_hot = tf.one_hot(y_true, 3, on_value=1, off_value=0)#shape=(2,3)

cross_entropy = -tf.reduce_sum(tf.to_float(y_true_one_hot)*tf.log(y),axis=1)
output = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y_true, logits=logits)
output_ = tf.nn.softmax_cross_entropy_with_logits(labels=y_true_one_hot, logits=logits)

with tf.Session() as sess:
    init = tf.global_variables_initializer()
    sess.run(init)
    print(sess.run(y_true_one_hot))
    print(sess.run(cross_entropy))
    print(sess.run(output))
    print(sess.run(output_))

结果:
[[0 0 1]
[0 1 0]]
[ 0.93983102 1.1330688 ]
[ 0.93983102 1.1330688 ]
[ 0.93983102 1.13306868]

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值