Lesson 4.9 · 9 of 10 · 6 min read · Reviewed 24 Nov 2026
Sparse vectors: TF-IDF, BM25 and SPLADE
By the end, you can
- Explain how sparse vectors represent text as weighted words.
- Score a document with BM25 and say what k1 and b do.
- Tell when a learned sparse model such as SPLADE is worth it.
Dense and sparse
The embeddingsEmbedding: A list of numbers (a vector) that represents the meaning of a piece of text, so similar meanings land close together. in 3.1 are dense: a few hundred to a few thousand numbers, all of them non-zero, none of them nameable. A sparse vector is the opposite. It has one slot for every word in the vocabulary (often 30,000 or more), and almost all of them are zero.
"refund for a damaged parcel"
dense: [0.12, -0.40, 0.88, ... 1,024 numbers]
sparse: {refund: 2.9, damaged: 2.1, parcel: 1.7} every other word = 0
You can read a sparse vector. That makes matches easy to explain and lets search engines store them in an inverted index: for each word, the list of documents that contain it. A query only touches the lists for its own words, so search stays fast over millions of documents.
TF-IDF
The first useful weighting multiplies two things:
- Term frequency (TF): how often the word appears in this document.
- Inverse document frequency (IDF): how rare the word is across the collection, usually
log(N / df), whereNis the number of documents anddfis how many contain the word.
“the” appears everywhere, so its IDF is near zero. “chargeback” appears in a handful of documents, so it carries a lot of weight.
BM25
BM25BM25: A classic keyword ranking function that scores documents by term frequency and rarity. keeps the TF-IDF idea and fixes two weaknesses.
| Problem with TF-IDF | BM25 fix | Knob |
|---|---|---|
| A word said 20 times scores 20 times higher | Term frequency saturates: each extra mention adds less | k1, typically 1.2 to 2 |
| Long documents win by containing more words | Scores are normalised by length against the average document | b, typically 0.75 (0 turns it off) |
For one query word, the score in a document is roughly:
IDF(word) x tf x (k1 + 1)
---------------------------------------
tf + k1 x (1 - b + b x doc_len / avg_len)
Add this up over the query’s words and you have the document’s BM25 score.
A worked example
Collection of 1,000 help articles. Query: cancel subscription.
| Article | tf “cancel” | tf “subscription” | Length vs average | Rank |
|---|---|---|---|---|
| A: “How to cancel your subscription” | 3 | 4 | 0.5x | 1 |
| B: Terms of service | 6 | 9 | 8x | 2 |
| C: “Pause your plan” | 0 | 1 | 1x | 3 |
Article B mentions both words more often, but saturation and length normalisation stop it beating the short, focused article A.
SPLADE: learned sparse vectors
BM25 only knows the words that are literally there. SPLADE runs the text through a transformerTransformer: The neural network architecture behind modern LLMs, built from stacked attention and feed-forward layers. that outputs a weight for every vocabulary word. Two things change:
- Weights are learned from relevance data, not counted.
- Expansion: the model can switch on words that are not in the text. “laptop won’t turn on” may get weight on power, boot and battery.
The result still fits an inverted index, so you get some of the paraphrase matching of dense search with the speed and explainability of keyword search. The cost is an extra model at index and query time.
When to use which
| Situation | Good choice |
|---|---|
| Ids, error codes, product names, legal terms | BM25 |
| No GPU, need a strong baseline today | BM25 |
| Paraphrases matter, but you want an inverted index and readable matches | SPLADE or a similar learned sparse model |
| Natural questions over prose | Dense embeddings, usually in hybrid with BM25 |
Common mistakes
- Skipping BM25 as a baseline. On many collections it is hard to beat, and it costs nothing to try.
- Tuning k1 and b on a hunch. Change them only with a labelled query set to measure against.
- Forgetting the tokenizerTokenizer: The component that splits text into tokens and maps each token to an id the model can process.. Stemming, lowercasing and stop words change BM25 scores as much as the formula does. Use the same analyser at index and query time.
Key points
- A sparse vector has one slot per word in the vocabulary, and almost every slot is zero. Only the words that matter get a weight.
- TF-IDF weights a word by how often it appears in the document and how rare it is across the collection.
- BM25 improves TF-IDF with term saturation (k1) and document length normalisation (b). It is still the standard keyword baseline.
- SPLADE learns the weights with a neural model and adds related words, so sparse search can match some paraphrases.
Score documents with BM25 by hand
Implement BM25 and see how term saturation and length normalisation stop long, repetitive documents winning.
You will have: A BM25 scorer that ranks three help articles for 'cancel subscription', with a comparison against raw term counts.
Steps
- Run the starter: ranking by raw term counts puts the long terms-of-service page first.
- Fill in idf() with log(1 + (N - df + 0.5) / (df + 0.5)).
- Fill in bm25() using k1 = 1.2 and b = 0.75.
- Rank the articles again: the short, focused article should now win.
- Set b = 0 and k1 = 100 and see the ranking drift back towards raw counts.
Done when
- Raw counts rank 'terms' first.
- BM25 with k1 = 1.2, b = 0.75 ranks 'how-to-cancel' first.
- The script prints the BM25 score of every article to 2 decimal places.
Open in the Playground No API key needed.
Starter code (Python)
import math
N = 1000
DF = {"cancel": 25, "subscription": 20}
ARTICLES = { # term counts and lengths in words
"how-to-cancel": {"tf": {"cancel": 3, "subscription": 4}, "len": 60},
"terms": {"tf": {"cancel": 6, "subscription": 9}, "len": 960},
"pause-plan": {"tf": {"cancel": 0, "subscription": 1}, "len": 120},
}
AVG_LEN = 120
QUERY = ["cancel", "subscription"]
def raw(doc):
return sum(doc["tf"].get(w, 0) for w in QUERY)
def idf(word):
return 1.0 # TODO: math.log(1 + (N - df + 0.5) / (df + 0.5))
def bm25(doc, k1=1.2, b=0.75):
return 0.0 # TODO: sum over query words of idf * tf * (k1 + 1) / (tf + k1 * (1 - b + b * len / AVG_LEN))
print("raw counts:", sorted(ARTICLES, key=lambda a: -raw(ARTICLES[a])))
print("bm25:", sorted(ARTICLES, key=lambda a: -bm25(ARTICLES[a])))
Show a solution
import math
N = 1000
DF = {"cancel": 25, "subscription": 20}
ARTICLES = {
"how-to-cancel": {"tf": {"cancel": 3, "subscription": 4}, "len": 60},
"terms": {"tf": {"cancel": 6, "subscription": 9}, "len": 960},
"pause-plan": {"tf": {"cancel": 0, "subscription": 1}, "len": 120},
}
AVG_LEN = 120
QUERY = ["cancel", "subscription"]
def raw(doc):
return sum(doc["tf"].get(w, 0) for w in QUERY)
def idf(word):
df = DF[word]
return math.log(1 + (N - df + 0.5) / (df + 0.5))
def bm25(doc, k1=1.2, b=0.75):
score = 0.0
for w in QUERY:
tf = doc["tf"].get(w, 0)
score += idf(w) * tf * (k1 + 1) / (tf + k1 * (1 - b + b * doc["len"] / AVG_LEN))
return score
print("raw counts:", sorted(ARTICLES, key=lambda a: -raw(ARTICLES[a])))
for name, doc in ARTICLES.items():
print(f"{name:14} bm25={bm25(doc):.2f}")
print("bm25:", sorted(ARTICLES, key=lambda a: -bm25(ARTICLES[a])))
print("no length norm, high k1:", sorted(ARTICLES, key=lambda a: -bm25(ARTICLES[a], k1=100, b=0)))