liaoming999
liaoming999

Reputation: 799

generate tensor like this in tensorflow

Supposed I have a vector

[3, 2, 4]

I want to generate a corresponding tensor

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

Would you please tell us how to do this? Thanks

Upvotes: 0

Views: 63

Answers (1)

Kilian Obermeier
Kilian Obermeier

Reputation: 7118

This should work:

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]]

Upvotes: 1

Related Questions