AI State of the Art
Math/Linear Algebra/14 min
Section 319

Norms and Distances: L1, L2, Cosine

Listen as a podcast β†’

Introduction: measuring in data space

In ML, you constantly need to answer two questions:

  • How big is this vector? (to control model weights, measure a gradient)
  • How close are these two vectors? (to compare embeddings, classify a neighbor, evaluate a prediction)

Norms answer the first question. Distances and similarities answer the second. They are the fundamental measurement tools of applied linear algebra.

The norm: measuring the size of a vector

A norm is a function that assigns to each vector a non-negative number, representing its "size" or "length." Formally, a norm βˆ₯β‹…βˆ₯\|\cdot\| satisfies:

  • βˆ₯vβˆ₯β‰₯0\|\mathbf{v}\| \geq 0 and βˆ₯vβˆ₯=0⇔v=0\|\mathbf{v}\| = 0 \Leftrightarrow \mathbf{v} = \mathbf{0}
  • βˆ₯Ξ±vβˆ₯=βˆ£Ξ±βˆ£β‹…βˆ₯vβˆ₯\|\alpha \mathbf{v}\| = |\alpha| \cdot \|\mathbf{v}\| (homogeneity)
  • βˆ₯u+vβˆ₯≀βˆ₯uβˆ₯+βˆ₯vβˆ₯\|\mathbf{u} + \mathbf{v}\| \leq \|\mathbf{u}\| + \|\mathbf{v}\| (triangle inequality)

Different norms measure size in different ways. The choice of norm is not trivial, it fundamentally changes the behavior of algorithms.

L1 norm: the Manhattan distance

Definition

The L1 norm of a vector v∈Rn\mathbf{v} \in \mathbb{R}^n is the sum of the absolute values of its components:

βˆ₯vβˆ₯1=βˆ‘i=1n∣vi∣\|\mathbf{v}\|_1 = \sum_{i=1}^{n} |v_i|

Intuition

Imagine a grid of streets (like in Manhattan). To go from point A to point B, you can't cut diagonally, you have to follow the streets. The L1 distance is the distance "walking along the blocks."

For v=(3,βˆ’4)\mathbf{v} = (3, -4): βˆ₯vβˆ₯1=∣3∣+βˆ£βˆ’4∣=7\|\mathbf{v}\|_1 = |3| + |-4| = 7.

Key property: sparsity

The L1 norm has a remarkable property: it promotes sparsity. When you minimize an objective with an L1 penalty, the solution tends to have many components exactly equal to zero.

Geometrically, the L1 "unit ball" (the set of vectors with L1 norm less than or equal to 1) is a diamond with tips on the axes. Optimal solutions tend to "land" on these tips, where coordinates are zero.

Three side-by-side diagrams in a theta1, theta2 parameter plane. Each shows concentric blue ellipses around the unconstrained optimum theta opt. On the left, a blue diamond labelled L1 Norm and Sparsity inducing, whose tip on the theta2 axis touches an ellipse. In the middle, an orange disc labelled L2 Norm and Weight sharing, whose edge touches an ellipse away from the axes. On the right, an in-between purple shape labelled L1 + L2 Norm.
The ellipses are level curves of the loss, the coloured region is the constraint imposed by the norm. The green dot is the solution: on the L1 diamond it lands on a tip, hence on an axis, hence with one coordinate exactly zero, this is the geometric origin of sparsity. With the L2 disc, contact almost always happens off the axes, and no weight is driven to zero.Source : Data 100, UC Berkeley, regularization notes

L2 norm: the Euclidean distance

Definition

The L2 norm is the square root of the sum of squares of the components:

βˆ₯vβˆ₯2=βˆ‘i=1nvi2\|\mathbf{v}\|_2 = \sqrt{\sum_{i=1}^{n} v_i^2}

It's the "natural" norm, the length of the vector in the usual geometric sense. It's the generalized Pythagorean theorem.

For v=(3,βˆ’4)\mathbf{v} = (3, -4): βˆ₯vβˆ₯2=9+16=5\|\mathbf{v}\|_2 = \sqrt{9 + 16} = 5.

Properties

The L2 norm is related to the dot product:

βˆ₯vβˆ₯2=⟨v,v⟩\|\mathbf{v}\|_2 = \sqrt{\langle \mathbf{v}, \mathbf{v} \rangle}

