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会有以下情况:
axis | indices为向量 | indices为矩阵 |
---|---|---|
-1 | n * depth | w * h * depth |
0 | depth * n | depth* w * h |
1 | w * 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