首页 > 解决方案 > 在张量流中生成这样的张量

问题描述

假设我有一个向量

[3, 2, 4]

我想生成一个对应的张量

[[1,1,1,0], [1,1,0,0],[1,1,1,1]]

你能告诉我们怎么做吗?谢谢

标签: pythontensorflow

解决方案


这应该有效:

import tensorflow as tf
sess = tf.Session()

# Input tensor
indices = tf.placeholder_with_default([3, 2, 4], shape=(None,))

max_index = tf.reduce_max(indices)

def to_ones(index):
    ones = tf.ones((index, ), dtype=indices.dtype)
    zeros = tf.zeros((max_index - index, ), dtype=indices.dtype)
    return tf.concat([ones, zeros], axis=0)

# Output tensor
result = tf.map_fn(to_ones, indices)

print(result)

Tensor("map/TensorArrayStack/TensorArrayGatherV3:0", shape=(?, ?), dtype=int32)

print(sess.run(result))

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

print(sess.run(result, feed_dict={indices: [1, 3, 3, 7]}))

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

推荐阅读