| | | 1 | | using Intentum.AI.Similarity; |
| | | 2 | | |
| | | 3 | | namespace Intentum.AI.Embeddings; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// Shared helpers for embedding score normalization used by provider embedding implementations. |
| | | 7 | | /// </summary> |
| | | 8 | | public static class EmbeddingScore |
| | | 9 | | { |
| | | 10 | | /// <summary> |
| | | 11 | | /// Computes a scalar score from an embedding vector using L2 magnitude, |
| | | 12 | | /// normalized to [0, 1]. This provides a rough "activation strength" indicator. |
| | | 13 | | /// For meaningful similarity, use cosine similarity between two vectors instead. |
| | | 14 | | /// </summary> |
| | | 15 | | public static double Normalize(IReadOnlyList<double> values) |
| | 9 | 16 | | { |
| | 9 | 17 | | if (values.Count == 0) |
| | 1 | 18 | | return 0; |
| | | 19 | | |
| | 8 | 20 | | var sumOfSquares = 0.0; |
| | 52 | 21 | | foreach (var v in values) |
| | 14 | 22 | | sumOfSquares += v * v; |
| | | 23 | | |
| | 8 | 24 | | var magnitude = Math.Sqrt(sumOfSquares / values.Count); |
| | 8 | 25 | | return Math.Clamp(magnitude, 0.0, 1.0); |
| | 9 | 26 | | } |
| | | 27 | | |
| | | 28 | | /// <summary> |
| | | 29 | | /// Computes cosine similarity between two embedding vectors. Returns a value in [0, 1] |
| | | 30 | | /// where 1 means identical direction and 0 means orthogonal or opposite. |
| | | 31 | | /// </summary> |
| | | 32 | | public static double CosineSimilarity(IReadOnlyList<double> a, IReadOnlyList<double> b) |
| | 11 | 33 | | { |
| | 11 | 34 | | if (a.Count == 0 || b.Count == 0 || a.Count != b.Count) |
| | 3 | 35 | | return 0; |
| | | 36 | | |
| | 8 | 37 | | return CosineSimilarityHelper.CosineSimilarityNormalized(a.ToArray(), b.ToArray()); |
| | 11 | 38 | | } |
| | | 39 | | } |