Skip to content
AI-grafen
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.

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

  1. dot, norm — Implement dot(u, v) and norm(u) with plain lists (no NumPy).
  2. cosinus (cosine) — Implement cosinus(u, v).
  3. 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 browser
import 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 account

Expected 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

  • zip stops at the shortest list — check that the lengths are equal.
  • Division by zero for the zero vector in cosine.
  • Uses max() on a dict without key= and gets the key in alphabetical order.