python - 在 Numpy 中减少或扩展广播

标签 python numpy array-broadcasting

在下面的代码中,我们计算所有给定点对之间的向量大小。为了在 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]

最佳答案

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

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 中几乎没有讨论其他矢量化方法。 ,所以也去那里看看吧!

关于python - 在 Numpy 中减少或扩展广播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40569650/

相关文章:

python - 如何防止Python IDLE在运行新脚本时重新启动

python - 为什么下面示例中的 python 广播比简单循环慢?

python - 锯齿状/参差不齐的 Numpy.array 的乘法定义是什么?

python - 如何沿矩阵轴执行滚动求和?

python - 将 pandas 时间序列数据导入本地主机上的 mysql 数据库时出错

python - botocore:如何关闭或清理 session 或客户端

python - 给定一个可以在字典的元组键之间找到的整数,在字典中查找值

python - 如何使用 IPython/NumPy 计算 RMSE?

python - 从索引矩阵填充矩阵

Julia:跨观测张量广播成对距离计算