2

我必须解决非常高维(~30'000)向量的异或运算来计算汉明距离。例如,我需要计算一个充满 False 的向量与 16 个稀疏定位的 True 与 50'000x30'000 矩阵的每一行之间的 XOR 运算。

截至目前,我发现最快的方法是不使用 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 维一维相同。

有什么解决办法吗?我在这里真的很挣扎,感谢您的帮助!

4

1 回答 1

1

如果您的向量非常稀疏(例如 16/30000),我可能会完全跳过对稀疏 xor 的摆弄。

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))
于 2020-12-01T21:09:07.253 回答