[英]Compare Two Vectors (Java)
目前,我有兩個大於50個字符串的較大向量
我希望能夠比較這兩個向量,並弄清楚它們有多相似。 我想我需要使用余弦相似度嗎?
有誰知道采用兩個Java Vector並給出介於0和1之間的值的方法的相似性嗎?
謝謝菲爾
有關余弦距離和相關方法的實現,請參見Apache Mahout庫 。 還可以考慮查找“本地敏感哈希”以尋求更快的替代方法。
請執行下列操作
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;
}
}
類型推斷,有人嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.