有没有一种方法可以测试两个形状是否可以在 numpy 中广播?

Is there a method to test whether two shapes can be broadcast in numpy?

numpy 是否有一种方法来测试是否可以在不创建数组的情况下广播形状?简而言之,我正在寻找一个提供以下输出的函数。

can_broadcast((1, 2), (2, 1))  # True
can_broadcast((1, 2), (2, 3))  # False

当然,我可以使用

模拟行为
def can_broadcast(s1, s2):
    try:
        np.empty(s1) + np.empty(s2)
        return True
    except ValueError:
        return False

或者建立我自己的逻辑。有内置的东西吗?

据我所知,内置函数使用数组而不是仅使用形状。所以,我不知道有什么内置的可以解决它。这是我可以想出的一个,基本上是寻找 singleton 维度,即 dimension lengths = 1 并检查维度长度是否匹配并满足其中一个标准让我们 True 成为 [=15] =]-

def can_broadcast(s1, s2):
    s1a = np.asarray(s1)
    s2a = np.asarray(s2)
    return ((s1a == 1) | (s2a==1) | (s2a == s1a)).all()

样品运行 -

In [335]: s1 = (1, 2, 1, 3)
     ...: s2 = (2, 3, 3, 3)
     ...: s3 = (1, 1, 3, 3)
     ...: 

In [336]: print can_broadcast(s1, s2)
     ...: print can_broadcast(s1, s3)
     ...: print can_broadcast(s2, s3)
     ...: 
False
True
True