The L2 "unit ball" is a sphere. Optimal solutions with an L2 penalty are small but rarely exactly zero, the L2 norm distributes the penalty uniformly across all components.

L-infinity norm: the maximum value

Definition

βˆ₯vβˆ₯∞=max⁑i∣vi∣\|\mathbf{v}\|_\infty = \max_{i} |v_i|

It's simply the largest component in absolute value. For v=(3,βˆ’4,1)\mathbf{v} = (3, -4, 1): βˆ₯vβˆ₯∞=4\|\mathbf{v}\|_\infty = 4.

Intuition

Imagine a chessboard where each square is a king's move. The L-infinity distance between two squares is the number of moves needed, the king can move diagonally.

The L-infinity unit ball is a hypercube (a square in 2D, a cube in 3D).

Use in ML

The L-infinity norm is used in adversarial attacks. An adversarial perturbation with L-infinity norm bounded by Ο΅\epsilon means that no pixel is modified by more than Ο΅\epsilon. It's a realistic model of "imperceptible" perturbation.

Comparing norms

For a vector v=(1,2,3)\mathbf{v} = (1, 2, 3):

NormFormulaValue
L1$1
L21+4+9\sqrt{1 + 4 + 9}β‰ˆ3.74\approx 3.74
L-infinitymax⁑(1,2,3)\max(1, 2, 3)33

All norms are equivalent in finite dimensions (they define the same notions of convergence), but they don't behave the same way in optimization.

Ordering relation: βˆ₯vβˆ₯βˆžβ‰€βˆ₯vβˆ₯2≀βˆ₯vβˆ₯1\|\mathbf{v}\|_\infty \leq \|\mathbf{v}\|_2 \leq \|\mathbf{v}\|_1

Three plots in the plane, with both axes graduated from -1 to 1. On the left, the L1 unit ball is a blue diamond with vertices at (1,0), (0,1), (-1,0) and (0,-1). In the middle, the L2 unit ball is a green disc of radius 1. On the right, the L-infinity unit ball is a red square of side 2 centred on the origin.
The three norms share the same origin and axes but not the same idea of size 1: a diamond for L1, a circle for L2, a square for L-infinity. The ordering relation is visible directly, the diamond sits inside the circle, which sits inside the square.Source : Numerical analysis course, Waseda University, Vector Norms and Matrix Norms

Distance between two vectors

The distance between two vectors u\mathbf{u} and v\mathbf{v} under a norm is simply the norm of their difference:

d(u,v)=βˆ₯uβˆ’vβˆ₯d(\mathbf{u}, \mathbf{v}) = \|\mathbf{u} - \mathbf{v}\|

The L2 distance between u\mathbf{u} and v\mathbf{v} is the classic Euclidean distance:

d2(u,v)=βˆ‘i=1n(uiβˆ’vi)2d_2(\mathbf{u}, \mathbf{v}) = \sqrt{\sum_{i=1}^{n} (u_i - v_i)^2}

Cosine similarity: comparing directions

Definition

Cosine similarity doesn't measure distance, but the angle between two vectors:

sim(u,v)=cos⁑(ΞΈ)=⟨u,v⟩βˆ₯uβˆ₯2β‹…βˆ₯vβˆ₯2=βˆ‘iuiviβˆ‘iui2β‹…βˆ‘ivi2\text{sim}(\mathbf{u}, \mathbf{v}) = \cos(\theta) = \frac{\langle \mathbf{u}, \mathbf{v} \rangle}{\|\mathbf{u}\|_2 \cdot \|\mathbf{v}\|_2} = \frac{\sum_{i} u_i v_i}{\sqrt{\sum_{i} u_i^2} \cdot \sqrt{\sum_{i} v_i^2}}

The result is between βˆ’1-1 and 11:

  • sim=1\text{sim} = 1: the vectors point in the same direction (angle of 0)
  • sim=0\text{sim} = 0: the vectors are orthogonal (angle of 90 degrees)
  • sim=βˆ’1\text{sim} = -1: the vectors point in opposite directions (angle of 180 degrees)
