1.tf.one_hot
返回一个onehot tensor
tf.one_hot(
indices,
depth,
on_value=None,
off_value=None,
axis=None,
dtype=None,
name=None
)
-
indices
: tensor类型值得索引. -
depth
: 代表one-hot得深度,可以理解为对应得类别数. -
on_value
: 一个标量值,索引位置上得值. (default: 1). -
off_value
: 索引之外的值. (default: 0) -
axis
: 新的维度,也就是填充的所在轴 (default: -1,). -
dtype
: The data type of the output tensor. -
name
: op节点名称 (optional).
一个N维的输入,则输出维度为N+1,意思就是:如果输入是一个标量,则输出为一个固定深度的向量;如果输入是一个 固定深度的向量,则输出是一个二维tensor。上述两个输入,又分两个情况(axis=-1或者0)。
# 输入为标量
[features, depth] if axis == -1
[depth, features] if axis == 0
# 输入为固定长度的向量
[batch, features x depth] if axis == -1
[batch, depth x features] if axis == 1
[depth, batch x features] if axis == 0
举例如下:
# 标量
indices = 3
depth = 4
a = tf.one_hot(indices, depth, axis=-1)
sess = tf.InteractiveSession()
print(sess.run(a))
# 输出
# axis=-1或者0,结果都是一样的,因为就一个维度,怎么取都是那一个。。。。。
[0. 0. 0. 1.]
--------------------------------------------------------------------------------
# 输入为固定长度向量
indices = [0, 1, 3, 2]
depth = 5
a = tf.one_hot(indices, depth, axis=-1)
sess = tf.InteractiveSession()
print(sess.run(a))
# axis=-1时
[[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 1. 0. 0.]]
# axis=0时
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 0. 1.]
[0. 0. 1. 0.]
[0. 0. 0. 0.]]
当输出为[batch, features]时(训练的时候都是批次的),输出维度应该是这样的:
[batch, features, depth] if axis == -1
[batch, depth, features] if axis == 1
[depth, batch, features] if axis == 0
举例:
# 对这种输入的one-hot,我是一般不会遇到,平时模型训练,label都是一维的
indices = [[0, 2], [1, -1], [2, 3]]
depth = 5
a = tf.one_hot(indices, depth, axis=-1)
sess = tf.InteractiveSession()
print(sess.run(a))
# 输出
# aixs=-1
[[[1. 0. 0. 0. 0.]
[0. 0. 1. 0. 0.]]
[[0. 1. 0. 0. 0.]
[0. 0. 0. 0. 0.]]
[[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]]]
# axis=0
[[[1. 0.]
[0. 0.]
[0. 0.]]
[[0. 0.]
[1. 0.]
[0. 0.]]
[[0. 1.]
[0. 0.]
[1. 0.]]
[[0. 0.]
[0. 0.]
[0. 1.]]
[[0. 0.]
[0. 0.]
[0. 0.]]]
持续更新·············