在 NumPy 中,命令
numpy.corrcoef(X.T)
在计算矩阵 X
中每对可能的列之间的相关性方面非常高效。我正在寻找一种类似有效的方法来计算二进制矩阵 B
的每个可能列之间的 Hamming距离。是否有一种 NumPy 方法可以适应这一点?
我尝试使用 SciPy 的
spatial.distance.pdist(X, metric = 'hamming')
,但它比 NumPy 的成对相关函数慢 100 倍。
按照@frank-yellin 的评论,我也尝试了
spatial.distance.pdist(X, metric = 'cityblock')
,但这仅将计算速度提高了 1.7 倍 - 这很棒,但如果可能的话,我希望速度提高约 100 倍。
import random
import numpy as np
import itertools
from scipy import stats, spatial
import time
binary_matrix = np.random.randint(0,2,(1000,1500),dtype = 'int32')
start = time.time()
hamming_with_scipy = spatial.distance.pdist(binary_matrix.T, metric = 'hamming')
end = time.time()
print(f'Hamming takes {end-start} seconds with scipy')
start = time.time()
corr_with_numpy = np.corrcoef(binary_matrix.T)
end = time.time()
print(f'Correlation takes {end-start} seconds with numpy')
输出:
Hamming takes 5.301102876663208 seconds with scipy
Correlation takes 0.03205609321594238 seconds with numpy