5

I have a tensor like this:

sim_topics = [[0.65 0. 0. 0. 0.42 0. 0. 0.51 0. 0.34 0.] [0. 0.51 0. 0. 0.52 0. 0. 0. 0.53 0.42 0.] [0. 0.32 0. 0.50 0.34 0. 0. 0.39 0.32 0.52 0.] [0. 0.23 0.37 0. 0. 0.37 0.37 0. 0.47 0.39 0.3 ]] 

and one boolean tensor like this:

bool_t = [False True True True] 

I want to select part of sim_topics based on the bool flag in bool_t in a way it just select top k smallest values per row(if the row is true if not leave it as it is).

So the expected output would be like this:(here k=2)

[[0.65 0. 0. 0. 0.42 0. 0. 0.51 0. 0.34 0.] [0. 0.51 0. 0. 0.52 0. 0. 0. 0.53 0.42 0.] [0. 0.32 0. 0.50 0 0 0. 0. 0 0.32 0 ] [0. 0.23 0 0. 0. 0 0 0. 0 0 0.3 ]] 

I was trying to accomplish this first by using boolean_mask and where to get the indices I want then go get the top smallest. However, when I use where it does not give me the indices where there is zero.

1 Answer 1

2
k = 2 dim0 = sim_topics.shape[0] a = tf.cast(tf.equal(sim_topics,0), sim_topics.dtype) b = tf.reshape(tf.reduce_sum(a,1) + k, (dim0,-1)) c = tf.cast(tf.argsort(tf.argsort(sim_topics,1),1), sim_topics.dtype) d = tf.logical_or(tf.less(c,b),tf.reshape(tf.logical_not(bool_t),(dim0,-1))) with tf.Session() as sess: print(sess.run(sim_topics * tf.cast(d,sim_topics.dtype))) [[0.65 0. 0. 0. 0.42 0. 0. 0.51 0. 0.34 0. ] [0. 0.51 0. 0. 0. 0. 0. 0. 0. 0.42 0. ] [0. 0.32 0. 0. 0. 0. 0. 0. 0.32 0. 0. ] [0. 0.23 0. 0. 0. 0. 0. 0. 0. 0. 0.3 ]] 
Sign up to request clarification or add additional context in comments.

10 Comments

Thanks a lot for your help. Actually, It prints out the correct answer, though I would like to learn your approach. could you explain it how did you come up with this solution? Actually, its totally different from my mind process and I would like to learn it:)
@sariii my aim is to only get the top K smallest. Since 0 are considered as smallest, and there are no negative numbers, then, eg if there are 3 zeros and we need top 2, then we need 5 numbers, the 3 zeros and the 2 numbers. So thats why I have b = a+k. then c is the index where the value should lie in the vector. Then I only want those values in c that are less than b and need to be changed according to the bool_t that is d.
Actually there are negative numbers as well. I should have a better tensor sample:| could you let me know what thing should I change so that it can work on the negatives as well?(but I dont want to consider them as smallest, I want top positive smallest
@sariii if you want top-positive smallest, force the negative numbers to be zero, then use the code above, then include the negative numbers
@sariii to use top_k, in the above code replace line c with c = tf.cast(tf.nn.top_k(tf.nn.top_k(sim_topics,sim_topics.shape[1])[1][:,::-1], sim_topics.shape[1])[1][:,::-1],sim_topics.dtype)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.