Course map
Stage 1: Foundations
Stage 2: Machine Learning
Stage 3: Deep Learning
Stage 4: LLMs & Generative AI
Stage 5: Production & Specialization

Part 02 / Topic 2 of 7

Dot product, norms and cosine similarity

The dot product a @ b multiplies matching entries and sums them. The norm ‖a‖ is a vector's length: np.linalg.norm([3, 4]) is 5.0. Divide the dot product by both norms and you get cosine similarity — how much two vectors point the same way, ignoring length.

Cosine similarity is the core of embeddings and attention (Stage 4): texts with similar meaning become vectors with high cosine.

# examples/01_dot_product_and_cosine_similarity.py
import numpy as np

a = np.array([1.0, 2.0, 3.0])
b = np.array([2.0, 4.0, 6.0])     # same direction as a
c = np.array([-3.0, 0.0, 1.0])    # orthogonal to a

def cosine(u, v):
    return float(u @ v / (np.linalg.norm(u) * np.linalg.norm(v)))

print("a·b =", a @ b)              # a·b = 28.0
print("cos(a, b) =", round(cosine(a, b), 4))   # 1.0
print("cos(a, c) =", round(cosine(a, c), 4))   # 0.0
Cosine Meaning
1 Same direction (maximum similarity)
0 Orthogonal (unrelated)
-1 Opposite direction

🧪 Quick quiz

  1. What is the cosine similarity of two vectors pointing in exactly the same direction?
Show the answer

1 — cos(a, 2a) = 1.0. Cosine ignores length and measures only direction; orthogonal vectors give 0.

Done here? The practice set for Part 2 — 4 exercises with solutions — is on the part page.

Search the guide