更新:发现了三倍的加速。在
这是一种在压缩位上使用numpy来节省内存的方法。要在这种格式与0s和1类型的uint8s之间进行转换,numpy提供了packbits和{}函数。在
下面的代码预计算所有2^16模式的和,这些模式可以由16位的块组成。在
(旧版本在数据和模板中查找字节对)
我们使用视图强制转换到uint64对64位的块执行按位交集,然后再转换回uint16进行查找。在
为了找到最接近的n,我们使用argpartition(O(N)),而不是{}(O(N logn))。在import numpy as np
n, m = 1_000_000, 1_000
data = np.random.randint(0, 256, (n, (m + 63) // 64 * 8), dtype=np.uint8)
test = np.random.randint(0, 256, ((m + 63) // 64 * 8,), dtype=np.uint8)
def create_lookup_1d():
x, p = np.ogrid[:1<<16, :16]
p = 1 << p
return np.count_nonzero(x & p, axis=1)
lookup_1d = create_lookup_1d()
def find_closest(data, test, n):
similarities = lookup_1d[(data.view(np.uint64) & test.view(np.uint64))
.view(np.uint16)].sum(axis=1)