Shan
Shan

Reputation: 63

how to add a slice of placeholder tensor to 1 in tensorflow?

In order to have oneHot encoding I use this code:

self.Y = tf.placeholder(tf.int32, [None, 1])
self.YY=tf.one_hot(self.Y,depth=5) gives us 

given y=2, it gives me [0 0 1 0 0].

Now I want to have an encoding like onehot, but with all ones after index y. For example, given y=2 then it should give [0 0 1 1 1].

By the way, I do not want to do this outside of tensorflow.

Upvotes: 2

Views: 99

Answers (1)

Stewart_R
Stewart_R

Reputation: 14515

You can use the tf.range() function to return a sequence of integers up to your max value then use the <= comparison to compute to your desired result.

So for example, with the tensor in your example, [2], we could just do:

tf.cast(Y <= tf.range(5),tf.int32)

to produce the desired result: [0,0,1,1,1].

It also 'broadcasts' in the way we'd expect with a a batch of values. Given say a batch size of 5 so you have a batch_Y with value something like: [[1], [0], [1], [4], [2]] then:

tf.cast(batch_y <= tf.range(5),tf.int32)

produces the correct output:

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

Upvotes: 1

Related Questions