| | | 1 | | using Intentum.AI.Embeddings; |
| | | 2 | | |
| | | 3 | | namespace Intentum.AI.Similarity; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// Similarity engine that applies weights to embeddings based on their source (actor:action). |
| | | 7 | | /// Useful when certain behaviors should have more influence on intent inference. |
| | | 8 | | /// </summary> |
| | | 9 | | public sealed class WeightedAverageSimilarityEngine : IIntentSimilarityEngine |
| | | 10 | | { |
| | | 11 | | private readonly IReadOnlyDictionary<string, double> _weights; |
| | | 12 | | private readonly double _defaultWeight; |
| | | 13 | | |
| | | 14 | | /// <summary> |
| | | 15 | | /// Creates a weighted average similarity engine. |
| | | 16 | | /// </summary> |
| | | 17 | | /// <param name="weights">Dictionary mapping source keys (actor:action) to weights. If a source is not found, defaul |
| | | 18 | | /// <param name="defaultWeight">Default weight for sources not in the weights dictionary. Defaults to 1.0.</param> |
| | 7 | 19 | | public WeightedAverageSimilarityEngine( |
| | 7 | 20 | | IReadOnlyDictionary<string, double>? weights = null, |
| | 7 | 21 | | double defaultWeight = 1.0) |
| | 7 | 22 | | { |
| | 7 | 23 | | _weights = weights ?? new Dictionary<string, double>(); |
| | 7 | 24 | | _defaultWeight = defaultWeight; |
| | 7 | 25 | | } |
| | | 26 | | |
| | | 27 | | public double CalculateIntentScore(IReadOnlyCollection<IntentEmbedding> embeddings) |
| | 6 | 28 | | => CalculateIntentScore(embeddings, null); |
| | | 29 | | |
| | | 30 | | /// <inheritdoc /> |
| | | 31 | | public double CalculateIntentScore(IReadOnlyCollection<IntentEmbedding> embeddings, IReadOnlyDictionary<string, doub |
| | 7 | 32 | | { |
| | 7 | 33 | | if (embeddings.Count == 0) |
| | 1 | 34 | | return 0; |
| | | 35 | | |
| | 6 | 36 | | var totalWeightedScore = 0.0; |
| | 6 | 37 | | var totalWeight = 0.0; |
| | | 38 | | |
| | 44 | 39 | | foreach (var embedding in embeddings) |
| | 13 | 40 | | { |
| | 13 | 41 | | var weight = sourceWeights?.GetValueOrDefault(embedding.Source, _defaultWeight) |
| | 13 | 42 | | ?? _weights.GetValueOrDefault(embedding.Source, _defaultWeight); |
| | 13 | 43 | | totalWeightedScore += embedding.Score * weight; |
| | 13 | 44 | | totalWeight += weight; |
| | 13 | 45 | | } |
| | | 46 | | |
| | 6 | 47 | | return totalWeight > 0 ? totalWeightedScore / totalWeight : 0; |
| | 7 | 48 | | } |
| | | 49 | | } |