Tensorflow中的交叉熵(Cross Entropy)

Tensorflow中的交叉熵(Cross Entropy)

Cross Entropy (Sigmoid)

适用于二分类,输入函数的logitslabels应当是一维的。如果输入One-Hot过的logits,会被当做多个一维分别计算。注意不要将已经通过sigmoid计算得到的数值输入函数,那样会得到错误的结果。

s i g m o i d ( x ) = x ^ = 1 1 + e − x sigmoid(x)=\hat x=\frac{1}{1+e^{-x}} sigmoid(x)=x^=1+ex1
l o s s = − y l o g x ^ − ( 1 − y ) l o g ( 1 − x ^ ) loss=-ylog\hat x - (1-y)log(1-\hat x) loss=ylogx^(1y)log(1x^)
x = [ 5.0 ] , y = [ 1 ] , l o s s = − l o g 1 1 + e − 5 = 0.006715 x=[5.0],y=[1],loss=-log\frac{1}{1+e^{-5}}=0.006715 x=[5.0],y=[1],loss=log1+e51=0.006715
x = [ 5.0 ] , y = [ 0 ] , l o s s = − l o g e − 5 1 + e − 5 = 5.006715 x=[5.0],y=[0],loss=-log\frac{e^{-5}}{1+e^{-5}}=5.006715 x=[5.0],y=[0],loss=log1+e5e5=5.006715
x = [ 5.0 ] , y = [ − 1 ] , l o s s = l o g 1 1 + e − 5 − 2 l o g e − 5 1 + e − 5 = 10.006715 x=[5.0],y=[-1],loss=log\frac{1}{1+e^{-5}}-2log\frac{e^{-5}}{1+e^{-5}}=10.006715 x=[5.0],y=[1],loss=log1+e512log1+e5e5=10.006715

# 3 samples
preds = [5., 5., 5.]
labels = [1., 0., -1.]
loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=preds, labels=labels)

Cross Entropy (Softmax)

适用于多分类,softmax_cross_entropy_with_logits_v2接收的logitslabels至少是二维的,sparse_softmax_cross_entropy_with_logits接收的logits至少是二维的,但labels不是One-Hot的,而是类别的下标,例如 [ 0 , 0 , 1 , 0 ] [0,0,1,0] [0,0,1,0]这样的label就是2(从0开始)。注意不要将已经通过softmax计算得到的数值输入函数,那样会得到错误的结果。

s o f t m a x ( x ) = x ^ i = e x i ∑ k e x k softmax(x)=\hat x_i=\frac{e^{x_i}}{\sum_k e^{x_k}} softmax(x)=x^i=kexkexi
l o s s = − ∑ k y k l o g x ^ i loss=-\sum_k y_k log\hat x_i loss=kyklogx^i
x = [ [ − 1.0 , 1.0 ] ] , y = [ [ 1 , − 1 ] ] , l o s s = − l o g e − 1 e − 1 + e 1 + l o g e 1 e − 1 + e 1 = 2 x=[[-1.0,1.0]], y=[[1,-1]],loss=-log\frac{e^{-1}}{e^{-1}+e^{1}}+log\frac{e^{1}}{e^{-1}+e^{1}}=2 x=[[1.0,1.0]],y=[[1,1]],loss=loge1+e1e1+loge1+e1e1=2
x = [ [ − 1.0 , 1.0 ] ] , y = [ [ 1 , 0 ] ] , l o s s = − l o g e − 1 e − 1 + e 1 = 2.137 x=[[-1.0,1.0]], y=[[1,0]],loss=-log\frac{e^{-1}}{e^{-1}+e^{1}}=2.137 x=[[1.0,1.0]],y=[[1,0]],loss=loge1+e1e1=2.137

# 4 samples
preds = [[10., -10.], [10., -10.], [10., -10.], [10.,-10.]]
labels = [[1., 0.], [1., -1.], [0., 1.], [-1., 1.]]
loss1 = tf.nn.softmax_cross_entropy_with_logits_v2(logits=preds, labels=labels)

labels = np.argmax(labels)
loss1 = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=preds, labels=labels)

参考

Tensorflow sparse_softmax_cross_entropy_with_logits
Tensorflow sigmoid_cross_entropy_with_logits
Tensorflow softmax_cross_entropy_with_logits_v2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值