Lesson 2 of 6 · 2 min
BM25 and rank fusion by hand
import math, re
from collections import Counter
docs = {
"d1": "Error E1042 occurs when the payment token has expired",
"d2": "Customers can get their money back within thirty days",
"d3": "Refund requests need the order number",
}
words = lambda s: re.findall(r"[a-z0-9]+", s.lower())
toks = {k: words(v) for k, v in docs.items()}
avg = sum(map(len, toks.values())) / len(toks)
df = Counter(w for t in toks.values() for w in set(t))
def bm25(q, k1=1.5, b=0.75):
score = {}
for key, t in toks.items():
tf = Counter(t)
score[key] = sum(math.log(1 + (len(docs) - df[w] + 0.5) / (df[w] + 0.5)) * tf[w] * (k1 + 1) / (tf[w] + k1 * (1 - b + b * len(t) / avg)) for w in words(q) if w in tf)
return sorted(score, key=score.get, reverse=True)
def fuse(*rankings, k=60):
total = Counter()
for r in rankings:
for place, key in enumerate(r, 1):
total[key] += 1 / (k + place)
return [key for key, _ in total.most_common()]
pretend_vector_ranking = ["d2", "d3", "d1"]
print("keywords:", bm25("E1042"))
print("fused: ", fuse(bm25("how do I get money back"), pretend_vector_ranking))
