python - 有没有办法对 scipy.sparse 矩阵进行快速 bool 运算?

标签 python hash sparse-matrix lsh

我必须对非常高维(~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/

相关文章:

python - 使用 Pandas 计算rolling.mean 时忽略给定列的先前值

algorithm - 在 kNN 中处理不完整数据(数据稀疏性)

python - 使用 scipy 的各种稀疏矩阵乘积的性能

multidimensional-array - 礼拜堂简陋的微妙之处

java - 类图中的 HashMap (UML)

python - 使用强化学习精炼边界框

python - QMessageBox.Yes/QMessageBox.No 的值

Python webdriver : driver. get(URL) 无法在单元测试中打开 - 通过控制台工作

algorithm - 麻省理工学院讲座错了吗?散列中的开放寻址分析

perl - 比较两个数组哈希是否相等