tf.one_hot编码的用法以及one-hot自己编码

本文介绍了如何使用TensorFlow的tf.one_hot函数进行one-hot编码,包括参数解析和注意事项,并提供了一个使用numpy自定义编码的例子。
摘要由CSDN通过智能技术生成

tf.one_hot编码的用法

最近想将之前用普通机器学习做的一个项目,用三层的全连接神经网络跑一遍,在做label时候,需要将(0,1)这两种label转为one-hot编码,因此探究了一下tf.one_hot的用法。

tf.one_hot(indices, depth, on_value=None, off_value=None, axis=None, dtype=None, name=None)

indices: 是一个矩阵,可以是一维的矩阵(居多),也可以是多维的

depth:要输出的one-hot编码的tensor的列的维度,比如说输入的是(1800,)的一维矩阵,depth是3,其会输出[1800,3]的shape的tensor

on_value:默认是1,可以自己指定,就是将one-hot编码的那个‘1’换成了你所指定的数字

off_value:默认是0,可以自己指定,就是将one-hot编码的那个‘0’换成了你所指定的数字

axis:默认是-1,一般我们就默认好了,符合直觉,具体用法:

If indices is a vector of length features(看作是样本个数,就是上面的1800), the output shape will be:
features x depth if axis == -1
depth x features if axis == 0
If indices is a matrix (batch) with shape [batch, features](有不同组的样本), the output shape will be:
batch x features x depth if axis == -1
batch x depth x features if axis == 1
depth x batch x features if axis == 0

dtype:默认是tf.float32

官方提供的例子:

   indices = [0, 1, 2]
   depth = 3
   tf.one_hot(indices, depth)  # output: [3 x 3]
   # [[1., 0., 0.],
   #  [0., 1., 0.],
   #  [0., 0., 1.]]
   
   indices = [0, 2, -1, 1]
   depth = 3
   tf.one_hot(indices, depth,
              on_value=5.0, off_value=0.0,
              axis=-1)  # output: [4 x 3]
   # [[5.0, 0.0, 0.0],  # one_hot(0)
   #  [0.0, 0.0, 5.0],  # one_hot(2)
   #  [0.0, 0.0, 0.0],  # one_hot(-1)
   #  [0.0, 5.0, 0.0]]  # one_hot(1)
   
   indices = [[0, 2], [1, -1]]
   depth = 3
   tf.one_hot(indices, depth,
              on_value=1.0, off_value=0.0,
              axis=-1)  # output: [2 x 2 x 3]
   # [[[1.0, 0.0, 0.0],   # one_hot(0)
   #   [0.0, 0.0, 1.0]],  # one_hot(2)
   #  [[0.0, 1.0, 0.0],   # one_hot(1)
   #   [0.0, 0.0, 0.0]]]  # one_hot(-1)

自己试验一下发现,这个one-hot编码是从0开始的编码,即使你的label里面没有0,比如说是从(1,2)的label,那它也只会从0开始编码,这个需要特别注意到:

>>> indices = [
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值