Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is good way to check a value existed in the tensor list in Tensorflow (batch version)?

Values Tensor: [[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15]]
Query Tensor: [[1,2,8], [0,0,6], [11,12,13]]
Reult tensor: [[True, True, False],[False, False, True],[True, True, True]]

If I have a values tensor and query tensor, i want to check whether query tensor existed in values tensor one by one, then return the result tensor. Could I ask do we have vector-based way to do this (rather than using tf.while_loop)?

Updated: I think as following, tf.sets.set_intersection may be useful.

import tensorflow as tf
a = tf.constant([[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15]])
b = tf.constant([[1,2,8], [0,0,6], [11,12,13]])
res = tf.sets.set_intersection(a, b)
res2 = tf.sparse_tensor_to_dense(
    res, default_value=-1)

with tf.Session() as sess:
  print(sess.run(res2))
[[ 1  2 -1]
 [ 6 -1 -1]
 [11 12 13]]
like image 638
Hypnoz Avatar asked Oct 17 '22 16:10

Hypnoz


1 Answers

You can achieve through subtracting every element of b with every other element of a, and then finding the indices of the zeros:

find_match =tf.reduce_prod(tf.transpose(a)[...,None]- tf.abs(b[None,...]), 0)

find_idx = tf.equal(find_match,tf.zeros_like(find_match))

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

#[[ True  True False]
# [False False  True]
# [ True  True  True]]
like image 66
vijay m Avatar answered Oct 21 '22 07:10

vijay m