用tf.one_hot函数写任一坐标为1的二维张量

2023-02-17,,,

先给出tf.one_hot的用例:(例子转自https://www.jianshu.com/p/c5b4ec39713b)

 import tensorflow as tf
var0 = tf.one_hot(indices=[1, 2, 3], depth=3, axis=0)
var1 = tf.one_hot(indices=[1, 2, 3], depth=4, axis=0)
var2 = tf.one_hot(indices=[1, 2, 3], depth=4, axis=1)
# axis=1 按行排
var3 = tf.one_hot(indices=[1, 2, 3], depth=4, axis=-1)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
a0 = sess.run(var0)
a1 = sess.run(var1)
a2 = sess.run(var2)
a3 = sess.run(var3)
print("var0(axis=0 depth=3)\n", a0)
print("var1(axis=0 depth=4P)\n", a1)
print("var2(axis=1)\n", a2)
print("var3(axis=-1)\n", a3)

运行结果如下:

 2018-08-01 18:06:39.012597: I T:\src\github\tensorflow\tensorflow\core\platform\cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
var0(axis=0 depth=3)
[[0. 0. 0.]
[1. 0. 0.]
[0. 1. 0.]]
var1(axis=0 depth=4P)
[[0. 0. 0.]
[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
var2(axis=1)
[[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]
var3(axis=-1)
[[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]] 进程已结束,退出代码0

这里需要一个4*3的矩阵,记为var1,则需要var1[2,1]为0的one_hot矩阵。如下代码可实现。

 import tensorflow as tf
q1 = 2
q2 = 1
depth = 4
kuan = 3
var0 = tf.one_hot(indices=[q2], depth=kuan, on_value=q1, off_value=depth, axis=1)
var1 = tf.one_hot(indices=[depth, q1, depth], depth=depth, axis=0)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
a0 = sess.run(var0)
a1 = sess.run(var1)
print("var0(axis=0 depth=3)\n", a0)
print("var1(axis=0 depth=4P)\n", a1)

运行结果:

 2018-08-01 18:08:01.640973: I T:\src\github\tensorflow\tensorflow\core\platform\cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
var0(axis=0 depth=3)
[[4 2 4]]
var1(axis=0 depth=4P)
[[0. 0. 0.]
[0. 0. 0.]
[0. 1. 0.]
[0. 0. 0.]] 进程已结束,退出代码0

用tf.one_hot函数写任一坐标为1的二维张量的相关教程结束。