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

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

 1 import tensorflow as tf
 2 var0 = tf.one_hot(indices=[1, 2, 3], depth=3, axis=0)
 3 var1 = tf.one_hot(indices=[1, 2, 3], depth=4, axis=0)
 4 var2 = tf.one_hot(indices=[1, 2, 3], depth=4, axis=1)
 5 # axis=1 按行排
 6 var3 = tf.one_hot(indices=[1, 2, 3], depth=4, axis=-1)
 7 with tf.Session() as sess:
 8     sess.run(tf.global_variables_initializer())
 9     a0 = sess.run(var0)
10     a1 = sess.run(var1)
11     a2 = sess.run(var2)
12     a3 = sess.run(var3)
13     print("var0(axis=0 depth=3)\n", a0)
14     print("var1(axis=0 depth=4P)\n", a1)
15     print("var2(axis=1)\n", a2)
16     print("var3(axis=-1)\n", a3)

运行结果如下:

 1 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
 2 var0(axis=0 depth=3)
 3  [[0. 0. 0.]
 4  [1. 0. 0.]
 5  [0. 1. 0.]]
 6 var1(axis=0 depth=4P)
 7  [[0. 0. 0.]
 8  [1. 0. 0.]
 9  [0. 1. 0.]
10  [0. 0. 1.]]
11 var2(axis=1)
12  [[0. 1. 0. 0.]
13  [0. 0. 1. 0.]
14  [0. 0. 0. 1.]]
15 var3(axis=-1)
16  [[0. 1. 0. 0.]
17  [0. 0. 1. 0.]
18  [0. 0. 0. 1.]]
19 
20 进程已结束,退出代码0

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

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

运行结果:

 1 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
 2 var0(axis=0 depth=3)
 3  [[4 2 4]]
 4 var1(axis=0 depth=4P)
 5  [[0. 0. 0.]
 6  [0. 0. 0.]
 7  [0. 1. 0.]
 8  [0. 0. 0.]]
 9 
10 进程已结束,退出代码0

 

posted @ 2018-08-01 18:11  苏拉士  阅读(934)  评论(0)    收藏  举报