tf.one_hot

什么是onehot:一位有效编码,对每一个样本,如果有n种类别,只有对应类别位置编码为1,其它为0 。ce 损失计算常常用到。
tensorflow 函数
tf.one_hot(
indices,
depth,
on_value=None,
off_value=None,
axis=None,
dtype=None,
name=None
)
indices:样本类别集合
depth:类别数
on_value: 最大值,如果未指定,默认为1
off_value: 最小值,如果未指定,默认为0
on_value和off_value常常和label smoothing 结合
什么是label_smoothing
一种正则方法,防止过拟合传统one-hot编码标签的网络学习过程中,鼓励模型预测为目标类别的概率趋近1,非目标类别的概率趋近0,即最终预测的logits向量(logits向量经过softmax后输出的就是预测的所有类别的概率分布)中目标类别z的值会趋于无穷大,使得模型向预测正确与错误标签的logit差值无限增大的方向学习,而过大的logit差值会使模型缺乏适应性,对它的预测过于自信.

上代码

import tensorflow as tf 
classes = 5
labels = tf.constant([0,1,2]) # 输入的元素值最小为0,最大为2
output = tf.one_hot(labels,classes)

label_smoothing = 0.1
p = 1.0 - label_smoothing
q = label_smoothing / (classes - 1)
output1 = tf.one_hot(labels,classes,on_value=p,off_value=q)

sess = tf.Session()
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    output = sess.run(output)
    output1 = sess.run(output1)
    print("output of one-hot is : \n",output)
    print("output of one-hot with label_smoothing is : \n",output1)

运行结果在这里插入图片描述
举个例子:
第一个one-hot: 有五种类别:红橙黄绿蓝。第一个样本是红的,第二个样本是橙色,第三个是黄色。
第二个one-hot: 在第一种基础上,“劫富济贫”,对应类别的概率不设置为1,而是设置成1-label_smoothing,也即0.9. 剩下的部分不设置成0,而是均分label_smoothing,也即0.1/4=0.025

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值