Mixed lengths, then normalised, with a check
The check raises an error and the example catches it and prints the message.
Normalising a vector means scaling it to length 1 without changing its direction. Then the dot product equals cosine similarity, which is why most stores assume unit vectors. Mixing normalised and raw vectors silently corrupts a ranking.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write normalise(v) that returns the unit vector (and returns a zero vector unchanged), and print normalise([3, 4]) and normalise([0, 0]) to three decimals.
Write ranks_differ(query, docs) that returns True when ranking docs (a dict of name to vector) by raw dot product gives a different order from ranking by dot product after normalising everything. Print the result for the query [0, 1] and docs {"a": [0.6, 0.8], "b": [3, 3]}.
Explain it without notes
Why does normalising make the dot product equal to the cosine similarity?
What is the bug when an index mixes normalised and raw vectors, and why is it hard to notice?
How do you normalise a vector, and what must you handle as a special case?
Where in a pipeline should you check that vectors have length 1, and why there?
Expected output
lengths: A=1.000, B=4.243
dot product on mixed lengths: B=3.000, A=0.800
dot product after normalising: A=0.800, B=0.707
A: ok
B: rejected, vector has length 4.243, expected 1.000 (normalise it first)
B normalised: ok