jaccard相似系数(Jaccard similarity coefficient)

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);

        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();
    }

 运行结果:

原文地址:https://www.cnblogs.com/qilin20/p/12260993.html