python - 使用 np.newaxis 计算平方差之和

标签 python numpy

在 Jake VanderPlas 所著的《Python 数据科学手册》第 2 章中,他使用以下代码计算了多个二维点的平方差之和:

rand = np.random.RandomState(42)
X = rand.rand(10,2)
dist_sq = np.sum(X[:,np.newaxis,:] - X[np.newaxis,:,:]) ** 2, axis=-1)

两个问题:

  1. 为什么要创建第三个轴?可视化正在发生的事情的最佳方式是什么?
  2. 是否有更直观的方法来执行此计算?

最佳答案

Why is a third axis created? What is the best way to visualize what is going on?

在添加/减去技巧之前添加新维度是一种相对常见的方法,通过使用广播来生成所有对(None 与此处的 np.newaxis 相同) :

>>> a = np.arange(10)
>>> a[:,None]
array([[0],
       [1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7],
       [8],
       [9]])

>>> a[None,:]
array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])

>>> a[:,None] + 100*a[None,:]
array([[  0, 100, 200, 300, 400, 500, 600, 700, 800, 900],
       [  1, 101, 201, 301, 401, 501, 601, 701, 801, 901],
       [  2, 102, 202, 302, 402, 502, 602, 702, 802, 902],
       [  3, 103, 203, 303, 403, 503, 603, 703, 803, 903],
       [  4, 104, 204, 304, 404, 504, 604, 704, 804, 904],
       [  5, 105, 205, 305, 405, 505, 605, 705, 805, 905],
       [  6, 106, 206, 306, 406, 506, 606, 706, 806, 906],
       [  7, 107, 207, 307, 407, 507, 607, 707, 807, 907],
       [  8, 108, 208, 308, 408, 508, 608, 708, 808, 908],
       [  9, 109, 209, 309, 409, 509, 609, 709, 809, 909]])

您的示例执行相同的操作,只是在最内层使用 2 个向量而不是标量:

>>> X[:,np.newaxis,:].shape
(10, 1, 2)

>>> X[np.newaxis,:,:].shape
(1, 10, 2)

>>> (X[:,np.newaxis,:] - X[np.newaxis,:,:]).shape
(10, 10, 2)

由此我们发现,“神奇的减法”就是坐标X的所有组合相互相减。

Is there a more intuitive way to perform this calculation?

是的,使用scipy.spatial.distance.pdist作为成对距离。要获得与您的示例等效的结果:

from scipy.spatial.distance import pdist, squareform
dist_sq = squareform(pdist(X))**2

关于python - 使用 np.newaxis 计算平方差之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66071823/

相关文章:

python - 模块函数 vs 静态方法 vs 类方法 vs 无装饰器 : Which idiom is more pythonic?

python - 无法使用来自 Docker 容器的 SSH 隧道连接到远程数据库

python - 嵌套 numpy 运算

python - 从 numpy 制作数据框 - 为什么列是混合的?

python - numpy.genfromtxt 压平我的数据

python - NumPy 排序函数返回 None

python - Python 中的随机颜色

python - ImportError:Python 2.7.13 中没有名为 _tkinter 的模块

python - 使用 bool 数组掩码,将 False 值替换为 NaN

python - 如何将向量添加到矩阵