我有一個構建為稀疏加權矩陣的資料集,我想為下游分組/聚類計算加權 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)。
uj5u.com熱心網友回復:
您可以使用連接:
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))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/433838.html
