【问题标题】:Cartesian product of two 2d arrays两个二维数组的笛卡尔积
【发布时间】:2016-02-24 22:40:57
【问题描述】:

假设我有一个 2d 图像,每个点都有相关的坐标 (x,y)。 我想在每个点 $i$ 与每隔一个点 $j$ 找到位置向量的内积。本质上是两个二维数组的笛卡尔积。

用 Python 最快的方法是什么?

我当前的实现如下所示:

def cartesian_product(arrays):
    broadcastable = np.ix_(*arrays)
    broadcasted = np.broadcast_arrays(*broadcastable)
    rows, cols = reduce(np.multiply, broadcasted[0].shape), len(broadcasted)
    out = np.empty(rows * cols, dtype=broadcasted[0].dtype)
    start, end = 0, rows
    for a in broadcasted:
        out[start:end] = a.reshape(-1)
        start, end = end, end + rows
    return out.reshape(cols, rows).T

def inner_product():
    x, y = np.meshgrid(np.arange(4),np.arange(4))

    cart_x = cartesian_product([x.flatten(),x.flatten()])
    cart_y = cartesian_product([y.flatten(),y.flatten()])

    Nx = x.shape[0]    

    xx = (cart_x[:,0]*cart_x[:,1]).reshape((Nx**2,Nx,Nx))
    yy = (cart_y[:,0]*cart_y[:,1]).reshape((Nx**2,Nx,Nx))

    inner_products = xx+yy
    return inner_products

(信用到期:cartesian_product 取自Using numpy to build an array of all combinations of two arrays

但这不起作用。对于较大的数组(例如 256x256),这会给我一个内存错误。

【问题讨论】:

    标签: python arrays numpy 2d cartesian-product


    【解决方案1】:

    您可能正在存储生成的笛卡尔积。
    您正在获取二维数组的乘积。 mxm 和 nxn 矩阵的乘积将产生 (mmn*n) 值。
    对于 256*256 矩阵,它将生成 2^32=4,294,967,296 个元素。 如果您不需要同时使用所有值,您可以尝试存储一些并处理它们,然后在生成下一个值之前将它们处理掉。

    采用笛卡尔积的更简单方法是:

    import itertools
    
    xMax = 2
    yMax = 2
    m1 = [ [ (x + y*xMax) for x in range(xMax)] for y in range(yMax)]
    print("m1=" + `m1`)
    m2 = [ [ chr(ord('a') + (x + y*xMax)) for x in range(xMax)] for y in range(yMax)]
    print("m2=" + `m2`)
    for x in m1 :
        for y in m2:
            for e in itertools.product(x,y): #generating xMax *xMax at at time, process one by one or in batch
                print e
    

    以上代码会产生如下输出

    m1=[[0, 1], [2, 3]]
    m2=[['a', 'b'], ['c', 'd']]
    (0, 'a')
    (0, 'b')
    (1, 'a')
    (1, 'b')
    (0, 'c')
    (0, 'd')
    (1, 'c')
    (1, 'd')
    (2, 'b')
    (2, 'a')
    (3, 'a')
    (3, 'b')
    (2, 'c')
    (2, 'd')
    (3, 'c')
    (3, 'd')
    

    【讨论】:

      猜你喜欢
      • 2018-11-21
      • 2017-03-05
      • 1970-01-01
      • 2021-07-16
      • 2011-12-18
      • 2011-01-31
      • 2015-06-16
      • 2020-12-10
      相关资源
      最近更新 更多