我必须对非常高维(~30'000)向量进行异或运算来计算汉明距离。例如,我需要计算一个充满 False 的向量与 16 个稀疏位置的 True 之间的异或运算,以及 50'000x30'000 矩阵的每一行。
到目前为止,我发现最快的方法是不使用 scipy.sparse 而是对每行使用简单的 ^ 操作。
这个:
l1distances=(self.hashes[index,:]^self.hashes[all_points,:]).sum(axis=1)
恰好比这个快十倍:
sparse_hashes = scipy.sparse.csr_matrix((self.hashes)).astype('bool')
for i in range(all_points.shape[0]):
l1distances[0,i]=(sparse_hashes[index]-sparse_hashes[all_points[i]]).sum()
但是快十倍仍然很慢,因为从理论上讲,具有 16 个激活的稀疏向量应该使计算与具有 16 维向量相同。
有什么解决办法吗?我真的很挣扎,谢谢你的帮助!
最佳答案
如果你的向量高度稀疏(比如 16/30000),我可能会完全跳过稀疏异或的操作。
from scipy import sparse
import numpy as np
import numpy.testing as npt
matrix_1 = sparse.random(10000, 100, density=0.1, format='csc')
matrix_1.data = np.ones(matrix_1.data.shape, dtype=bool)
matrix_2 = sparse.random(1, 100, density=0.1, format='csc', dtype=bool)
vec = matrix_2.A.flatten()
# Pull out the part of the sparse matrix that matches the vector and sum it after xor
matrix_xor = (matrix_1[:, vec].A ^ np.ones(vec.sum(), dtype=bool)[np.newaxis, :]).sum(axis=1)
# Sum the part that doesnt match the vector and add it
l1distances = matrix_1[:, ~vec].sum(axis=1).A.flatten() + matrix_xor
# Double check that I can do basic math
npt.assert_array_equal(l1distances, (matrix_1.A ^ vec[np.newaxis, :]).sum(axis=1))
关于python - 有没有办法对 scipy.sparse 矩阵进行快速 bool 运算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65092272/