Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 14.5 — Vectors and Matrices: The Maths AI Runs On
Python · Example 2 of 4

Cosine similarity and top-k search over embeddings

These 4-number embeddings are made up to show the mechanics. Change the query to emb[3] (car) and see the order change.

A vector is a list of numbers that can describe anything from a point on a map to the meaning of a sentence. The dot product, norm, cosine similarity and matrix multiplication (@) are the four operations behind embeddings, search and every neural-network layer.

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 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write normalise(v) that returns v divided by its length. Test it on [3.0, 4.0].

02

Given A of shape (2, 3) and B of shape (3, 4), say what A @ B shape is and confirm it with np.ones.

03

Compute the cosine similarity between [1.0, 0.0] and [1.0, 1.0].

04

Given three embeddings as the rows of emb = np.array([[1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]), compute the whole 3-by-3 table of cosine similarities between every pair with one matrix product, rounded to 3 places. Hint: unit @ unit.T.

Explain it without notes

01

What is an embedding and why is cosine similarity a useful way to compare two of them?

02

State the shape rule for A @ B and the shape of the result. How is it different from A * B?

03

Explain Z = X @ W + b with shapes for a layer that maps 128 inputs to 64 outputs on a batch of 32.

04

How do you find the top 3 most similar items to a query with NumPy?

05

When are cosine similarity, dot product and Euclidean distance equivalent for ranking, and when do they disagree?

06

What can go wrong when you normalise vectors, and how do you guard against it?

Cosine similarity and top-k search over embeddings
Sign in to run this example in your browser.

Expected output

cat vs kitten: 0.995
cat vs car   : 0.116
cat     1.000
kitten  0.995
puppy   0.656