Lesson 4 of 18

Vector Norm

Vector Norm (Magnitude)

The norm (or magnitude) of a vector is its length:

Vert = sqrt{v_0^2 + v_1^2 + cdots + v_n^2} = sqrt{sum_{i=0}^{n} v_i^2}$$ ```python import math v = [3, 4] norm = math.sqrt(sum(x**2 for x in v)) print(norm) # √(9 + 16) = √25 = 5.0 ``` ### Unit Vectors A **unit vector** has norm 1. To **normalize** a vector — convert it to a unit vector — divide by its norm: ```python import math v = [3, 4] norm = math.sqrt(sum(x**2 for x in v)) # 5.0 unit = [round(x / norm, 2) for x in v] # [0.6, 0.8] print(math.sqrt(sum(x**2 for x in unit))) # ≈ 1.0 ``` Unit vectors preserve direction but discard magnitude. They answer: *which way?* rather than *how far?* ### Why It Matters - **Normalization** is used everywhere in ML: embeddings, attention weights, cosine similarity - The dot product formula $mathbf{a} cdot mathbf{b} = lVert mathbf{a} Vert lVert mathbf{b} Vert cos( heta)$ uses norms to extract the angle - **L2 regularization** in neural networks penalizes the norm of the weight vector ### Your Task Implement `normalize(v)` that returns the unit vector in the direction of $mathbf{v}$, with each component rounded to 2 decimal places.
Pyodide loading...
Loading...
Click "Run" to execute your code.