0

我有一个构建为稀疏加权矩阵的数据集,我想为下游分组/聚类计算加权 Jaccard 索引,灵感来自以下文章:http ://static.googleusercontent.com/media/research.google.com/en //pubs/archive/36928.pdf

在寻找在 Python 中进行上述计算的最佳方法时,我遇到了一个小问题。我目前检验我的假设的功能如下:

def weighted_jaccard_index(x,y):
    mins, maxs = 0, 0
    for i in np.arange(len(x)):
        mins += np.amin([x[i],y[i]])
        maxs += np.amax([x[i],y[i]])
    return mins/maxs

from scipy.spatial.distance import pdist然后我通过传递我定义的函数来提供这个weighted_jaccard_index

w_j = pdist(X, weighted_jaccard_index)

但并不奇怪我看到了很大的性能问题。我目前正在研究将 MinHash 与datasketch包一起使用,但我很高兴就如何最好地实现这一点提出意见。我认为这样的事情是可能的:

df_np = df_gameinfo.to_numpy()
mg = ds.WeightedMinHashGenerator(20,20000)
lsh = ds.MinHashLSH(threshold=0.2,num_perm=20000)

#Create index in LSH
for i in np.arange(len(df_np)):
    vc = df_arr[i]
    m_hash = mg.minhash(vc)
    lsh.insert(i,m_hash)

test_ex = df.iloc[9522].to_numpy() #Random observations to calculate distance for
test_ex_m = mg.minhash(test_ex)

lsh.query(test_ex_m)

可能在 Numpy 中使用矢量化,但我不确定如何表达它。

数据的大小为 20k 观测值和 30 维(NxM = 20.000x30)。

4

1 回答 1

1

您可以使用连接:

q = np.concatenate([x,y], axis=1)
np.sum(np.amin(q,axis=1))/np.sum(np.amax(q,axis=1))

%%timeit -r 10 -n 10 对于 100 x 10 阵列,每个循环给出 131 µs ± 61.7 µs(10 次运行的平均值 ± 标准偏差,每次 10 个循环)。

您的原始函数给出:对于相同的数据,每个循环 4.46 ms ± 95.9 µs(平均值 ± 标准偏差,10 次运行,每次 10 个循环)

def jacc_index(x,y):
    q = np.concatenate([x,y], axis=1)
    return np.sum(np.amin(q,axis=1))/np.sum(np.amax(q,axis=1))
于 2022-02-26T11:17:41.203 回答