gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:09:40 26 4
gpt4 key购买 nike

我想做的是检查张量 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]]]

我想要的是一个单一的 bool 值(True 或 False)来告诉 t1 是否存在于 t2 中。有点像

if your_method(t2, t1):
print("Yes, t1 is contained in t2.")

是否有完全pythonic的方法来做到这一点?
另外,我检查了一下,不再支持 tf.listdiff() 。

编辑:

好的,我找到了 tf.math.reduce_all()可以应用于

的上述输出张量的方法
[[[True False True] [True True True]]]

将其简化为像

这样的张量

[[[真假真]]]

但我仍然不知道如何从中获得正确答案(这将是一个 True 的 bool 值)。
另外,如果我申请 tf.math.reduce_any()

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

可以简化为

[[[True True True]]]

(再次给我一个张量而不是单个 bool 值)然后如果我假设答案为 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. 使用 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.

关于python - 如何检查一个张量是否存在于另一个张量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53920189/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com