💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows
Python agentsaiai-agentsembeddingsinformation-retrievallanguage-modellarge-language-modelsllmnlppythonragretrieval-augmented-generationsearchsearch-enginesemantic-searchsentence-embeddingstransformerstxtaivector-databasevector-search
Normalize scores, closes #401
davidmezzettie609f8c7e2b8
diff --git a/src/python/txtai/scoring/base.py b/src/python/txtai/scoring/base.pyindex 5e28204d..c9c35d0f 100644--- a/src/python/txtai/scoring/base.py+++ b/src/python/txtai/scoring/base.py@@ -37,6 +37,9 @@ class Scoring:self.documents = {} if self.config.get("content") else Noneself.docterms = {} if self.config.get("terms") else None+ # Normalize scores+ self.normalize = self.config.get("normalize")+# Word frequencyself.docfreq = Counter()self.wordfreq = Counter()@@ -210,6 +213,15 @@ class Scoring:scores[x] += self.docterms[token][x]+ # Check if score normalization enabled+ if self.normalize:+ # Calculate max score = 4 * average score+ maxscore = 4 * self.score(self.avgfreq, self.avgidf, self.avgdl)++ # Normalize scores between 0 - 1 using maxscore+ for x in scores:+ scores[x] = min(scores[x] / maxscore, 1.0)+# Sort and get topn resultstopn = sorted(scores.items(), key=lambda x: x[1], reverse=True)[:limit]diff --git a/test/python/testscoring.py b/test/python/testscoring.pyindex b2d7521f..7d29aff6 100644--- a/test/python/testscoring.py+++ b/test/python/testscoring.py@@ -73,6 +73,7 @@ class TestScoring(unittest.TestCase):self.index(config)self.weights(config)self.search(config)+ self.normalize(config)self.content(config)self.empty(config)@@ -172,6 +173,22 @@ class TestScoring(unittest.TestCase):index, _ = scoring.search("bear", 1)[0]self.assertEqual(index, 3)+ def normalize(self, config):+ """+ Test scoring search with normalized scores.++ Args:+ method: scoring method+ """++ scoring = ScoringFactory.create({**config, **{"terms": True, "normalize": True}})+ scoring.index(self.data)++ # Run search and validate correct result returned+ index, score = scoring.search(self.data[3][1], 1)[0]+ self.assertEqual(index, 3)+ self.assertEqual(score, 1.0)+def content(self, config):"""Test scoring search with content.