有没有办法对 scipy.sparse 矩阵进行快速布尔运算?

Is there a way to have fast boolean operations on scipy.sparse matrices?

我必须解决非常高维 (~30'000) 向量的 XOR 运算以计算汉明距离。例如,我需要计算一个充满 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 维的向量相同。

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

如果你的向量是高度稀疏的(比如 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))