1、tf.one_hot()

tf.one_hot(indices, depth, on_value, off_value, axis)

  • indices是一个列表,指定张量中独热向量的独热位置,或者说indeces是非负整数表示的标签列表。len(indices)就是分类的类别数。
  • tf.one_hot返回的张量的阶数为indeces的阶数+1。
  • 当indices的某个分量取-1时,即对应的向量没有独热值。
  • depth是每个独热向量的维度。
  • on_value是独热值。
  • off_value是非独热值。
  • axis指定第几阶为depth维独热向量,默认为-1,即,指定张量的最后一维为独热向量

①对于一个2阶张量而言,axis=0时,即,每个列向量是一个独热的depth维向量 axis=1时,即,每个行向量是一个独热的depth维向量。axis=-1,等价于axis=1

1 import tensorflow as tf
2 labels = [0,2,-1,1]
3 y = tf.one_hot(indices=labels, depth=5, on_value=1.0, off_value=0.0, axis=-1)
4 print(y.numpy())

输出:

[[1. 0. 0. 0. 0.]
 [0. 0. 1. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0.]]

"""
[0,2,-1,1]
# 得到4个5维独热行向量向量,
#    其中第1个向量的第0个分量是独热1,
#    第2个向量的第2个分量是独热,
#    第3个向量没有独热,因为指定为-1
#    第4个向量的第1个分量为独热
"""

②得到一个5维独热行向量

1 y1 = tf.one_hot(indices=3, depth=5, on_value=1.0, off_value=0.0, axis=0)
2 print(y1)
3 
4 # tf.Tensor([0. 0. 0. 1. 0.], shape=(5,), dtype=float32)

③得到一个5维独热列向量

1 y2 = tf.one_hot(indices=[3], depth=5, on_value=1.0, off_value=0.0, axis=0)
2 print(y2)
3 
4 tf.Tensor(
5 [[0.]
6  [0.]
7  [0.]
8  [1.]
9  [0.]], shape=(5, 1), dtype=float32)

y3 = tf.one_hot(indices=[[0,1],[1,0]], depth=3)
print(y3)
tf.Tensor(
[[[1. 0. 0.]
  [0. 1. 0.]]

 [[0. 1. 0.]
  [1. 0. 0.]]], shape=(2, 2, 3), dtype=float32)
posted on 2019-11-27 09:56  Luaser  阅读(670)  评论(0编辑  收藏  举报