DAI developerLab· about 40 min· in the browser
Lab: dot product, norm and cosine similarity
Implement the vector operations by hand with lists, verify against NumPy, and use cosine similarity to find the most similar word.
Teaches: Vectors
Requires: Python — lists, loops and dictionaries
Theory
u·v = Σ uᵢvᵢ. ‖u‖ = √(u·u). cos(u,v) = u·v / (‖u‖‖v‖). The dot product is large when the vectors point in the same direction — that is the whole idea behind embeddings.
Sub-tasks
- dot, norm — Implement
dot(u, v)andnorm(u)with plain lists (no NumPy). - cosinus (cosine) — Implement
cosinus(u, v). - mest_lik — most similar —
mest_lik(q, ordvektorer)returns the key in the dict whose vector has the highest cosine similarity with q.
The starter code
runs in your browserimport math
def dot(u, v):
# TODO
...
def norm(u):
# TODO: math.sqrt(dot(u, u))
...
def cosinus(u, v):
# TODO
...
def mest_lik(q, ordvektorer):
# TODO: nyckeln med högst cosinus(q, vektor)
...
You write the code; tests you cannot see decide whether it holds up. Create a free account to run the lab.
Try the diagnosticCreate a free accountExpected results
dot([1,2,3],[4,-1,2]) = 8; norm([6,8]) = 10; cosinus([1,0],[1,1]) ≈ 0.707; mest_lik(kung, {...}) = 'drottning' (king → queen).
Common mistakes
zipstops at the shortest list — check that the lengths are equal.- Division by zero for the zero vector in cosine.
- Uses
max()on a dict withoutkey=and gets the key in alphabetical order.