k-shingle

文档的k-shingle算法

本文主要是讲解以Java实现。首先得出两篇文档的k-shingle,然后计算他们的Jaccard相似度:

集合的Jaccard相似度

集合S和T的Jaccard相似度为|S∩T|/|S∩T|,也就是集合S和T的交集的集合和集合并集大小之间的比率。一般将和T的相似度记作SIM(S,T)。


k-shingle

一篇文档就是一个字符串。文档的k-shingle定义为其中任意长度为k的子串。

  • 假设文档D为字符串abcdabd,选择k = 2, 则文档中的所有2-shingle组成的集合为{ab,bc,cd,da,bd}。




计算 str1 = “ABCDE” 和 str2 = “ABCDF” 的 2-shingle 的jaccard相似度


- 当 k = 2时, str1 的 2-shingle 为集合A = {AB,BC,CD,DE},而str2的 2-shingle为集合B={AB,BC,CD,DF}。
- 因为A∪B = {AB,BC,CD,DE,DF},并且A∩B={AB,BC,CD},所以 SIM(A,B) = 3/5;


java代码实现

import java.util.*;

public class ShingleBased {
    public static void main(String args[]){
        ShingleBased j2 = new ShingleBased(2);
        // AB BC CD DE DF
        // 1  1  1  1  0
        // 1  1  1  0  1
        // => 3 / 5 = 0.6
        System.out.println(j2.similarity("ABCDE", "ABCDF"));
    }

    private int k;

    ShingleBased(final int k) {
        this.k = k;
    }

    public int getK() {
        return k;
    }

    public final Map<String, Integer> getProfile(String string) {
        HashMap<String, Integer> shingles = new HashMap<String, Integer>();

        for (int i = 0; i < (string.length() - k + 1); i++) {
            String shingle = string.substring(i, i + k);
            Integer old = shingles.get(shingle);
            if (old != null) {
                shingles.put(shingle, old + 1);
            } else {
                shingles.put(shingle, 1);
            }
        }

        return shingles;
    }

    public final double similarity(final String s1, final String s2) {

        if (s1.equals(s2)) {
            return 1;
        }

        Map<String, Integer> profile1 = getProfile(s1);
        Map<String, Integer> profile2 = getProfile(s2);


        Set<String> union = new HashSet<String>();
        union.addAll(profile1.keySet());
        union.addAll(profile2.keySet());

        int inter = profile1.keySet().size() + profile2.keySet().size()
                - union.size();

        return 1.0 * inter / union.size();
    }

}


参考

  • 大数据互联网大规模数据挖掘与分布式处理
  • github.
  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值