RAG · Lesson 72 of 120
Hit Rate
Did we find it.
The simplest retrieval measure is hit rate. For each question, did the chunk with the fact appear in the top k results? Hit rate is the share of questions where it did.

- Top k results
- Fact found?
- Share of hits
Measuring hit rate
We load the test set. For each question, a hit means the fact appears in one of the top three chunks. We count the hits, and print the misses. Run it. Six out of ten. Four questions missed their fact.
hit_rate.pypython
import json
from rag_kit import load_docs, make_chunks, Index
tests = json.load(open("eval_set.json"))
index = Index(make_chunks(load_docs()))
def hit(t, k=3):
return any(t["fact"] in c["text"] for s, c in index.search(t["question"], k))
hits = [hit(t) for t in tests]
print(f"hit rate: {sum(hits)} of {len(tests)}")
for t, h in zip(tests, hits):
if not h: print(" missed:", t["question"])Output
hit rate: 6 of 10 missed: What does E03 mean? missed: What is the APR? missed: Can I spread the payments? missed: How many hours until my e-bike is full again?
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter
def load_docs(folder="data/rag/northwind"):
return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]
def make_chunks(docs, size=300, overlap=50):
splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
return [{"source": d["source"], "text": t.replace("\n", " ")}
for d in docs for t in splitter.split_text(d["text"])]
embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")
def embed(texts):
return embedder.encode(texts, normalize_embeddings=True)
class Index:
def __init__(self, chunks):
self.chunks = chunks
self.vectors = embed([c["text"] for c in chunks])
def search(self, query, k=3):
scores = self.vectors @ embed([query])[0]
top = np.argsort(-scores)[:k]
return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]Also uses eval_set.json
[
{"question": "What does E03 mean?", "source": "ebike_errors.md", "fact": "speed sensor"},
{"question": "What is the APR?", "source": "finance.md", "fact": "9.9"},
{"question": "Can I spread the payments?", "source": "finance.md", "fact": "spread the cost"},
{"question": "How many hours until my e-bike is full again?", "source": "ebike_battery.md", "fact": "4 hours"},
{"question": "How long until my money comes back?", "source": "returns.md", "fact": "7 working days"},
{"question": "Can I get next-day delivery on a bike?", "source": "shipping.md", "fact": "Next-day"},
{"question": "How much is a rental deposit?", "source": "rentals.md", "fact": "£150"},
{"question": "When is the York shop open?", "source": "stores.md", "fact": "5:30pm"},
{"question": "How much is a Basic service?", "source": "servicing.md", "fact": "£49"},
{"question": "Do you deliver bikes to France?", "source": "shipping.md", "fact": "complete bikes"}
]Reading hit rate
Hit rate ignores the position, so first and third place count the same. A low hit rate means the answer can't be right, however good the model is. Always measure it first.
| key | value |
|---|---|
| Hit | fact in top k |
| Ignores | position |
| Low hit rate | answer can't be right |
| Measure | first |
Summary
Hit rate is the share of questions whose fact is in the top k chunks. Next, MRR, which rewards being near the top.
Key takeaways- Fact in top k
- Share of questions
- Measure first
Next up: MRR — how high was it