我有20,000个文档,我想计算真正的Jaccard相似度,以便稍后我可以检查MinWise散列的准确度是近似的。
每个文档都表示为numpy矩阵中的一列,其中每一行都是出现在文档(entry = 1)或不出现(entry = 0)的单词。有大约600个单词(行)。
因此,例如,第1列将是[1 0 0 0 0 0 1 0 0 0 1 0],这意味着单词1,7,11出现在其中而没有其他单词。
除了我的元素比较方法之外,还有更有效的方法来计算相似性吗?我不知道如何使用集合来提高速度,因为集合刚刚变为(0,1),但是现在代码变得非常慢。
import numpy as np
#load file into python
rawdata = np.loadtxt("myfile.csv",delimiter="\t")
#Convert the documents from rows to columns
rawdata = np.transpose(rawdata)
#compute true jacard similarity
ndocs = rawdata.shape[1]
nwords = rawdata.shape[0]
tru_sim = np.zeros((ndocs,ndocs))
#computes jaccard similarity of 2 documents
def jaccard(c1, c2):
n11 = sum((c1==1)&(c2==1))
n00 = sum((c1==0)&(c2==0))
jac = n11 / (nfeats-n00)
return (jac)
for i in range(0,ndocs):
tru_sim[i,i]=1
for j in range(i+1,ndocs):
tru_sim[i,j] = jaccard(rawdata[:,i],rawdata[:,j])
答案 0 :(得分:4)
这是一种矢量化方法 -
# Get the row, col indices that are to be set in output array
r,c = np.tril_indices(ndocs,-1)
# Use those indicees to slice out respective columns
p1 = rawdata[:,c]
p2 = rawdata[:,r]
# Perform n11 and n00 vectorized computations across all indexed columns
n11v = ((p1==1) & (p2==1)).sum(0)
n00v = ((p1==0) & (p2==0)).sum(0)
# Finally, setup output array and set final division computations
out = np.eye(ndocs)
out[c,r] = n11v / (nfeats-n00v)
使用np.einsum
-
n11v
和n00v
的替代方法
n11v = np.einsum('ij,ij->j',(p1==1),(p2==1).astype(int))
n00v = np.einsum('ij,ij->j',(p1==0),(p2==0).astype(int))
如果rawdata
仅由0s
和1s
组成,则获得这些内容的更简单方法是 -
n11v = np.einsum('ij,ij->j',p1,p2)
n00v = np.einsum('ij,ij->j',1-p1,1-p2)
<强>基准强>
功能定义 -
def original_app(rawdata, ndocs, nfeats):
tru_sim = np.zeros((ndocs,ndocs))
for i in range(0,ndocs):
tru_sim[i,i]=1
for j in range(i+1,ndocs):
tru_sim[i,j] = jaccard(rawdata[:,i],rawdata[:,j])
return tru_sim
def vectorized_app(rawdata, ndocs, nfeats):
r,c = np.tril_indices(ndocs,-1)
p1 = rawdata[:,c]
p2 = rawdata[:,r]
n11v = ((p1==1) & (p2==1)).sum(0)
n00v = ((p1==0) & (p2==0)).sum(0)
out = np.eye(ndocs)
out[c,r] = n11v / (nfeats-n00v)
return out
验证和时间安排 -
In [6]: # Setup inputs
...: rawdata = (np.random.rand(20,10000)>0.2).astype(int)
...: rawdata = np.transpose(rawdata)
...: ndocs = rawdata.shape[1]
...: nwords = rawdata.shape[0]
...: nfeats = 5
...:
In [7]: # Verify results
...: out1 = original_app(rawdata, ndocs, nfeats)
...: out2 = vectorized_app(rawdata, ndocs, nfeats)
...: print np.allclose(out1,out2)
...:
True
In [8]: %timeit original_app(rawdata, ndocs, nfeats)
1 loops, best of 3: 8.72 s per loop
In [9]: %timeit vectorized_app(rawdata, ndocs, nfeats)
10 loops, best of 3: 27.6 ms per loop
那里有一些神奇的 300x+
加速!
那么,它为什么这么快?嗯,有很多因素,最重要的是NumPy数组是为性能而构建的,并针对矢量化计算进行了优化。通过提出的方法,我们可以很好地利用它,从而看到这样的加速。
这里有一个related Q&A
详细讨论这些效果标准。
答案 1 :(得分:2)
要计算Jaccard,请使用:
#include<iostream>
using namespace std;
int main()
{
char sentence[100]={'\0'}, word[100]={'\0'};
cin.getline(sentence,100);
for(int i = 0; sentence[i] != 32 || sentence[i] != '\0'; i++)
{
word[i]=sentence[i];
}
cout << word;
}