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;
            }
        }
    }
  • 相关阅读:
    欧拉计划之题目2:在斐波那契数列中,找出4百万以下的项中值为偶数的项之和。
    MFC非模态对话框的销毁
    MFC:只允许产生一个应用程序实例的具体实现
    从_tiddata看CRT的线程不安全函数
    关于消息循环的深入分析
    MFC:关于MFC窗口对象(CWnd对象)与Window对象(HWND所指对象)的销毁问题
    使用FindFirstFile和FindNextFile对给定目录下所有文件进行广度优先遍历
    工作线程的消息循环与通信
    MFC和设计模式
    _endthreadex与CloseHandle
  • 原文地址:https://www.cnblogs.com/live41/p/2013041.html
Copyright © 2011-2022 走看看