Tensorflow:如何在给定1的索引的情况下创建0和1的一维张量

时间:2019-02-24 03:36:10

标签: python tensorflow

以长度为5的张量为例,索引为1、3和4。结果张量应为:

[0, 1, 0, 1, 1]

谢谢

1 个答案:

答案 0 :(得分:0)

import tensorflow as tf
import numpy
a = []

indices = [1, 3, 4]
for i in range(5):
    if i in indices:
        a.append(1)
    else:
        a.append(0)


arr = numpy.array(a)

x = tf.convert_to_tensor(a, dtype=tf.float32)


with tf.Session() as sess:
    print(sess.run(x))

输出:

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

如果需要,可以调整索引的参数和数组的大小