RAG · Lesson 74 of 120
Precision and Recall at k
Finding all of it.
Some questions need several chunks. Precision at k asks, how many of the top k chunks are relevant? Recall at k asks, how many of all the relevant chunks did we find?

- Several chunks needed
- Precision: how clean
- Recall: how complete
Precision and recall
We treat every chunk from the returns page as relevant to a general returns question. For k of one, three, and five, we count the relevant chunks in the results. Precision divides by k. Recall divides by all relevant chunks. Run it. As k grows, recall rises, and precision falls.
precision_recall.pypython
from rag_kit import load_docs, make_chunks, Index
chunks = make_chunks(load_docs())
index = Index(chunks)
relevant = [c for c in chunks if c["source"] == "returns.md"]
for k in [1, 3, 5]:
found = sum(c["source"] == "returns.md" for s, c in index.search("How do returns work?", k))
print(f"k={k} precision {found / k:.2f} recall {found / len(relevant):.2f}")Output
k=1 precision 1.00 recall 0.25 k=3 precision 1.00 recall 0.75 k=5 precision 0.80 recall 1.00
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]The trade-off
Fetch few chunks, and they're clean but may miss some facts. Fetch many, and you find more, but add noise. A reranker lets you fetch many, then keep only the best.
Small k
- High precisionLower recallClean prompt
Large k
- Higher recallLower precisionMore noise
Summary
Precision measures how clean the results are. Recall measures how complete. Next, checking the answer is grounded.
Key takeaways- Precision
- Recall
- k trade-off
Next up: Faithfulness — is it grounded