Skip to content

Add smoothing constant to IDF formula in BM25 to prevent negative scores #5696

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,6 @@ private double computeBM25Score(int termFrequency, double docLength, double idf)
*/
private double computeIDF(int docFrequency) {
// Total number of documents in the index
return Math.log((totalDocuments - docFrequency + 0.5) / (docFrequency + 0.5));
return Math.log((totalDocuments - docFrequency + 0.5) / (docFrequency + 0.5) + 1);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,15 @@ void testSearchRanking() {
// Perform search for the term "good"
List<SearchResult> results = index.search("good");
assertFalse(results.isEmpty());

for (SearchResult result : results) {
System.out.println(result);
}
// Validate the ranking based on the provided relevance scores
assertEquals(6, results.get(0).getDocId()); // It's a Wonderful Life should be ranked 1st
assertEquals(7, results.get(1).getDocId()); // The Pursuit of Happyness should be ranked 2nd
assertEquals(1, results.get(0).getDocId()); // The Shawshank Redemption should be ranked 1st
assertEquals(8, results.get(1).getDocId()); // A Few Good Men should be ranked 2nd
assertEquals(5, results.get(2).getDocId()); // Good Will Hunting should be ranked 3rd
assertEquals(8, results.get(3).getDocId()); // A Few Good Men should be ranked 4th
assertEquals(1, results.get(4).getDocId()); // The Shawshank Redemption should be ranked 5th
assertEquals(7, results.get(3).getDocId()); // The Pursuit of Happyness should be ranked 4th
assertEquals(6, results.get(4).getDocId()); // It's a Wonderful Life should be ranked 5th

// Ensure the relevance scores are in descending order
for (int i = 0; i < results.size() - 1; i++) {
Expand Down