2

在下面的代码中,我们计算所有给定点对之间的向量大小。为了在 NumPy 中加速这个操作,我们可以使用广播

import numpy as np
points = np.random.rand(10,3)

pair_vectors = points[:,np.newaxis,:] - points[np.newaxis,:,:]
pair_dists = np.linalg.norm(pair_vectors,axis=2).shape

或外部产品迭代

it = np.nditer([points,points,None], flags=['external_loop'], op_axes=[[0,-1,1],[-1,0,1],None])
for a,b,c in it:
    c[...] = b - a
pair_vectors = it.operands[2]
pair_dists = np.linalg.norm(pair_vectors,axis=2)

我的问题是如何使用广播或外部产品迭代来创建一个格式为 10x10x6 的数组,其中最后一个轴包含一对(扩展)中两个点的坐标。并且以相关的方式,是否可以直接使用广播或外积迭代来计算对距离,即在不首先计算差异向量(约简)的情况下产生形式为 10x10 的矩阵。

为了澄清,以下代码使用慢循环创建所需的矩阵。

pair_coords = np.zeros(10,10,6)
pair_dists = np.zeros(10,10)
for i in range(10):
    for j in range(10):
        pair_coords[i,j,0:3] = points[i,:]
        pair_coords[i,j,3:6] = points[j,:]
        pair_dists[i,j] = np.linalg.norm(points[i,:]-points[j,:])

这是使用外积迭代计算距离(或应用任何其他函数,该函数采用一对中两个点的 6 个坐标并产生一个标量)的失败尝试。

res = np.zeros((10,10))
it = np.nditer([points,points,res], flags=['reduce_ok','external_loop'], op_axes=[[0,-1,1],[-1,0,1],None])
for a,b,c in it: c[...] = np.linalg.norm(b-a)
pair_dists = it.operands[2]
4

1 回答 1

1

这是一种以矢量化方式生成这些数组的方法 -

from itertools import product
from scipy.spatial.distance import pdist, squareform

N = points.shape[0]

# Get indices for selecting rows off points array and stacking them 
idx = np.array(list(product(range(N),repeat=2)))
p_coords = np.column_stack((points[idx[:,0]],points[idx[:,1]])).reshape(N,N,6)

# Get the distances for upper triangular elements. 
# Then create a symmetric one for the final dists array.
p_dists = squareform(pdist(points))

很少有其他矢量化方法在 中讨论this post,所以也看看那里!

于 2016-11-13T11:58:31.330 回答