0
votes

Let's go straight, currently, I want to index a tensor and change the non-zero term to -1 and zero term to 1. But I don't know how to do it in TensorFlow.

Here is my code:

y_[y_ != 0].assign(-1)
y_[y_ == 0].assign(1)

The reason is TensorFlow doesn't seem to support boolean indexing. How can I fix it?

Btw, it seems boolean_mask doesn't work for me, because I don't want to return a slice of y_, I just want y_ to change its values.

Thanks!

1

1 Answers

0
votes

You can use tf.cond (), for the conditional assignment. I have given an example code below,

import tensorflow as tf

x_= tf.Variable(5) #non-zero variable
y_= tf.Variable(0) #variable euqals to 0

y_ =tf.cond(tf.equal(y_,0),lambda :y_.assign(1),lambda :y_.assign(-1)) #assign 1 if variable equals to zero else -1
x_ =tf.cond(tf.equal(x_,0),lambda :x_.assign(1),lambda :x_.assign(-1)) #assign 1 if variable equals to zero else -1

sess = tf.Session()
sess.run(tf.global_variables_initializer())

with sess.as_default():
   print(y_.eval()) #prints 1
   print(x_.eval()) #prints -1

Hope this helps.