one_hot(indices, depth, on_value=None, off_value=None, axis=None, dtype=None, name=None)
Returns a one-hot tensor.
tf.one_hot()函数是将input转化为one-hot类型数据输出,举例:
classes = 3
labels = tf.constant([0,1,0,3,1,2])
output = tf.one_hot(labels,classes)
output
<tf.Tensor: shape=(6, 3), dtype=float32, numpy=
array([[1., 0., 0.],
[0., 1., 0.],
[1., 0., 0.],
[0., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]], dtype=float32)>
参数:
on_value,指用某个值代替出现的类别,默认是1;off_value,指用某个值代替未出现的类别,默认是0。例如,我改为用6代替出现的类别,用7代替未出现的类别:
classes = 3
labels = tf.constant([0,1,0,3,1,2]) # 输入的元素值最小为0,最大为2
output = tf.one_hot(labels,classes,on_value=6, off_value=7)
output
<tf.Tensor: shape=(6, 3), dtype=int32, numpy=
array([[6, 7, 7],
[7, 6, 7],
[6, 7, 7],
[7, 7, 7],
[7, 6, 7],
[7, 7, 6]])>
depth,就是类别数量;axis,默认对最后一维进行独热编码,例如我一个batch有2个样本标签,一共有八个类别,其中2个batch的标签为:[[0,0],[1,1]],
classes = 8
labels = tf.constant([[0,0],[1,1]]) # 输入的元素值最小为0,最大为2
output = tf.one_hot(labels,classes)
output
<tf.Tensor: shape=(2, 2, 8), dtype=float32, numpy=
array([[[1., 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.]]], dtype=float32)>
可以看出,这两个batch的标签经过独热编码后,分别为:
Output[0] :
[[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.]]
Output[1] :
[[0., 1., 0., 0., 0., 0., 0., 0.],
[0., 1., 0., 0., 0., 0., 0., 0.]]