Test if an array is broadcastable to a shape?

后端 未结 5 1889
灰色年华
灰色年华 2021-01-21 16:39

What is the best way to test whether an array can be broadcast to a given shape?

The \"pythonic\" approach of trying doesn\'t work for my case, because the

5条回答
  •  孤独总比滥情好
    2021-01-21 17:01

    If you just want to avoid materializing an array with a given shape, you can use as_strided:

    import numpy as np
    from numpy.lib.stride_tricks import as_strided
    
    def is_broadcastable(shp1, shp2):
        x = np.array([1])
        a = as_strided(x, shape=shp1, strides=[0] * len(shp1))
        b = as_strided(x, shape=shp2, strides=[0] * len(shp2))
        try:
            c = np.broadcast_arrays(a, b)
            return True
        except ValueError:
            return False
    
    is_broadcastable((1000, 1000, 1000), (1000, 1, 1000))  # True
    is_broadcastable((1000, 1000, 1000), (3,))  # False
    

    This is memory efficient, since a and b are both backed by a single record

提交回复
热议问题