Perform a cosine similarity scoring between two vectors - Java java.lang

Java examples for java.lang:Math Vector

Description

Perform a cosine similarity scoring between two vectors

Demo Code


//package com.java2s;

import java.util.Iterator;

import java.util.Map;
import java.util.Set;

public class Main {
    /**/*from  ww  w .j  a v  a  2s  . c o  m*/
     * 
     * Perform a cosine similarity scoring between two vectors
     * 
     * @param vector1
     * @param vector2
     * @return score
     */
    public static double computeCosineSimilarity(
            Map<String, Integer> vector1, Map<String, Integer> vector2) {
        return dot(vector1, vector2)
                / (Math.sqrt(dot(vector1, vector1)) * Math.sqrt(dot(
                        vector2, vector2)));
    }

    /**
     * 
     * Perform a vector dot product between two vectors
     * 
     * @param vector1
     * @param vector2
     * @return dotproduct
     */
    public static double dot(Map<String, Integer> vector1,
            Map<String, Integer> vector2) {
        double dotproduct = 0.0;
        Set<String> vector1Vocab = vector1.keySet();
        Iterator<String> iter = vector1Vocab.iterator();
        Integer vector1Freq;
        Integer vector2Freq;
        String word = null;
        while (iter.hasNext()) {
            word = iter.next();
            vector1Freq = vector1.get(word);
            if (vector2.containsKey(word)) {
                vector2Freq = vector2.get(word);
            } else {
                continue;
            }
            dotproduct = dotproduct + (vector1Freq * vector2Freq);
        }
        return dotproduct;
    }
}

Related Tutorials