首页 > 解决方案 > 检查Tensorflow(批处理版)张量列表中是否存在值的好方法是什么?

问题描述

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]]

如果我有值张量和查询张量,我想一一检查值张量中是否存在查询张量,然后返回结果张量。请问我们是否有基于向量的方法来执行此操作(而不是使用 tf.while_loop)?

更新:我认为如下, tf.sets.set_intersection 可能有用。

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]]

标签: tensorflowmatrix

解决方案


您可以通过将 的每个元素b与 的每个其他元素相减a,然后找到零的索引来实现:

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]]

推荐阅读