形状T1的两个tensorflow张量= N * d,T2 = M * d;中号<N T1在T2具有行。查找T1张行指数为T2的每一行

问题描述 投票:1回答:1

我有两个张量T1(N * d的尺寸)和T2(M * d的尺寸)(M是小于N)。 T2行保证在T1。对于T2的每一行,有没有办法找到T1其中行相匹配的指数?我能解决使用急于执行的问题。

import tensorflow as tf
import numpy as np
tf.enable_eager_execution()
x = tf.random_normal([15,3])
y = x[:2] # first two entries 
y= tf.concat([y,x[8:9]], 0)
output = []
for row in x:
   if row.numpy() in y.numpy():
     output.append(True)
   else:
     output.append(False)

可能有人对于不急于执行执行提供帮助?我们如何执行相同的操作,如果T1和T2是批?即T1 - B * N * d和T2 - B * M * d

附:我们如何搜索在Tensorflow行?

python tensorflow
1个回答
0
投票

这里是你如何能做到这一点:

import tensorflow as tf

def find_row_indices(t1, t2):
    # Compare every pair of rows
    eq = tf.equal(tf.expand_dims(t1, -3), tf.expand_dims(t2, -2))
    # Find where all the elements in two rows match
    matches = tf.reduce_all(eq, axis=-1)
    # Find indices where match occurs
    idx = tf.argmax(tf.cast(matches, tf.uint8), axis=-1)
    # Find where there has been no match
    has_match = tf.reduce_any(matches, axis=-1)
    # Return match index of -1 if no match found
    return tf.where(has_match, idx, -tf.ones_like(idx))

# Test
with tf.Graph().as_default():
    tf.set_random_seed(100)
    x = tf.random_normal([15, 3])
    y = x[:2]
    y = tf.concat([y, x[8:9]], 0)
    idx = find_row_indices(x, y)
    with tf.Session() as sess:
        print(sess.run(idx))
        # [0 1 8]

它有二次空间和内存成本,因为它的每行对彼此比较,所以有两个非常大的投入可能会在某些情况下出现问题。此外,如果有一个以上的匹配指数,这种方法并不能保证它们中的哪一个将被退回。

编辑:上面的功能也可以用更多的初始尺寸阵列中使用。例如:

import tensorflow as tf

with tf.Graph().as_default():
    tf.set_random_seed(100)
    x = tf.random_normal([4, 15, 3])
    y = tf.gather_nd(x, [[[ 0,  3], [ 0,  6], [ 0,  2]],
                         [[ 1, 10], [ 1,  5], [ 1, 12]],
                         [[ 2,  8], [ 2,  1], [ 2,  0]],
                         [[ 3,  9], [ 3, 14], [ 3,  4]]])
    idx = find_row_indices(x, y)
    with tf.Session() as sess:
        print(sess.run(idx))
        # [[ 3  6  2]
        #  [10  5 12]
        #  [ 8  1  0]
        #  [ 9 14  4]]
© www.soinside.com 2019 - 2024. All rights reserved.