【问题标题】:How to compare an array against a list of arrays?如何将数组与数组列表进行比较?
【发布时间】:2021-05-18 19:48:59
【问题描述】:

假设我有一个列表,其中包含一堆 numpy ndarray(甚至是 torch 张量):

a, b, c = np.random.rand(3, 3), np.random.rand(3, 3), np.random.rand(3, 3)
collection = [a, b, c]

现在,如果我要检查数组 b 是否在 collection 中(假设我不知道 collection 中存在哪些数组),然后尝试:b in collection 会出现以下错误:

ValueError:具有多个元素的数组的真值不明确。使用 a.any() 或 a.all()

同样适用于包含数组的元组。

解决此问题的一种方法是进行列表理解:

True in [(b == x).all() for x in collection]

但是这需要一个for 循环,我想知道是否有更“有效”的方法来完成这个?

【问题讨论】:

    标签: python arrays python-3.x list numpy


    【解决方案1】:

    我会一直使用 numpy 数组:

    import numpy as np
    a, b, c = np.random.rand(3, 3), np.random.rand(3, 3), np.random.rand(3, 3)
    array = np.dstack([a, b, c])
    print(array.shape)
    # (3, 3, 3)
    np.all(array == b, axis=1).all(axis=1).any()
    # True
    

    【讨论】:

    • 非常好的解决方案:)
    • @Paul H 最后一行给了我 False。也许是 np.stack() 而不是 np.dstack()?
    【解决方案2】:

    您可以在 numpy 数组中沿 axis=0 堆叠任意形状的张量,然后一次将所有剩余的轴与 np.all 进行比较(这只是 PaulH 答案的稍微清晰的版本):

    ugly_shaped_tensor_list = [np.random.rand(3,7,5,3) for j in range(10)]
    known_tensor = ugly_shaped_tensor_list[1]
    
    # stack all tensors in a single array along axis=0:
    tensor_stack = np.stack(ugly_shaped_tensor_list)
    
    # compare all axes except the "list" axis, 0:
    matches = np.all(tensor_stack == known_tensor, axis=(1,2,3,4))
    # array([False,  True, False, False, False, False, False, False, False, False])
    matches.any()
    # True
    

    【讨论】:

    • 你能解释一下关键字“轴”到底指的是什么吗?就像如果它只设置为 2,那意味着什么,它到底在比较什么?
    • 将它们视为张量笛卡尔轴的标签。对于矩阵(嵌套数组),轴 0 == 行值,轴 1 == 列值
    【解决方案3】:

    好吧,这比预期的要简单得多......

    您实际上可以将您的数组/张量堆叠到一个更高维度(在这种情况下为深度/通道),然后结果是一个数组,它是一个集合所有其他数组,但独立存储在“不同维度”中。

    a, b, c = np.random.rand(3, 3), np.random.rand(3, 3), np.random.rand(3, 3)
    collection = np.stack((a, b, c))
    

    现在您可以简单地检查 collection 中的 b,就像您将其与列表进行比较一样:

    b in collection
    > True
    

    【讨论】:

      猜你喜欢
      • 2017-12-22
      • 2010-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-04
      • 2020-02-26
      • 2015-10-05
      • 1970-01-01
      相关资源
      最近更新 更多