引導語:Java 程式語言的風格十分接近C、C++語言。Java是一個純的面向物件的程式設計語言,以下是小編整理的Java基於餘弦方法實現的`計算相似度演算法示例,歡迎參考閱讀!
(1)餘弦相似性
通過測量兩個向量之間的角的餘弦值來度量它們之間的相似性。0度角的餘弦值是1,而其他任何角度的餘弦值都不大於1;並且其最小值是-1。從而兩個向量之間的角度的餘弦值確定兩個向量是否大致指向相同的方向。所以,它通常用於檔案比較。
相關介紹可參考百度百科:餘弦相似性
(2)演算法實現的中未使用權重(IDF ---逆文件頻率),使用詞項的出現次數作為向量空間的值。
import Map;
import ator;
import ;
public class SimilarDegreeByCos
{
/*
* 計算兩個字串(英文字元)的相似度,簡單的餘弦計算,未添權重
*/
public static double getSimilarDegree(String str1, String str2)
{
//建立向量空間模型,使用map實現,主鍵為詞項,值為長度為2的陣列,存放著對應詞項在字串中的出現次數
MapvectorSpace = new HashMap();
int[] itemCountArray = null;//為了避免頻繁產生區域性變數,所以將itemCountArray宣告在此
//以空格為分隔符,分解字串
String strArray[] = t(" ");
for(int i=0; i<th; ++i)
{
if(ainsKey(strArray[i]))
++((strArray[i])[0]);
else
{
itemCountArray = new int[2];
itemCountArray[0] = 1;
itemCountArray[1] = 0;
(strArray[i], itemCountArray);
}
}
strArray = t(" ");
for(int i=0; i<th; ++i)
{
if(ainsKey(strArray[i]))
++((strArray[i])[1]);
else
{
itemCountArray = new int[2];
itemCountArray[0] = 0;
itemCountArray[1] = 1;
(strArray[i], itemCountArray);
}
}
//計算相似度
double vector1Modulo = 0.00;//向量1的模
double vector2Modulo = 0.00;//向量2的模
double vectorProduct = 0.00; //向量積
Iterator iter = ySet()ator();
while(ext())
{
y entry = (y)();
itemCountArray = (int[])alue();
vector1Modulo += itemCountArray[0]*itemCountArray[0];
vector2Modulo += itemCountArray[1]*itemCountArray[1];
vectorProduct += itemCountArray[0]*itemCountArray[1];
}
vector1Modulo = (vector1Modulo);
vector2Modulo = (vector2Modulo);
//返回相似度
return (vectorProduct/(vector1Modulo*vector2Modulo));
}
/*
*
*/
public static void main(String args[])
{
String str1 = "gold silver truck";
String str2 = "Shipment of gold damaged in a fire";
String str3 = "Delivery of silver arrived in a silver truck";
String str4 = "Shipment of gold arrived in a truck";
String str5 = "gold gold gold gold gold gold";
tln(imilarDegree(str1, str2));
tln(imilarDegree(str1, str3));
tln(imilarDegree(str1, str4));
tln(imilarDegree(str1, str5));
}
}