Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keras : How to find indices from a tensor for a particular value similar to numpy.where()

Tags:

keras

I am searching for a Keras command which is similar to python "numpy.where()" command. Basically, my idea is to extract the indices from a tensor. In python I can do simply f_j=(np.where(X==j)) which gives me specific indices(f_j) for the value j.

ex:

X= [0 1 1 0 0 2 3 ]

f_j=(np.where(X==1))

f_j= [1 2]

Is there is any similar function which I can use for this purpose ?

I tried to write array search inside a tensor. However, I end up with error when calling "if K.equal():" line as

TypeError: Using a tf.Tensor as a Python bool is not allowed. Use if t is not None: instead of if t: to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.

def loss(y_true, y_pred:

b=K.equal(y_true,0)

b=K.cast(b,dtype='float32')

for i in range(0,5):

if K.equal(b[i],1):

........

y_true = [0 1 1 0 0 2 3 ]
like image 895
Rithmax Avatar asked Apr 21 '17 23:04

Rithmax


People also ask

How do you access the element in a tensor?

We use Indexing and Slicing to access the values of a tensor. Indexing is used to access the value of a single element of the tensor, whereasSlicing is used to access the values of a sequence of elements. We use the assignment operator to modify the values of a tensor.

Can you index a tensor?

We can index a Tensor with another Tensor and sometimes we can successfully index a Tensor with a NumPy array. The following code works for some dims : (2, 3) (2, 3, 2)

How do you subset a tensor?

Basically to subset a tensor for some indexes [a,b,c] It needs to get in the format [[0,a],[1,b],[2,c]] and then use gather_nd() to get the subset.

Can you slice tensors?

You can use tf. slice on higher dimensional tensors as well. You can also use tf. strided_slice to extract slices of tensors by 'striding' over the tensor dimensions.


1 Answers

You should try something like:

from keras import backend as K
value = 5
wh = K.tf.where(K.tf.equal(x,value))

when your backend is tensorflow.

Hope that helps

like image 188
Δημητρης Παππάς Avatar answered Oct 15 '22 14:10

Δημητρης Παππάς