BeginnerCoder

Lesson 15 — Cosine similarity

Cosine similarity: same direction, not same size

Cosine similarity measures how much two vectors point the same way: 1 = same direction, 0 = unrelated, −1 = opposite. Formula: dot(a, b) / (norm(a) × norm(b)). Unlike distance, it ignores length — a short and a long text about the same topic still score high.

# [1, 1] and [2, 2] point the same way -> 1.0

Here each document is a word-count vector: how many times each word of a small vocabulary appears.

Why it matters: search engines, recommendation systems and AI "embeddings" all use cosine similarity to find related items.

Want it another way?
Task

Finish cosine(a, b) using dot and norm. The program then finds which document is closest to the query.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.