A two-axis coordinate system with two arrows starting at the origin and pointing up and to the right, labelled A and B. A small arc marks the angle between them, annotated 10 degrees. Text alongside states that the angle between vectors A and B is 10 degrees and that the cosine of 10 degrees is 0.9848.
What matters is not the length of the arrows but the angular gap between them. A 10-degree angle gives a similarity of 0.98, two nearly aligned vectors count as very close, even if one is far longer than the other.Source : Built In, Understanding Cosine Similarity and Its Applications

Why it's so important in ML

Cosine similarity ignores magnitude and only looks at direction. That's exactly what you want for comparing embeddings.

Concrete example: two documents of very different lengths (a tweet and an article) discuss the same topic. Their TF-IDF vectors have very different norms (the article has more words), but their directions are similar. Euclidean distance judges them "far apart," cosine similarity judges them "close."

It's the standard metric for:

  • Semantic search: finding documents most similar to a query
  • Word embeddings: measuring semantic proximity (Word2Vec, GloVe)
  • RAG (Retrieval-Augmented Generation): retrieving relevant passages for a question
  • Recommendation systems: comparing user profiles

Cosine distance

Cosine distance is simply 1βˆ’sim(u,v)1 - \text{sim}(\mathbf{u}, \mathbf{v}). It equals 0 for vectors identical in direction and 2 for opposite vectors.

Applications in ML

L1 and L2 regularization

Regularization adds a penalty on the norm of weights to the loss function:

  • L2 regularization (ridge, weight decay): Lreg=L+Ξ»βˆ₯wβˆ₯22\mathcal{L}_{\text{reg}} = \mathcal{L} + \lambda \|\mathbf{w}\|_2^2. Pushes all weights toward small values. Prevents overfitting by limiting the "size" of the model.

  • L1 regularization (lasso): Lreg=L+Ξ»βˆ₯wβˆ₯1\mathcal{L}_{\text{reg}} = \mathcal{L} + \lambda \|\mathbf{w}\|_1. Pushes some weights exactly to zero. Produces sparse models, useful for feature selection.

  • Elastic Net: combines both, Ξ»1βˆ₯wβˆ₯1+Ξ»2βˆ₯wβˆ₯22\lambda_1 \|\mathbf{w}\|_1 + \lambda_2 \|\mathbf{w}\|_2^2.

Loss functions

Several loss functions are defined in terms of norms:

  • MSE (Mean Squared Error): it's the squared L2 norm of the error (divided by nn): 1nβˆ₯yβˆ’y^βˆ₯22\frac{1}{n}\|\mathbf{y} - \hat{\mathbf{y}}\|_2^2

  • MAE (Mean Absolute Error): it's the L1 norm of the error (divided by nn): 1nβˆ₯yβˆ’y^βˆ₯1\frac{1}{n}\|\mathbf{y} - \hat{\mathbf{y}}\|_1

  • Cosine embedding loss: used to train embedding models to bring similar pairs closer and push dissimilar pairs apart.

MSE penalizes large errors more (because of the square). MAE is more robust to outliers.

k-NN (k nearest neighbors)

The k-NN algorithm classifies a point by looking at the kk closest points in the training dataset. The notion of "close" depends entirely on the choice of distance. Using L2, L1, or cosine distance gives different results, and the right choice depends on the problem.

Gradient clipping

During training, if the gradient becomes too large (gradient explosion), you "clip" it:

g←gβˆ₯gβˆ₯2β‹…max_normifΒ βˆ₯gβˆ₯2>max_norm\mathbf{g} \leftarrow \frac{\mathbf{g}}{\|\mathbf{g}\|_2} \cdot \text{max\_norm} \quad \text{if } \|\mathbf{g}\|_2 > \text{max\_norm}

It's a normalization by the L2 norm of the gradient. Without this, training RNNs and Transformers would be unstable.

Why this matters for AI

Norms and distances are the measurement instruments of ML:

  • Regularization (L1/L2) controls model complexity and fights overfitting
  • Cosine similarity is the universal metric for comparing embeddings
  • Loss functions (MSE, MAE) measure prediction quality in terms of norms
  • Gradient clipping uses the L2 norm to stabilize training

Choosing the right norm or distance isn't a technical detail. It's a modeling decision that profoundly affects algorithm behavior. Understanding these tools means being able to make informed choices.

Where this is used. Cosine similarity is the measuring instrument of all semantic search: see text embeddings.