001/* 002 * Copyright (c) 2012, Regents of the University of Colorado 003 * All rights reserved. 004 * 005 * Redistribution and use in source and binary forms, with or without 006 * modification, are permitted provided that the following conditions are met: 007 * 008 * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 009 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 010 * Neither the name of the University of Colorado at Boulder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 011 * 012 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 013 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 014 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 015 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 016 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 017 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 018 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 019 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 020 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 021 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 022 * POSSIBILITY OF SUCH DAMAGE. 023 */ 024package org.cleartk.ml.feature.transform.extractor; 025 026import java.util.Map; 027 028/** 029 * 030 * <br> 031 * Copyright (c) 2012, Regents of the University of Colorado <br> 032 * All rights reserved. 033 * 034 * @author Lee Becker 035 */ 036public class CosineSimilarity implements SimilarityFunction { 037 038 @Override 039 public double distance(Map<String, Double> vector1, Map<String, Double> vector2) { 040 return CosineSimilarity.dotProduct(vector1, vector2) 041 / (magnitude(vector1) * magnitude(vector2)); 042 } 043 044 public static double dotProduct(Map<String, Double> vector1, Map<String, Double> vector2) { 045 double dot = 0.0; 046 047 if (vector1.size() > vector2.size()) { 048 Map<String, Double> tmp = vector2; 049 vector2 = vector1; 050 vector1 = tmp; 051 } 052 053 for (Map.Entry<String, Double> entry1 : vector1.entrySet()) { 054 if (vector2.containsKey(entry1.getKey())) { 055 dot += entry1.getValue() * vector2.get(entry1.getKey()); 056 } 057 } 058 059 return dot; 060 } 061 062 public static double magnitude(Map<String, Double> vector) { 063 double mag = 0.0; 064 for (double v : vector.values()) { 065 mag += v * v; 066 } 067 return Math.sqrt(mag); 068 } 069 070}