CodeCollection2018
10/26/2018 - 12:54 PM

tensorflow-one_hot方法

tensorflow自带将label转换为类one_hot向量的方法

返回一个 one-hot 张量。 

索引中由索引表示的位置取值 on_value,而所有其他位置都取值 off_value。 

on_value 和 off_value必须具有匹配的数据类型。如果还提供了 dtype,则它们必须与 dtype 指定的数据类型相同。

如果未提供 on_value,则默认值将为 1,其类型为 dtype。 

如果未提供 off_value,则默认值为 0,其类型为 dtype。

如果输入的索引的秩为 N,则输出的秩为 N+1。新的坐标轴在维度上创建 axis(默认值:新坐标轴在末尾追加)。

如果索引是标量,则输出形状将是长度 depth 的向量。

如果索引是长度 features 的向量,则输出形状将为:

features x depth if axis == -1
depth x features if axis == 0
如果索引是具有形状 [batch, features] 的矩阵(批次),则输出形状将是: 

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 没有提供,则它会尝试假定 on_value 或者 off_value 的数据类型,如果其中一个或两个都传入。如果没有提供 on_value、off_value 或 dtype,则dtype 将默认为值 tf.float32。 

注意:如果一个非数值数据类型输出期望(tf.string,tf.bool等),都on_value与off_value 必须被提供给one_hot。
示例
示例-1
假设如下:

indices = [0, 2, -1, 1]
depth = 3
on_value = 5.0
off_value = 0.0
axis = -1
那么输出为 [4 x 3]:

output =
[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)
示例-2
假设如下:

indices = [[0, 2], [1, -1]]
depth = 3
on_value = 1.0
off_value = 0.0
axis = -1
那么输出是 [2 x 2 x 3]:

output =
[
  [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)
]
使用 on_value 和 off_value 的默认值:

indices = [0, 1, 2]
depth = 3
输出将是:

output =
[[1., 0., 0.],
 [0., 1., 0.],
 [0., 0., 1.]]