jaccard相似系數
jaccard相似系數(Jaccard similarity coefficient)主要應用場景為數據聚類、比較文本的相似度,用於文本的查重與去重,計算對象間的距離。
jaccard相似系數用於比較有限樣本集之間的相似性和差異性J(A,B)為A與B交集的大小與A與B並集的大小的比值。
實例
s1={1,3,4,5,7,8,9},s2={1,2,3,5,6,8},s1∩s2=“{1,3,5,8},s1∪s2={1,2,3,4,5,6,7,8,9},s1和s2的相似度為4/9。
J(A,B)∈(0,1)。jaccard值越大說明相似度越高,jaccard值越小說明相似度越低。
公式

Jaccard 距離
與Jaccard 相似系數相關的指標叫做Jaccard 距離,用於描述集合之間的不相似度。它是jaccard相似系數的補集,被定義為1減去Jaccard相似系數。
Jaccard 距離越大,樣本相似度越低。
公式定義如下:

jaccard相似系數 代碼實現
public double distance(String s1, String s2) {
if (s1 == null || s2 == null) {
throw new NullPointerException("字符串為空");
}
if (s1.equals(s2)){
return 1;
}
Map<String, Integer> h1 = getHashKey(s1);
Map<String, Integer> h2 = getHashKey(s2);
if (s1 == null || s2 == null) {
throw new NullPointerException("字符串為空");
}
if (s1.equals(s2)){
return 1;
}
Map<String, Integer> h1 = getHashKey(s1);
Map<String, Integer> h2 = getHashKey(s2);
Set<String> union = new HashSet<String>();
union.addAll(h1.keySet());
union.addAll(h2.keySet());
int flag = 0;
for (String key : union) {
if (h1.containsKey(key) && h2.containsKey(key)){
flag++;
}
}
return 1.0*flag / union.size();
}
union.addAll(h1.keySet());
union.addAll(h2.keySet());
int flag = 0;
for (String key : union) {
if (h1.containsKey(key) && h2.containsKey(key)){
flag++;
}
}
return 1.0*flag / union.size();
}
運行結果:

