0
假设我有一个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),这给我一个内存错误。