tf.one_hot()函数

one_hot(indices, depth, on_value=None, off_value=None, axis=None, dtype=None, name=None)
    Returns a one-hot tensor.

tf.one_hot()函数是将input转化为one-hot类型数据输出,举例:

classes = 3
labels = tf.constant([0,1,0,3,1,2]) 
output = tf.one_hot(labels,classes)
output
<tf.Tensor: shape=(6, 3), dtype=float32, numpy=
array([[1., 0., 0.],
       [0., 1., 0.],
       [1., 0., 0.],
       [0., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]], dtype=float32)>

参数:
on_value,指用某个值代替出现的类别,默认是1;off_value,指用某个值代替未出现的类别,默认是0。例如,我改为用6代替出现的类别,用7代替未出现的类别:

classes = 3
labels = tf.constant([0,1,0,3,1,2]) # 输入的元素值最小为0,最大为2
output = tf.one_hot(labels,classes,on_value=6, off_value=7)
output
<tf.Tensor: shape=(6, 3), dtype=int32, numpy=
array([[6, 7, 7],
       [7, 6, 7],
       [6, 7, 7],
       [7, 7, 7],
       [7, 6, 7],
       [7, 7, 6]])>

depth,就是类别数量;axis,默认对最后一维进行独热编码,例如我一个batch有2个样本标签,一共有八个类别,其中2个batch的标签为:[[0,0],[1,1]],

classes = 8
labels = tf.constant([[0,0],[1,1]]) # 输入的元素值最小为0,最大为2
output = tf.one_hot(labels,classes)
output
<tf.Tensor: shape=(2, 2, 8), dtype=float32, numpy=
array([[[1., 0., 0., 0., 0., 0., 0., 0.],
        [1., 0., 0., 0., 0., 0., 0., 0.]],
[[0., 1., 0., 0., 0., 0., 0., 0.],
        [0., 1., 0., 0., 0., 0., 0., 0.]]], dtype=float32)>

可以看出,这两个batch的标签经过独热编码后,分别为:

Output[0] :
[[1., 0., 0., 0., 0., 0., 0., 0.],
        [1., 0., 0., 0., 0., 0., 0., 0.]]
Output[1] :
[[0., 1., 0., 0., 0., 0., 0., 0.],
        [0., 1., 0., 0., 0., 0., 0., 0.]]
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值