Java根據余弦定理計算文本相似度


項目中需要算2個字符串的相似度,是根據余弦相似性算的,下面具體介紹一下:

余弦相似度計算

余弦相似度用向量空間中兩個向量夾角的余弦值作為衡量兩個個體間差異的大小。余弦值越接近1,就表明夾角越接近0度,也就是兩個向量越相似,這就叫"余弦相似性"。

 

我們知道,對於兩個向量,如果他們之間的夾角越小,那么我們認為這兩個向量是越相似的。余弦相似性就是利用了這個理論思想。它通過計算兩個向量的夾角的余弦值來衡量向量之間的相似度值。余弦相似性推導公式如下:

 

public class Cosine {

    public static double getSimilarity(String doc1, String doc2) {
        if (doc1 != null && doc1.trim().length() > 0 && doc2 != null&& doc2.trim().length() > 0) {

            Map<Integer, int[]> AlgorithmMap = new HashMap<Integer, int[]>();

            //將兩個字符串中的中文字符以及出現的總數封裝到,AlgorithmMap中
            for (int i = 0; i < doc1.length(); i++) {
                char d1 = doc1.charAt(i);
                if(isHanZi(d1)){//標點和數字不處理
                    int charIndex = getGB2312Id(d1);//保存字符對應的GB2312編碼
                    if(charIndex != -1){
                        int[] fq = AlgorithmMap.get(charIndex);
                        if(fq != null && fq.length == 2){
                            fq[0]++;//已有該字符,加1
                        }else {
                            fq = new int[2];
                            fq[0] = 1;
                            fq[1] = 0;
                            AlgorithmMap.put(charIndex, fq);//新增字符入map
                        }
                    }
                }
            }

            for (int i = 0; i < doc2.length(); i++) {
                char d2 = doc2.charAt(i);
                if(isHanZi(d2)){
                    int charIndex = getGB2312Id(d2);
                    if(charIndex != -1){
                        int[] fq = AlgorithmMap.get(charIndex);
                        if(fq != null && fq.length == 2){
                            fq[1]++;
                        }else {
                            fq = new int[2];
                            fq[0] = 0;
                            fq[1] = 1;
                            AlgorithmMap.put(charIndex, fq);
                        }
                    }
                }
            }

            Iterator<Integer> iterator = AlgorithmMap.keySet().iterator();
            double sqdoc1 = 0;
            double sqdoc2 = 0;
            double denominator = 0;
            while(iterator.hasNext()){
                int[] c = AlgorithmMap.get(iterator.next());
                denominator += c[0]*c[1];
                sqdoc1 += c[0]*c[0];
                sqdoc2 += c[1]*c[1];
            }

            return denominator / Math.sqrt(sqdoc1*sqdoc2);//余弦計算
        } else {
            throw new NullPointerException(" the Document is null or have not cahrs!!");
        }
    }

    public static boolean isHanZi(char ch) {
        // 判斷是否漢字
        return (ch >= 0x4E00 && ch <= 0x9FA5);
        /*if (ch >= 0x4E00 && ch <= 0x9FA5) {//漢字
            return true;
        }else{
            String str = "" + ch;
            boolean isNum = str.matches("[0-9]+");
            return isNum;
        }*/
        /*if(Character.isLetterOrDigit(ch)){
            String str = "" + ch;
            if (str.matches("[0-9a-zA-Z\\u4e00-\\u9fa5]+")){//非亂碼
                return true;
            }else return false;
        }else return false;*/
    }

    /**
     * 根據輸入的Unicode字符,獲取它的GB2312編碼或者ascii編碼,
     *
     * @param ch 輸入的GB2312中文字符或者ASCII字符(128個)
     * @return ch在GB2312中的位置,-1表示該字符不認識
     */
    public static short getGB2312Id(char ch) {
        try {
            byte[] buffer = Character.toString(ch).getBytes("GB2312");
            if (buffer.length != 2) {
                // 正常情況下buffer應該是兩個字節,否則說明ch不屬於GB2312編碼,故返回'?',此時說明不認識該字符
                return -1;
            }
            int b0 = (int) (buffer[0] & 0x0FF) - 161; // 編碼從A1開始,因此減去0xA1=161
            int b1 = (int) (buffer[1] & 0x0FF) - 161;
            return (short) (b0 * 94 + b1);// 第一個字符和最后一個字符沒有漢字,因此每個區只收16*6-2=94個漢字
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return -1;
    }

    public static void main(String[] args) {
        String str1="擔保人姓名";
        String str2="個人法定名稱";
        long start=System.currentTimeMillis();
        double Similarity=Cosine.getSimilarity(str1, str2);
        System.out.println("用時:"+(System.currentTimeMillis()-start));
        System.out.println(Similarity);
    }

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM