Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement Numpy where index in TensorFlow?

I have the following operations which uses numpy.where:

    mat = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.int32)
    index = np.array([[1,0,0],[0,1,0],[0,0,1]])
    mat[np.where(index>0)] = 100
    print(mat)

How to implement the equivalent in TensorFlow?

mat = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.int32)
index = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
tf_mat = tf.constant(mat)
tf_index = tf.constant(index)
indi = tf.where(tf_index>0)
tf_mat[indi] = -1   <===== not allowed 
like image 390
Roby Avatar asked Jan 02 '23 01:01

Roby


1 Answers

Assuming that what you want is to create a new tensor with some replaced elements, and not update a variable, you could do something like this:

import numpy as np
import tensorflow as tf

mat = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.int32)
index = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
tf_mat = tf.constant(mat)
tf_index = tf.constant(index)
tf_mat = tf.where(tf_index > 0, -tf.ones_like(tf_mat), tf_mat)
with tf.Session() as sess:
    print(sess.run(tf_mat))

Output:

[[-1  2  3]
 [ 4 -1  6]
 [ 7  8 -1]]
like image 89
jdehesa Avatar answered Jan 05 '23 16:01

jdehesa