Can someone give an example of cosine similarity, in a very simple, graphical way?

前端 未结 10 1865
别跟我提以往
别跟我提以往 2020-11-28 17:04

Cosine Similarity article on Wikipedia

Can you show the vectors here (in a list or something) and then do the math, and let us see how it works?

I\'m a begin

10条回答
  •  温柔的废话
    2020-11-28 18:00

    Here's my implementation in C#.

    using System;
    
    namespace CosineSimilarity
    {
        class Program
        {
            static void Main()
            {
                int[] vecA = {1, 2, 3, 4, 5};
                int[] vecB = {6, 7, 7, 9, 10};
    
                var cosSimilarity = CalculateCosineSimilarity(vecA, vecB);
    
                Console.WriteLine(cosSimilarity);
                Console.Read();
            }
    
            private static double CalculateCosineSimilarity(int[] vecA, int[] vecB)
            {
                var dotProduct = DotProduct(vecA, vecB);
                var magnitudeOfA = Magnitude(vecA);
                var magnitudeOfB = Magnitude(vecB);
    
                return dotProduct/(magnitudeOfA*magnitudeOfB);
            }
    
            private static double DotProduct(int[] vecA, int[] vecB)
            {
                // I'm not validating inputs here for simplicity.            
                double dotProduct = 0;
                for (var i = 0; i < vecA.Length; i++)
                {
                    dotProduct += (vecA[i] * vecB[i]);
                }
    
                return dotProduct;
            }
    
            // Magnitude of the vector is the square root of the dot product of the vector with itself.
            private static double Magnitude(int[] vector)
            {
                return Math.Sqrt(DotProduct(vector, vector));
            }
        }
    }
    

提交回复
热议问题