0

Suppose I´ve got three tensors shape (n,1) T,r,E and I wanted to implement a function that calculates: sum(i,j) (T[j] < T[i]) (r[j] > r[i]) E[j]. How can I proceed?

This is what I´ve got

#tensor examples
T=K.constant([1,4,5])
r=K.constant([.8,.3,.7])
E=K.constant([1,0,1])

# cartesian product of T to compare element wise
c = tf.stack(tf.meshgrid(T, T, indexing='ij'), axis=-1)
cartesian_T = tf.reshape(c, (-1, 2))

# cartesian product of r to compare elemento wise
r = tf.stack(tf.meshgrid(r, r, indexing='ij'), axis=-1)
cartesian_r = tf.reshape(r, (-1, 2))

# TO DO: 
# compare the two columns in cartesian T and cast to integer 1/0 if  
# second column in T less/greater than first column in T => return tensor


# compare the two columns in cartesian E and cast to integer 1/0 if  
# second column in r greater/less than first column in r => return tensor

# multiply previous tensors by a broadcasted version of E, then do K.sum()

Do you think I'm on the right track? What would you suggest to implement this?

4
  • What output do you expect? n*1 or n*n? Commented Jun 6, 2019 at 2:22
  • Should be a double Commented Jun 6, 2019 at 3:46
  • Can you give the output you expect in your example when T=[1,4,5] & r=[.8,.3,.7] & E=[1,0,1]? Commented Jun 6, 2019 at 3:53
  • Hi. I would expect 2.0 ! Commented Jun 6, 2019 at 11:18

1 Answer 1

1

Try:

import keras.backend as K
import tensorflow as tf

T=K.constant([1,4,5])
r=K.constant([.8,.3,.7])
E=K.constant([1,0,1])

T_new = tf.less(T[tf.newaxis,:],T[:,tf.newaxis])
r_new = tf.greater(r[tf.newaxis,:],r[:,tf.newaxis])
E_row,_ = tf.meshgrid(E, E)
result = tf.reduce_sum(tf.boolean_mask(E_row,tf.logical_and(T_new,r_new)))

with tf.Session() as sess:
    print(sess.run(result))

#print
2.0
Sign up to request clarification or add additional context in comments.

7 Comments

Great! This it it! So grateful!
@JuanCastaño Please accept the answer if you have no question.
I've implemented the function; however when the tensors are big, it blows the memory; do you happen to think of a more performatic implementation?
@JuanCastaño How about the updated code? But I think the best way is to reduce batch size.
@JuanCastaño Did you use tf.placeholder to feed data?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.