tensorflow2.0之one_hot函数使用

tensorflow2.0之one_hot函数使用

在这里插入图片描述

先了解一下one_hot要干啥吧。来,咱先看个程序,你一定会很眼熟的。

import tensorflow as tf
labels = [0, 6, 5, 4, 2]
res = tf.one_hot(
			indices=labels, 
			depth=10, 
			on_value=1, 
			off_value=0, 
			axis=-1)
print(res)

在这里插入图片描述
嘿,是不是发现什么了?
labels向量最后可以表示乘矩阵的方式,且[1 0…0]表示0,类推[0 1 0…0]表示1,这样,可以表示 0~9总共九个数值。
one_hot的作用就是这样的,作为存储标签的一种方式,用1的位置不同来区分数值。


那么下来接详细介绍one_hot中的参数有哪些以及参数的效果。
one_hot函数定义:

one_hot(
    indices,        #输入的tensor,在深度学习中一般是给定的labels,通常是数字列表,属于一维输入,也可以是多维。
    depth,          #一个标量,用于定义一个 one hot 维度的深度
    on_value=None,  #定义在 indices[j] = i 时填充输出的值的标量,默认为1
    off_value=None, #定义在 indices[j] != i 时填充输出的值的标量,默认为0
    axis=None,      #要填充的轴,默认为-1,即一个新的最内层轴
    dtype=None,     #默认是int32
    name=None
)

简言之,
indices是用来确定生成的张量中哪些位置的值为on_value
其他参数好理解,重点说一下axis的取值问题。
indices为向量、矩阵(若向量大小为n,矩阵大小为w*h)事时,axis取值的不同会影响输出的shape结构,输出的张量shape会有以下情况:

axisindices为向量indices为矩阵
-1n * depthw * h * depth
0depth * ndepth* w * h
1w * depth * h

当indices为向量时

import tensorflow as tf
labels = [0, 2, -1, 1]  #为向量
res = tf.one_hot(
			indices=labels, 
			depth=3, 
			on_value=1.0, 
			off_value=0.0, 
			axis=-1)
print(res)

输出:
在这里插入图片描述

即当axis=-1时, shape = indices * depth  
下面将axis 改为0,结果因为 shape =depth * indices

在这里插入图片描述


indices为矩阵时

import tensorflow as tf
labels = [[3, 2], [1, 6], [3, 5]]  #3*2的矩阵
res = tf.one_hot(
			indices=labels, 
			depth=10, 
			on_value=1, 
			off_value=0, 
			axis=-1)
print(res)
axis=-1, 结果shape = 3*2*10 即 h * w * indices

在这里插入图片描述

将axis改为0,结果如下,shape = 10*3*2 即indices*w*h

在这里插入图片描述

将 axis改为1,结果如下,shape = 3*10*2 即w*indices*h

在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值