shingling算法用于计算两个文档的相似度,例如,用于网页去重。维基百科对w-shingling的定义如下:
In natural language processing a w-shingling is a set of unique "shingles"contiguous subsequences of tokens in a document —that can be used to gauge the similarity of two documents. The w denotes the number of tokens in each shingle in the set.
维基百科用一个浅显的例子讲解了shingling算法的原理。
比如,一个文档 "a rose is a rose is a rose" ,分词后的词汇(token,语汇单元)集合是:(a,rose,is,a,rose,is, a, rose)
那么w=4的4-shingling就是集合:
{ (a,rose,is,a), (rose,is,a,rose), (is,a,rose,is), (a,rose,is,a), (rose,is,a,rose)}
去掉重复的子集合:
{ (a,rose,is,a), (rose,is,a,rose), (is,a,rose,is) }
给定shingle的大小,两个文档A和B的相似度 r 定义为: r(A,B)=|S(A)∩S(B)|/|S(A)∪S(B)| ,其中|A|表示集合A的大小。 因此,相似度是介于0和1之间的一个数值,且r(A,A)=1,即一个文档和它自身 100%相似。 假设A([b1,…,bm])是包含m个二进制字符的二进制字符串,那么可以根据A构造相应的(m-1)度的多项式如下,其中t是不定元。
A(t)=b1tm-1 + b2tm-2+…+bm-1t+bm (1)
给定一个度为k的多项式P(t),如下:
P(t)=a1tk+a2tk-1+…+ak-1t+ak (2)
那么A(t) 除以P(t)的余数f (t)的度数为(k-1)。对于给定的字符串A,定义A的指纹f(A)如下:
f(A)=A(t) mod P(t) (3)