| | | 1 | | namespace Intentum.AI.Similarity; |
| | | 2 | | |
| | | 3 | | /// <summary> |
| | | 4 | | /// Standard cosine similarity implementation. |
| | | 5 | | /// </summary> |
| | | 6 | | public static class CosineSimilarityHelper |
| | | 7 | | { |
| | | 8 | | /// <summary> |
| | | 9 | | /// Computes cosine similarity between two vectors. Returns a value in [-1, 1] range. |
| | | 10 | | /// 1 means identical direction, 0 means orthogonal, -1 means opposite direction. |
| | | 11 | | /// </summary> |
| | | 12 | | /// <param name="a">First vector.</param> |
| | | 13 | | /// <param name="b">Second vector.</param> |
| | | 14 | | /// <returns>Cosine similarity in [-1, 1].</returns> |
| | | 15 | | /// <exception cref="ArgumentException">Thrown when vectors have different lengths.</exception> |
| | | 16 | | public static double CosineSimilarity(double[] a, double[] b) |
| | 21 | 17 | | { |
| | 21 | 18 | | if (a.Length != b.Length) |
| | 1 | 19 | | throw new ArgumentException("Vectors must have the same length"); |
| | | 20 | | |
| | 60 | 21 | | double dotProduct = 0, normA = 0, normB = 0; |
| | | 22 | | |
| | 216 | 23 | | for (int i = 0; i < a.Length; i++) |
| | 88 | 24 | | { |
| | 88 | 25 | | dotProduct += a[i] * b[i]; |
| | 88 | 26 | | normA += a[i] * a[i]; |
| | 88 | 27 | | normB += b[i] * b[i]; |
| | 88 | 28 | | } |
| | | 29 | | |
| | | 30 | | const double epsilon = 1e-10; |
| | 20 | 31 | | if (normA < epsilon || normB < epsilon) |
| | 3 | 32 | | return 0; |
| | | 33 | | |
| | 17 | 34 | | return dotProduct / (Math.Sqrt(normA) * Math.Sqrt(normB)); |
| | 20 | 35 | | } |
| | | 36 | | |
| | | 37 | | /// <summary> |
| | | 38 | | /// Computes cosine similarity normalized to [0, 1] range. |
| | | 39 | | /// 1 means identical direction, 0.5 means orthogonal, 0 means opposite direction. |
| | | 40 | | /// </summary> |
| | | 41 | | /// <param name="a">First vector.</param> |
| | | 42 | | /// <param name="b">Second vector.</param> |
| | | 43 | | /// <returns>Normalized cosine similarity in [0, 1].</returns> |
| | | 44 | | /// <exception cref="ArgumentException">Thrown when vectors have different lengths.</exception> |
| | | 45 | | public static double CosineSimilarityNormalized(double[] a, double[] b) |
| | 16 | 46 | | => (CosineSimilarity(a, b) + 1) / 2; |
| | | 47 | | } |