上原型:
one_hot(indices, depth, on_value=None, off_value=None, axis=None, dtype=None, name=None)
indices: 代表了on_value所在的索引,其他位置值为off_value。类型为tensor,其尺寸与depth共同决定输出tensor的尺寸。
depth:编码深度。
on_value & off_value为编码开闭值,缺省分别为1和0,indices指定的索引处为on_value值;
axis:编码的轴,分情况可取-1、0或-1、0、1,默认为-1
dtype:默认为 on_value 或 off_value的类型,若未提供on_value或off_value,则默认为tf.float32类型。
返回一个 one-hot tensor。
当axis==0,输出尺寸为:depth * features
indices = [2,3,1,6]#长度为features=4的向量
dep = 3
asa = tf.one_hot(indices,dep,axis=0)
with tf.Session() as sess:
print('hot: ', sess.run(asa))
结果为:
hot: [[0. 0. 0. 0.]
[0. 0. 1. 0.]
[1. 0. 0. 0.]]
尺寸为3 * 4也就是:depth * features
当axis==-1,输出尺寸为:features * depth
indices = [2,3,1,6]#长度为features=4的向量
dep = 3
asa = tf.one_hot(indices,dep,axis=-1)
with tf.Session() as sess:
print('hot: ', sess.run(asa))
结果为:
hot: [[0. 0. 1.]
[0. 0. 0.]
[0. 1. 0.]
[0. 0. 0.]]
尺寸为4 * 3也就是:features * depth
当axis = 1时,同axis = -1。
当axis==0,输出尺寸为:depth * batch * features,如下代码:
indices = [[2,3,4],[1,6,7]]#[2,3]的矩阵
dep = 4
asa = tf.one_hot(indices,dep,axis=0)
with tf.Session() as sess:
print('hot: ', sess.run(asa))
输出结果:
hot: [[[0. 0. 0.]
[0. 0. 0.]]
[[0. 0. 0.]
[1. 0. 0.]]
[[1. 0. 0.]
[0. 0. 0.]]
[[0. 1. 0.]
[0. 0. 0.]]]
尺寸为[4,2,3]也就是:depth * batch * features
当axis==-1,输出尺寸为:batch * features * depth
indices = [[2,3,4],[1,6,7]]#[2,3]的矩阵
dep = 4
asa = tf.one_hot(indices,dep,axis=-1)
with tf.Session() as sess:
print('hot: ', sess.run(asa))
输出结果为:
hot: [[[0. 0. 1. 0.]
[0. 0. 0. 1.]
[0. 0. 0. 0.]]
[[0. 1. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]]
尺寸为[2,3,4]也就是:batch * features * depth
当axis==1,输出尺寸为:batch * depth * features
indices = [[2,3,4],[1,6,7]]#[2,3]的矩阵
dep = 4
asa = tf.one_hot(indices,dep,axis=1)
with tf.Session() as sess:
print('hot: ', sess.run(asa))
输出结果为:
hot: [[[0. 0. 0.]
[0. 0. 0.]
[1. 0. 0.]
[0. 1. 0.]]
[[0. 0. 0.]
[1. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]]
尺寸为[2,4,3]也就是:batch * depth * features