Cosine Retrieval
Vector length should not dominate relevance. Normalize dot products by both norms, give zero vectors score zero, and keep stable indices for tied documents.
import math
query, document = [1, 0], [10, 0]
dot = sum(a*b for a,b in zip(query, document))
print(dot / (math.hypot(*query)*math.hypot(*document)))From arithmetic to an experiment
Vector length should not dominate relevance. Normalize dot products by both norms, give zero vectors score zero, and keep stable indices for tied documents. The trace reads the local variables of your function as it executes. Change one input or parameter, predict the result, then run the checks again. A small deterministic example makes arithmetic mistakes easier to locate than a long training run. State the shape and meaning of the returned value before coding. Keep preprocessing, evaluation and model updates in their proper order, and examine the boundary case in each check. The companion lab lets you replay intermediate values while the same algorithm runs.
Your task
rank_vectors(query, documents, k) returns the top k document indices by descending cosine similarity, breaking ties by smaller index. Empty or zero vectors score 0. Dimensions match and k >= 0.
The explanation opens here once every check passes.