zoukankan      html  css  js  c++  java
  • 向量余弦值(Cosine)(C#)

    接前面一篇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<intdouble> vector1, Dictionary<intdouble> 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<intdouble> vector)
            {
                
    double length = 0;
                
    foreach (KeyValuePair<intdouble> 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<intdouble> vector1, Dictionary<intdouble> vector2)
            {
                
    double dotProduct = 0;
                
    foreach (KeyValuePair<intdouble> kvp in vector1)
                {
                    
    if (vector2.ContainsKey(kvp.Key))
                    {
                        dotProduct 
    += kvp.Value * vector2[kvp.Key];
                    }
                }
                
    return dotProduct;
            }
        }
    }
  • 相关阅读:
    cdoj1325卿学姐与基本法
    HUAS 1476 不等数列(DP)
    BZOJ 1818 内部白点(离散化+树状数组)
    BZOJ 1816 扑克牌(二分)
    BZOJ 1801 中国象棋(DP)
    BZOJ 1791 岛屿(环套树+单调队列DP)
    BZOJ 1797 最小割(最小割割边唯一性判定)
    BZOJ 1789 Y形项链(思维)
    BZOJ 1787 紧急集合(LCA)
    BZOJ 1786 配对(DP)
  • 原文地址:https://www.cnblogs.com/live41/p/2013041.html
Copyright © 2011-2022 走看看