在TensorFlow中计算两个二维数组之间的集合差异

3
如何在tensorflow中计算两个数组元素的差集?
例如:我想从a中减去所有b的元素。
import numpy as np

a = np.array([[1, 0, 1], [2, 0, 1], [3, 0, 1], [0, 0, 0]])
b = np.array([[1, 0, 1], [2, 0, 1]])

期望结果:

array([[3, 0, 1], 
       [0, 0, 0]])

可能可以使用tf.sets.set_difference()完成,但我不知道如何做。
在numpy中,你可以像这样做,但是我想要一个tensorflow解决方案来将此操作卸载到GPU设备上,因为对于大型数组来说,此操作的计算成本很高。

tf.sets.set_difference 仅在张量的最低维度上操作,并且允许两个输入张量中仅有最后一个维度不同。如果您尝试删除整行,即在集合的维度-2上进行操作,则无法使用 set_difference - GPhilo
1个回答

0
这个解决方案怎么样?
import tensorflow as tf

def diff(tens_x, tens_y):
    with tf.get_default_graph().as_default():
        i=tf.constant(0)
        score_list = tf.constant(dtype=tf.int32, value=[])

    def cond(score_list, i):
        return tf.less(i, tf.shape(tens_y)[0])

    def body(score_list, i):
        locs_1 = tf.not_equal(tf.gather(tens_y, i), tens_x)
        locs = tf.reduce_any(locs_1, axis=1)
        ans = tf.reshape(tf.cast(tf.where(locs), dtype=tf.int32), [-1])
        score_list = tf.concat([score_list, ans], axis=0)

        return [score_list, tf.add(i, 1)]

    all_scores, _ = tf.while_loop(cond, body, loop_vars=[score_list, i],
                                  shape_invariants=[tf.TensorShape([None,]), i.get_shape()])

    uniq, __, counts = tf.unique_with_counts(all_scores)

    return tf.gather(tens_x,tf.gather(uniq, tf.where(counts > tf.shape(tens_y)[0] - 1)))


if __name__ == '__main__':
    tens_x = tf.constant([[1, 0, 1], [2, 0, 1], [3, 0, 1], [0, 0, 0]])
    tens_y = tf.constant([[1, 0, 1], [2, 0, 1]])

    results = diff(tens_x, tens_y)

with tf.Session() as sess:
    ans_ = sess.run(results)
    print(ans_)

[[[3 0 1]]

 [[0 0 0]]]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接