大阵列的 3D 中两点之间的距离

Kat*_*eva 2 python numpy distance scikit-learn

我有一个数组n× m,其中n = 217000m = 3(来自望远镜的一些数据)。

我需要计算 3D 中 2 个点之间的距离(根据我在列中的 x、y、z 坐标)。

当我尝试使用sklearn工具时,结果是:

ValueError: array is too big; `arr.size * arr.dtype.itemsize` is larger than the maximum possible size.
Run Code Online (Sandbox Code Playgroud)

在这种情况下我可以使用什么工具以及该工具的最大可能尺寸是多少?

Ton*_*has 5

在这种情况下我可以使用什么工具......?

您可以使用@Saksow 建议的方法自行实现欧几里得距离函数。假设ab是一维 NumPy 数组,您还可以使用此线程中提出的任何方法:

import numpy as np
np.linalg.norm(a-b)
np.sqrt(np.sum((a-b)**2))
np.sqrt(np.dot(a-b, a-b))
Run Code Online (Sandbox Code Playgroud)

如果您想一次性计算所有点之间的成对距离(不一定是欧几里德距离)米*米数组,模块scipy.spatial.distance是你的朋友。

演示:

In [79]: from scipy.spatial.distance import squareform, pdist

In [80]: arr = np.asarray([[0, 0, 0],
    ...:                   [1, 0, 0],
    ...:                   [0, 2, 0],
    ...:                   [0, 0, 3]], dtype='float')
    ...: 

In [81]: squareform(pdist(arr, 'euclidean'))
Out[81]: 
array([[ 0.        ,  1.        ,  2.        ,  3.        ],
       [ 1.        ,  0.        ,  2.23606798,  3.16227766],
       [ 2.        ,  2.23606798,  0.        ,  3.60555128],
       [ 3.        ,  3.16227766,  3.60555128,  0.        ]])

In [82]: squareform(pdist(arr, 'cityblock'))
Out[82]: 
array([[ 0.,  1.,  2.,  3.],
       [ 1.,  0.,  3.,  4.],
       [ 2.,  3.,  0.,  5.],
       [ 3.,  4.,  5.,  0.]])
Run Code Online (Sandbox Code Playgroud)

请注意,此玩具示例中使用的模拟数据数组中的点数为 n=4 结果成对距离数组有 n^2=16 元素。

...以及此工具的最大可能尺寸是多少?

如果您尝试使用您的数据应用上述方法(n=217000) 你得到一个错误:

In [105]: data = np.random.random(size=(217000, 3))

In [106]: squareform(pdist(data, 'euclidean'))
Traceback (most recent call last):

  File "<ipython-input-106-fd273331a6fe>", line 1, in <module>
    squareform(pdist(data, 'euclidean'))

  File "C:\Users\CPU 2353\Anaconda2\lib\site-packages\scipy\spatial\distance.py", line 1220, in pdist
    dm = np.zeros((m * (m - 1)) // 2, dtype=np.double)

MemoryError
Run Code Online (Sandbox Code Playgroud)

问题是您的 RAM 不足。要执行此类计算,您需要超过 350TB!所需的内存量是将距离矩阵的元素数 (217000 2 )乘以该矩阵的每个元素的字节数 (8),然后将该乘积除以适当的因子 (1024 3 ) 来表示结果以千兆字节为单位:

In [107]: round(data.shape[0]**2 * data.dtype.itemsize / 1024.**3)
Out[107]: 350.8
Run Code Online (Sandbox Code Playgroud)

因此,您的数据允许的最大大小取决于可用 RAM 的数量(有关更多详细信息,请查看此线程)。