接前面一篇TF-IDF的代码,用其结果来计算出向量的余弦值的代码
View Code
using System;
using System.Collections.Generic;
using System.Text;
namespace Cluster
{
static class Cosine
{
/// <summary>
/// 计算向量余弦值
/// </summary>
/// <param name="vector1"></param>
/// <param name="vector2"></param>
public static double Calculate(Dictionary<int, double> vector1, Dictionary<int, double> vector2)
{
double dotProduct = CalcDotProduct(vector1, vector2);
double length1 = CalcLength(vector1);
double length2 = CalcLength(vector2);
double cosine = dotProduct / (length1 * length2);
return cosine;
}
/// <summary>
/// 计算向量长度(vector length)
/// </summary>
/// <param name="vector"></param>
/// <returns></returns>
private static double CalcLength(Dictionary<int, double> vector)
{
double length = 0;
foreach (KeyValuePair<int, double> kvp in vector)
{
length += Math.Pow(kvp.Value, 2);
}
return Math.Sqrt(length);
}
/// <summary>
/// 计算向量点积(dot product)/内积(inner product)
/// </summary>
/// <param name="vector1"></param>
/// <param name="vector2"></param>
/// <returns></returns>
private static double CalcDotProduct(Dictionary<int, double> vector1, Dictionary<int, double> vector2)
{
double dotProduct = 0;
foreach (KeyValuePair<int, double> kvp in vector1)
{
if (vector2.ContainsKey(kvp.Key))
{
dotProduct += kvp.Value * vector2[kvp.Key];
}
}
return dotProduct;
}
}
}
using System.Collections.Generic;
using System.Text;
namespace Cluster
{
static class Cosine
{
/// <summary>
/// 计算向量余弦值
/// </summary>
/// <param name="vector1"></param>
/// <param name="vector2"></param>
public static double Calculate(Dictionary<int, double> vector1, Dictionary<int, double> vector2)
{
double dotProduct = CalcDotProduct(vector1, vector2);
double length1 = CalcLength(vector1);
double length2 = CalcLength(vector2);
double cosine = dotProduct / (length1 * length2);
return cosine;
}
/// <summary>
/// 计算向量长度(vector length)
/// </summary>
/// <param name="vector"></param>
/// <returns></returns>
private static double CalcLength(Dictionary<int, double> vector)
{
double length = 0;
foreach (KeyValuePair<int, double> kvp in vector)
{
length += Math.Pow(kvp.Value, 2);
}
return Math.Sqrt(length);
}
/// <summary>
/// 计算向量点积(dot product)/内积(inner product)
/// </summary>
/// <param name="vector1"></param>
/// <param name="vector2"></param>
/// <returns></returns>
private static double CalcDotProduct(Dictionary<int, double> vector1, Dictionary<int, double> vector2)
{
double dotProduct = 0;
foreach (KeyValuePair<int, double> kvp in vector1)
{
if (vector2.ContainsKey(kvp.Key))
{
dotProduct += kvp.Value * vector2[kvp.Key];
}
}
return dotProduct;
}
}
}