import numpy as np
import tensorflow as tf
indices = [0, 1, 1] # rank=1
depth = 8
a = tf.one_hot(indices, depth) # rank=2,输出为[3,3]
indices=[0,2,-2,1] #rank=1
depth=7
b=tf.one_hot(indices,depth,on_value=5.0,off_value=1.0,axis=-1)
print(a)
print(b)
结果:
tf.Tensor(
[[1. 0. 0. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 0.]], shape=(3, 8), dtype=float32)
tf.Tensor(
[[5. 1. 1. 1. 1. 1. 1.]
[1. 1. 5. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1. 1.]
[1. 5. 1. 1. 1. 1. 1.]], shape=(4, 7), dtype=float32)
2022-01-26 23:03:21.608213: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x2181e053ce0 initialized for platform Host (this does not guarantee that XLA will be used). Devices:
2022-01-26 23:03:21.608562: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): Host, Default Version
2022-01-26 23:03:21.608979: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1102] Device interconnect StreamExecutor with strength 1 edge matrix:
2022-01-26 23:03:21.609264: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1108]
Process finished with exit code 0
one_hot(a,b)中,b代表向量的长度
a为列表,代表每个行向量中主元素(on_value)的值为1(若设定,则为设定值),其余元素(off_value)的值为0(若设定,则为设定值)。