如何检查一个张量是否存在于另一个张量中?

3
我想要做的是检查张量 t1 = [[[1. , 2. , 3.4]]] 是否存在于另一个张量 t2 = [[[1. , 5. , 3.4], [1. , 2. , 3.4]]] 中。我尝试使用 tf.equal(),但它返回了以下结果。
tf.equal(t2, t1) # Output : [[[True False True] [True True True]]]

我需要的是一个布尔值(True或False),用于判断t1是否存在于t2中。 类似于:
if your_method(t2, t1):
  print("Yes, t1 is contained in t2.")

有没有一种完全符合Python规范的方法来做到这一点?
此外,我已经检查过了,tf.listdiff()不再受支持。

编辑:

好的,我找到了一个tf.math.reduce_all()方法,可以应用于上面的输出张量

[[[True False True] [True True True]]]

将其缩减为类似张量的形式
[[[True False True]]]
但我仍然不知道如何从中获得正确答案(应为单个布尔值True)。 此外,如果我将tf.math.reduce_any()应用于
[[[True False True] [True True True]]]
它可以被缩减为
[[[True True True]]]
(再次给我一个张量而不是单个布尔值),然后如果我假设答案将为True,因为结果张量的所有元素都为True,则这是不正确的,因为tf.math.reduce_all()对于tf.equal()的输出也会给出类似的结果,即
[[[True False True] [False True False]]]
也就是说,例如 t1 = [[[1., 2., 3.4]]]t2 = [[[1., 5., 3.4], [6., 2., 7.8]]]
希望这能帮到你。

1
这里 in 运算符有用吗? - Mad Physicist
在numpy中,您可以使用equal的结果:np.any(np.all(np.equal(t2, t1), axis=1))。我期望tf有一组类似的操作。 - Mad Physicist
@MadPhysicist 不是的,in 操作符返回了 false。 - Anubhav Pandey
我认为你不需要将任何东西转换成numpy。我对tf不是非常熟悉,但我猜它会有任何和所有的方法。 - Mad Physicist
@MadPhysicist,我刚刚检查了一下,TensorFlow没有 tf.any() 或 tf.all() 方法,但是它有一个 tf.reduce_any() 方法,可以在包含布尔值的张量维度上执行“逻辑或”操作。 - Anubhav Pandey
这正是你要找的。此外,我希望这些方法是张量类的一部分,而不一定是tf模块本身。 - Mad Physicist
1个回答

2

你有两个选择。

  1. 使用numpy

首先评估张量以获取各自张量的numpy数组,然后使用in运算符。

t1_array = t1.eval()
t2_array = t2.eval()
t1_array in t2_array # this will be true if t2 contians t1.

2. 使用tensorflow的 equal, reduce_anyreduce_all 方法。

# check equality of array in t1 for each array in t2 element by element. This is possible because the equal function supports broadcasting. 
equal =  tf.math.equal(t1, t2)
# checking if all elements from  t1 match for all elements of some array in t2
equal_all = tf.reduce_all(equal, axis=2)
contains = tf.reduce_any(equal_all)

编辑

如果启用了急切执行

contains = t1.numpy() in t2.numpy() # this will be true if t2 contians t1.

请注意,在 reduce_all 中的 axis=2 假设您要比较的张量具有特定的形状,例如 (n, m) vs (m, n) 将需要不同的轴。此答案中的轴是针对问题中的张量特定的。 - joel
在numpy中,in运算符并不像你期望的那样工作。例如,np.array([[[1., 2., 3.4]]]) in np.array([[[1., 3., 100.]]])返回True - rchome
在numpy中,in运算符并不像你期望的那样工作。例如,np.array([[[1., 2., 3.4]]]) in np.array([[[1., 3., 100.]]])的结果是True - undefined

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