在 numpy.narray
中映射函数的常规方法,例如 np.array[map(some_func,x)]
或 vectorize(f)( x)
无法提供索引。
以下代码只是一个在许多应用程序中常见的简单示例。
dis_mat = np.zeros([feature_mat.shape[0], feature_mat.shape[0]])
for i in range(feature_mat.shape[0]):
for j in range(i, feature_mat.shape[0]):
dis_mat[i, j] = np.linalg.norm(
feature_mat[i, :] - feature_mat[j, :]
)
dis_mat[j, i] = dis_mat[i, j]
有没有办法加快速度?
感谢您的帮助!使用 @user2357112 评论的函数,加快此代码速度的最快方法是:
from scipy.spatial.distance import pdist,squareform
dis_mat = squareform(pdist(feature_mat))
@Julien 的 method 如果 feature_mat
很小也不错,但是当 feature_mat
到 2000 年为 1000 时,它需要将近 40 GB 的内存。
最佳答案
SciPy 带有一个专门用于计算您正在计算的成对距离类型的函数。它是 scipy.spatial.distance.pdist
, 它以压缩格式生成距离,基本上只存储距离矩阵的上三角形,但您可以使用 scipy.spatial.distance.squareform
将结果转换为正方形形式:
from scipy.spatial.distance import pdist, squareform
distance_matrix = squareform(pdist(feature_mat))
这样做的好处是避免了直接矢量化解决方案所需的巨大中间数组,因此它更快并且适用于更大的输入。它失去了到 an approach that uses algebraic manipulations to have dot
handle the heavy lifting 的时间。 ,不过。
pdist
还支持多种替代距离指标,如果您决定想要欧几里德距离以外的其他指标。
# Manhattan distance!
distance_matrix = squareform(pdist(feature_mat, 'cityblock'))
# Cosine distance!
distance_matrix = squareform(pdist(feature_mat, 'cosine'))
# Correlation distance!
distance_matrix = squareform(pdist(feature_mat, 'correlation'))
# And more! Check out the docs.
关于python - 是否可以在 Python 中加速这个循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47566072/