Python 什么是计算具有复数的超大矩阵的欧几里德距离的最快方法?

Python 什么是计算具有复数的超大矩阵的欧几里德距离的最快方法?,python,numpy,complex-numbers,euclidean-distance,Python,Numpy,Complex Numbers,Euclidean Distance,我有一个非常大的输入数据集,包含50000个9维样本(即50000x9矩阵)。此数据已使用DFT进行转换: dft_D = data.dot(dft(9).T) / np.sqrt(9) 我想计算每对行的欧几里德距离。我发现当使用实数矩阵时,scipy.space.distance.pdist是计算欧几里德距离最快的(例如,在数据上计算距离需要~`15秒)。但是,此函数不适用于复数 我尝试了中介绍的解决方案,但这给了我严重的内存问题(即“无法为具有形状(50000、50000、9)和数据类型复

我有一个非常大的输入数据集,包含50000个9维样本(即50000x9矩阵)。此数据已使用DFT进行转换:

dft_D = data.dot(dft(9).T) / np.sqrt(9)
我想计算每对行的欧几里德距离。我发现当使用实数矩阵时,
scipy.space.distance.pdist
是计算欧几里德距离最快的(例如,在
数据上计算距离需要~`15秒)。但是,此函数不适用于复数

我尝试了中介绍的解决方案,但这给了我严重的内存问题(即“无法为具有形状(50000、50000、9)和数据类型复杂128的阵列分配191.GiB”)。我也尝试过使用中定义的EDM,但这也给了我类似的内存问题

最初,我能够通过使用定义
np.sqrt(np.sum(np.square(np.abs(data[I,:]-data[j,:]))对行和列进行迭代来计算这些欧几里德距离。这太慢了。然后,我使用了for
sklearn.metrics.pairwise.euclidean_distance
(这也不适用于复数)中描述的定义,它稍微快一点,但仍然非常慢(运行时间超过2小时)

这是我的最终结果(注意,由于距离矩阵是对称的,所以我只计算全距离矩阵的一半)

当涉及复数时,有没有更快的方法获得这些距离?

您可以使用numpy.roll()以循环方式移动输入数组的行。它重复了大量的计算,但速度要快得多。下面的代码填充距离矩阵的下半部分

dist_matrix = np.empty(shape = [inp_arr.shape[0], inp_arr.shape[0]])
for i in range(inp_arr.shape[0]):
    shifted_arr = np.roll(inp_arr, i, axis = 0)
    curr_dist = np.sqrt(np.sum(np.square(np.abs(inp_arr - shifted_arr)), axis = 1))
    for j in range(i, inp_arr.shape[0]):
        dist_matrix[j, j - i] = curr_dist[j]

我不明白你对dft的定义。但是,如果您试图计算原始数据的DFT行之间的距离,这将与原始数据行之间的距离相同

根据,向量的大小及其变换是相同的。通过线性,两个向量的差的变换等于它们的变换的差。由于欧几里德距离是差值大小的平方根,因此使用哪个域计算度量并不重要。我们可以用一个小样本来演示:

import numpy as np
import scipy.spatial

x = np.random.random((500,9)) #Use a smaller data set for the demo
Sx = np.fft.fft(x)/np.sqrt(x.shape[1]) #numpy fft doesn't normalize by default
xd = scipy.spatial.distance.pdist(x,metric='euclidean')
Sxd = np.array([np.sqrt(np.sum(np.square(np.abs(Sx[i,:] - Sx[j,:])))) for i in range(Sx.shape[0]) for j in range(Sx.shape[0])]).reshape((Sx.shape[0],Sx.shape[0])) #calculate the full square of pairwise distances
Sxd = scipy.spatial.distance.squareform(Sxd) #use scipy helper function to get back the same format as pdist
np.all(np.isclose(xd,Sxd)) # Should print True

因此,只需在原始数据上使用
pdist

您的代码没有运行,因为
norm\u data
e
(在
dist\u matrix[e]
中)没有定义。@mtrw啊,谢谢,这已经修复了!谢谢你的回复。我需要从数据的DFT中提取前三列(即前三个“系数”),并计算所得40000x3矩阵上的距离以进行比较。
import numpy as np
import scipy.spatial

x = np.random.random((500,9)) #Use a smaller data set for the demo
Sx = np.fft.fft(x)/np.sqrt(x.shape[1]) #numpy fft doesn't normalize by default
xd = scipy.spatial.distance.pdist(x,metric='euclidean')
Sxd = np.array([np.sqrt(np.sum(np.square(np.abs(Sx[i,:] - Sx[j,:])))) for i in range(Sx.shape[0]) for j in range(Sx.shape[0])]).reshape((Sx.shape[0],Sx.shape[0])) #calculate the full square of pairwise distances
Sxd = scipy.spatial.distance.squareform(Sxd) #use scipy helper function to get back the same format as pdist
np.all(np.isclose(xd,Sxd)) # Should print True