Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.HashMap;
- import java.util.Map;
- public class CosSim {
- public <T>double getSimVal(Map<T,Double> mapA, Map<T,Double> mapB){
- T key;
- double dotProduct = 0.0;
- double sizeA = 0.0;
- double sizeB = 0.0;
- for (Map.Entry<T, Double> entry : mapA.entrySet()) {
- key = entry.getKey();
- if (mapA.containsKey(key) && mapB.containsKey(key)) dotProduct += mapA.get(key) * mapB.get(key);
- }
- for (Map.Entry<T, Double> entry : mapA.entrySet()) {
- key = entry.getKey();
- sizeA += Math.pow(mapA.get(key), 2);
- }
- for (Map.Entry<T, Double> entry : mapB.entrySet()) {
- key = entry.getKey();
- sizeB += Math.pow(mapB.get(key), 2);
- }
- double cosSim = dotProduct / (Math.sqrt(sizeA) * Math.sqrt(sizeB));
- return cosSim;
- }
- private void debug(){
- Map<String, Double> mapA = new HashMap<>();
- mapA.put("リンゴ", 1.0);
- mapA.put("ミカン", 1.0);
- Map<String, Double> mapB = new HashMap<>();
- mapB.put("リンゴ", 1.0);
- mapB.put("バナナ", 1.0);
- double sim = getSimVal(mapA, mapB);
- System.out.println(sim);
- }
- public static void main(String[] args) {
- CosSim cosim = new CosSim();
- cosim.debug();
- }
- }
Add Comment
Please, Sign In to add comment