在 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)
两个问题:
- 为什么要创建第三个轴?可视化正在发生的事情的最佳方式是什么?
- 是否有更直观的方法来执行此计算?
最佳答案
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/