Module 5 · Lesson 1
Vectors & Dot Products
The dot product of two same-length vectors, np.dot(a, b) or simply
a @ b, multiplies corresponding elements and sums the results. It shows
up everywhere: it’s the core of matrix multiplication (next lesson), and
np.linalg.norm(v) — a vector’s length/magnitude — is just
sqrt(v @ v).
A useful derived quantity is cosine similarity, which measures the angle between two vectors regardless of their length:
cos(theta) = (a @ b) / (||a|| * ||b||)
It ranges from -1 (opposite direction) to 1 (same direction), with 0
meaning the vectors are orthogonal.
a = np.array([1.0, 2.0, 3.0])
b = np.array([4.0, 5.0, 6.0])
print("dot: ", np.dot(a, b), a @ b)
print("norm a:", np.linalg.norm(a), np.sqrt(a @ a))
cos_theta = (a @ b) / (np.linalg.norm(a) * np.linalg.norm(b))
print("cos similarity:", cos_theta)
Output:
dot: 32.0 32.0
norm a: 3.7416573867739413 3.7416573867739413
cos similarity: 0.9746318461970762
Unit vector
Write to_unit_vector(v) that returns v scaled to have length (norm)
exactly 1, pointing in the same direction. Use np.linalg.norm.
💡 Hint
Divide v by np.linalg.norm(v).
✅ Solution
def to_unit_vector(v):
return v / np.linalg.norm(v)
Cosine similarity
Write cosine_similarity(a, b) that returns the cosine similarity between
two 1-D vectors, as defined above.
💡 Hint
(a @ b) / (np.linalg.norm(a) * np.linalg.norm(b)) — just transcribe the formula above.
✅ Solution
def cosine_similarity(a, b):
return (a @ b) / (np.linalg.norm(a) * np.linalg.norm(b))