Norms: how big is a vector?
Straight-line length is one way to measure a vector; adding absolute values and taking the biggest entry are two more. Each draws a different shape, and each shows up in training.
1. The idea
A norm measures the size of a vector with one number, never negative and zero only for the zero vector. The everyday one is straight-line length, the L2 norm: βπ±ββ = β(xβΒ² + xβΒ² + β¦). It is Pythagoras, in any number of dimensions, and it equals β(π±Β·π±).
It isn't the only sensible choice. The L1 norm adds up absolute values, βπ±ββ = |xβ| + |xβ| + β¦, like walking a city grid instead of flying. The Lβ norm keeps only the biggest entry. The widget draws each one's unit ball, every point whose norm is exactly 1: L2 gives a circle, L1 a diamond, Lβ a square.
Norms are how machine learning measures βtoo bigβ. Weight decay adds Ξ»βπ°ββΒ² to the loss to keep weights small. An L1 penalty Ξ»βπ°ββ pushes many weights to exactly zero, because the diamond's corners sit on the axes, where some coordinates are 0. Gradient clipping shrinks a gradient whose norm is too large, and dividing an embedding by its L2 norm keeps only its direction.
2. Try it: three ways to measure
Pick a norm to draw its unit ball, then drag π±. Put π± on the L1 diamond and switch to L2: is it inside the circle, on it or outside? Can a point on the diamond ever be outside the circle?
3. The math
4. The code (python)
import numpy as np
x = np.array([3.0, -4.0])
print(np.linalg.norm(x)) # 5.0
print(np.linalg.norm(x, 1)) # 7.0
print(np.linalg.norm(x, np.inf)) # 4.0
print(x / np.linalg.norm(x)) # [ 0.6 -0.8]
g = np.array([6.0, 8.0]) # clip a gradient to a norm of at most 5
max_norm = 5.0
n = np.linalg.norm(g)
if n > max_norm:
g = g * (max_norm / n)
print(g, np.linalg.norm(g)) # [3. 4.] 5.05. Youβll see this in
- Core Course chapter 11: overfitting and regularization the L2 penalty at work
- Ridge regression in the catalog
- Reference notes: linear algebra norms of matrices too
6. Check yourself
Finished this chapter?
What changed in ML architectures this week
New models worth knowing, benchmark moves, and one architecture explained in plain words. Free, once a week, unsubscribe anytime.