转载自@Dymc的博客tensorflow2.0之one_hot函数使用
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=-1, #要填充的轴,默认为-1,即一个新的最内层轴
dtype=None, #默认为int32
name=None
)
简单看个例子,理解一下上面的语法:
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)
输出结果:
tf.Tensor(
[[1 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 1 0 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 0]], shape=(5, 10), dtype=int32)
可以看到张量res
的形状为
5
∗
10
(
5
∗
d
e
p
t
h
)
5*10(5 * depth)
5∗10(5∗depth),并且
res[0][0] = 1
res[1][6] = 1
res[2][5] = 1
res[3][4] = 1
res[4][2] = 1
其余均为0。
indices
用来确定生成的张量中哪些位置为on_value
。
axis
的取值不同会影响输出的shape
结构。主要有以下几种情况:
axis | indices为向量 | indices 为矩阵 |
---|---|---|
-1 | n * depth | w * h * depth |
0 | depth * n | depth * w * h |
1 | w * depth * h |