目前我有两个50+字符串的较大载体
我希望能够比较这两个向量,并确定它们的相似程度。我想我需要使用余弦相似度?
有没有人知道任何接受两个Java向量的方法,并给出一个0到1之间的值,看它们有多相似?
由于 菲尔
答案 0 :(得分:2)
答案 1 :(得分:2)
有关余弦距离及相关方法的实施,请参阅Apache Mahout library。另外,请考虑查找Locality Sensitive Hashing以获得更快速的替代方案。
答案 2 :(得分:1)
执行以下操作
package com.example;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/** Computes the similarity between two bags of words.
* 1.0 is most similar, 0.0 is most unsimilar.
*
*/
public class Cosine {
public static double cosine(Collection<String> a, Collection<String> b) {
Map<String,Integer> aa = asBag(a);
Map<String,Integer> bb = asBag(b);
double sum = 0;
for (String word: aa.keySet()) {
if (!bb.containsKey(word)) continue;
sum += aa.get(word) * bb.get(word);
}
return sum / (norm(aa) * norm(bb));
}
private static double norm(Map<String, Integer> bag) {
double sum = 0;
for (int each: bag.values()) sum += each * each;
return Math.sqrt(sum);
}
private static Map<String,Integer> asBag(Collection<String> vector) {
Map<String,Integer> bag = new HashMap<String,Integer>();
for (String word: vector) {
if (!bag.containsKey(word)) bag.put(word,0);
bag.put(word, bag.get(word) + 1);
}
return bag;
}
}
类型推断,任何人?