Tensorflow入门——分类问题cross_entropy的选择

in #cn-stem5 years ago (edited)


image source by Samuel Zeller from unsplash.com

Tensorflow中有一大堆cross_entropy损失函数用于处理分类问题,初学者往往会一脸懵逼,不知道如何选择。

  • tf.losses.softmax_cross_entropy
  • tf.losses.sparse_softmax_cross_entropy
  • tf.losses.sigmoid_cross_entropy
  • tf.contrib.losses.softmax_cross_entropy
  • tf.contrib.losses.sigmoid_cross_entropy
  • tf.nn.softmax_cross_entropy_with_logits
  • tf.nn.sigmoid_cross_entropy_with_logits
  • ….

1. 名词解释

其实如果我们理解了里面出现的几个关键词,很多问题就一目了然了。

  • Logit (Score)

    分类器给(比如图片)属于每个类别所打的分数

  • Softmax

    将Logit的分数转换成概率,属于每个类别的概率,数值0到1之间

  • Sigmoid

    与Softmax功能一样将Logit的分数转换成概率,只不过Sigmoid仅支持类别个数为2二分类问题,Softmax支持更多类别的分类问题。

  • Onehot (lables)

    一种只用0和1的编码方式,比如有三类,非Onehot的标签可以标为0,1和2。转换成Onehot之后就分别变成[1,0,0],[0,1,0]和[0,01]了。

  • Cross-Entropy(交叉熵)

    计算分类器算出的属于各个类的概率,与(Onehot)标签的差距,用于评价分类器表现

注意所有的损失函数都接受Logits而不必手动通过sigmoid或者softmax转换成概率

2. Sigmoid vs Softmax

正如前面提到,如果是二分问题可以选用Sigmoid的损失函数,如果类别大于两个,最好选用Softmax。

读者应该知道这下面两个怎么选了吧

3. nn and Logits

tf.nn.sigmoid_cross_entropy_with_logitstf.losses.sigmoid_cross_entropy的差别是,前者输出的是一堆Logits向量,后者输出的是一个数loss

f.losses.sigmoid_cross_entropy = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits)

4. Weight

tf.losses.sigmoid_cross_entropy 和 tf.losses.softmax_cross_entropy 都支持权重Weight,默认Weight为1,当w为标量的时候

tf.losses.sigmoid_cross_entropy(weight = w) = w* tf.losses.sigmoid_cross_entropy(weight = 1)

当W为向量的时候,权重加在每一个logits上再Reduce Mean.

f.losses.sigmoid_cross_entropy(weight = W) = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits*W)

加上权重之后,在训练的时候能使某些sample比其他更加重要。

关于tf.nn.weighted_cross_entropy_with_logits` 有一个pos_weight 与前面讲到的sample Weight不同,这个pos_weight是Class Weight, 用来加权类别的,对于 unbalanced数据(一个类别的数据量明显大于另一个类别)非常有用。

5. Sparse

Sparse的 softmax cross_entropy与普通的softmax cross唯一的区别是,其标签没有Onehot编码。

在类别数量巨大的时候,这种方式可以减少内存占用。

6. Sampled Softmax

另外一种减少内存占用的方式,直接对类别进行抽样训练。注意这些loss函数仅能在训练的时候使用,验证的时候不要使用。sampled softmax function如下


参考资料

https://stackoverflow.com/questions/47034888/how-to-choose-cross-entropy-loss-in-tensorflow

https://www.tensorflow.org/api_docs/


同步到我的简书
https://www.jianshu.com/u/bd506afc6fc1

Sort:  




This post has been voted on by the SteemSTEM curation team and voting trail in collaboration with @curie.

If you appreciate the work we are doing then consider voting both projects for witness by selecting stem.witness and curie!

For additional information please join us on the SteemSTEM discord and to get to know the rest of the community!

吃了吗?欢迎在steemauto里设置跟赞 @cnbuddy 给整个cn区点赞倘若你想让我隐形,请回复“取消”。

Coin Marketplace

STEEM 0.20
TRX 0.13
JST 0.029
BTC 67120.19
ETH 3459.44
USDT 1.00
SBD 2.72