我有一個名爲向量的矩陣[i] [j]。我想計算每行之間的餘弦相似度。例如,對於這個矩陣的計算矩陣中每一行的餘弦相似度
1 0 1 0 1 0 0
v= 0 0 1 1 1 0 1
1 1 0 0 1 0 1
我想有相似度計算,ROW1和列2,ROW1和ROW3,ROW2和row3.Further之間更分別如果ROW1和ROW2之間的相似性等於= 0.6和其他0.5和0.4 。我想在這些行的每個元素(e =!0)上加上這個值,並得到最終的矩陣。
2.1 0 2.1 0 2.1 0 0
v= 0 0 2 2 2 0 2
1.9 1.9 0 0 1.9 0 1.9
這裏是我定義和填充我的矩陣的代碼部分;
string text = Request.Form["TextBox1"]; ; // text
string[] textInArray = text.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
int[,] vectors = new int[textInArray.Length, keywords.Length];
for (int i = 0; i < textInArray.Length; i++)
{
string[] words = textInArray[i].Split(' ');
for (int j = 0; j < keywords.Length; j++)
{
foreach (var word in words)
{
if (word.Contains(keywords[j]))
{
vectors[i, j]++;
}
}
}
}
,這裏是我的代碼來計算相似度,但我認爲它不是某個地方我有錯誤,我不知道我怎樣才能在當前的兩行的元素添加此值完成。
for(i=1 i<matrix.GetLength(0) i++){
for(j=1 j<matrix.GetLength(0) j++){
dot += vectors[i] * vectors[j];
mag1 += Math.Pow(vectors[i], 2);
mag2 += Math.Pow(vectors[j], 2);
}
float M= dot/(Math.Sqrt(mag1) * Math.Sqrt(mag2));
}
}
刪除了asp.net標籤,因爲問題似乎並不涉及asp.net以任何方式,添加C# – Andrei