BRAGA

02 Writing02-02 Notes02-02-175

Minkowski Distance (Lₚ norm)

Published 16 Apr 20266 min read
Contents
  1. 01Deep Breakdown
  2. 02Flowchart
  3. 03Real-world use
  4. 04The formula, piece by piece
  5. 05The formula in words
  6. 06Critical Concepts
  7. 07Step-by-step calculation (tiny example)
  8. 08Code examples
D(x,y)=(∑i=1n∣xi−yi∣p)1/pD(x,y) = \left( \sum_{i=1}^n |x_i - y_i|^p \right)^{1/p}
(1)

Deep Breakdown

What it tells me (Situation Awareness): The Minkowski distance is the general LpL_p norm-based distance family. Every standard distance metric you know is a special case: p=1p=1 is Manhattan, p=2p=2 is Euclidean, p→∞p \to \infty is Chebyshev. The parameter pp controls how much weight is given to large vs. small differences: large pp increasingly dominates on the single largest component difference. In DA/DS: Minkowski distance is used in kk-NN classification/regression, clustering (k-means with custom distance), anomaly detection, and any pipeline where the geometry of the feature space matters. Choosing pp is a hyperparameter that affects model sensitivity to outlier features.

Flowchart

Vectors x =(x1,...,xn), y =(y1,...,yn),parameter p = 1Computeelement-wisedifferences: |xi -yi|Raise each topower p: |xi -yi|^pSum all terms:sum_i |xi - yi|^pTake p-th root:(sum)^(1/p)D_p(x,y) =Minkowskidistancep=1: Manhattan(L1), p=2:Euclidean (L2)p - inf:Chebyshev(L_inf = max |xi -yi|)

Real-world use

Where it is used

kk-NN with tunable pp (scikit-learn KNeighborsClassifier(metric='minkowski', p=p)), distance-based clustering, feature space analysis, and grid search over pp as a hyperparameter in any distance-based model.

Problem it solves

Different feature spaces have different geometric properties. Euclidean distance penalizes large deviations quadratically. Manhattan is robust to this. Chebyshev captures the worst-case deviation. Minkowski unifies these under one formula so you can tune or search over the right geometry for your data.

How it solves the problem

By varying pp, the shape of the "unit ball" (set of all points at distance 1) changes from a diamond (p=1p=1), to a circle (p=2p=2), to a square (p→∞p \to \infty). The appropriate pp depends on the domain: high-dimensional sparse data tends to prefer p=1p=1 (Manhattan); dense continuous data tends to prefer p=2p=2 (Euclidean).

Example in a business

A DS trains a kk-NN churn classifier on customer behavioral features and tunes pp via cross-validation. For p=1p=1 (Manhattan) the model focuses on total behavioral deviation; for p=2p=2 (Euclidean) it weights larger deviations more strongly. The optimal pp is selected by comparing validation AUC across p∈{1,1.5,2,3}p \in \{1, 1.5, 2, 3\}.

The formula, piece by piece

  • D(x,y)D(x,y): the Minkowski distance between vectors x,y∈Rnx, y \in \mathbb{R}^n
  • ∣xi−yi∣|x_i - y_i|: absolute difference of the ii-th feature
  • (⋅)p(\cdot)^p: raising to power pp controls sensitivity to large differences; large pp = more weight on the biggest gap
  • ∑i=1n\sum_{i=1}^n: sum over all nn dimensions
  • (⋅)1/p(\cdot)^{1/p}: the pp-th root brings the result back to the original scale (undoes the power)
  • p≥1p \geq 1: the constraint that makes this a proper metric (triangle inequality holds iff p≥1p \geq 1, by Minkowski's inequality)
  • Special cases: p=1p=1 (Manhattan), p=2p=2 (Euclidean), p→∞p \to \infty gives max⁡i∣xi−yi∣\max_i |x_i - y_i| (Chebyshev)

The formula in words

"Compute the absolute difference in each coordinate. Raise each to the pp-th power (amplifying large gaps more for larger pp). Sum them up. Then take the pp-th root to restore the scale. The result is a distance where pp controls how much the biggest gaps dominate." Tiny example: x=(1,0)x = (1, 0), y=(4,3)y = (4, 3).

  • p=1p=1: ∣3∣+∣3∣=6|3| + |3| = 6.
  • p=2p=2: 9+9=18≈4.243\sqrt{9+9} = \sqrt{18} \approx 4.243.
  • p→∞p \to \infty: max⁡(3,3)=3\max(3, 3) = 3.

Critical Concepts

  • p≥1p \geq 1 required for metric: for p<1p < 1, the triangle inequality fails (it is a semimetric, not a metric).
  • Curse of dimensionality: as n→∞n \to \infty, Minkowski distances concentrate — all pairwise distances become similar. This makes distance-based models unreliable in very high dimensions.
  • p=2p=2 is rotation-invariant: only p=2p=2 (Euclidean) is invariant under rotation of the coordinate system. p=1p=1 and others depend on axis alignment.
  • p→∞p \to \infty limit: lim⁡p→∞(∑∣xi−yi∣p)1/p=max⁡i∣xi−yi∣\lim_{p \to \infty} \left(\sum |x_i - y_i|^p\right)^{1/p} = \max_i |x_i - y_i|.
  • Weighted Minkowski: (∑iwi∣xi−yi∣p)1/p\left(\sum_i w_i |x_i - y_i|^p\right)^{1/p} allows feature importance weighting.
  • scikit-learn: KNeighborsClassifier(metric='minkowski', p=p) defaults to p=2p=2 (Euclidean).

Step-by-step calculation (tiny example)

Step 1: Set up vectors and choose pp x=(1,2,3)x = (1, 2, 3), y=(4,0,6)y = (4, 0, 6). Differences: ∣1−4∣=3|1-4| = 3, ∣2−0∣=2|2-0| = 2, ∣3−6∣=3|3-6| = 3.

Step 2: Compute for p=1p=1 (Manhattan) D1=3+2+3=8D_1 = 3 + 2 + 3 = 8.

Step 3: Compute for p=2p=2 (Euclidean) D2=9+4+9=22≈4.690D_2 = \sqrt{9 + 4 + 9} = \sqrt{22} \approx 4.690.

Step 4: Compute for p=3p=3 D3=(27+8+27)1/3=621/3≈3.958D_3 = (27 + 8 + 27)^{1/3} = 62^{1/3} \approx 3.958. As pp increases, the result approaches max⁡(3,2,3)=3\max(3,2,3) = 3 (Chebyshev). ✓\checkmark

Code examples

Beginner example (Python)

python
import numpy as np

def minkowski_distance(x: np.ndarray, y: np.ndarray, p: float) -> float:
    """Compute Minkowski distance D_p(x, y) for given p >= 1."""
    if p == float('inf'):
        return float(np.max(np.abs(x - y)))
    return float(np.sum(np.abs(x - y) ** p) ** (1.0 / p))
x = np.array([1.0, 2.0, 3.0])
y = np.array([4.0, 0.0, 6.0])
for p_val in [1, 2, 3, 10, float('inf')]:
    dist = minkowski_distance(x, y, p_val)
print(f"p={p_val:>5}: D_p = {dist:.4f}")   # Compare with scipy reference
from scipy.spatial.distance import minkowski
print(f"\nscipy minkowski p=2: {minkowski(x, y, p=2):.4f}")
print(f"scipy minkowski p=1: {minkowski(x, y, p=1):.4f}")

Beginner example (R)

r
# -- Minkowski distance for varying p ---
minkowski_dist <- function(x, y, p) { if (is.infinite(p))
  return(max(abs(x - y))) sum(abs(x - y)^p)^(1 / p)
}
x <- c(1, 2, 3)
y <- c(4, 0, 6)
for (p_val in c(1, 2, 3, 10, Inf)) { dist <- minkowski_dist(x, y, p_val)
  cat(sprintf("p = %5s: D_p = %.4f\n", ifelse(is.infinite(p_val), "Inf", as.character(p_val)), dist))
}

Professional example (Python)

python
import numpy as np
import pandas as pd
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import make_classification
np.random.seed(42)   # -- Business scenario: tune Minkowski p as hyperparameter for kNN churn model ---
X, y = make_classification( n_samples=800, n_features=10, n_informative=6, n_redundant=2, random_state=42 )
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
P_VALUES = [1, 1.5, 2, 3, 5]
CV = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
K_NEIGHBORS = 7
results = []
for p_val in P_VALUES:
    clf = KNeighborsClassifier(n_neighbors=K_NEIGHBORS, metric='minkowski', p=p_val)
scores = cross_val_score(clf, X_scaled, y, cv=CV, scoring='roc_auc')
results.append({ "p": p_val, "norm_name": {1: "Manhattan", 2: "Euclidean"}.get(p_val, f"L{p_val}"), "mean_auc": round(scores.mean(), 4), "std_auc": round(scores.std(), 4), })
df = pd.DataFrame(results)
print(f"kNN (k={K_NEIGHBORS}) Minkowski distance hyperparameter search:")
print(df.to_string(index=False))
best_row = df.loc[df["mean_auc"].idxmax()]
print(f"\nBest: p={best_row['p']} ({best_row['norm_name']}), AUC={best_row['mean_auc']:.4f}")

Source: domain knowledge

#linear-algebra#spatial-distance-norms-and-analytic-geometry#advanced-distance-and-similarity-metrics

Keyboard shortcuts

Single keys, ignored while typing in a field or with Cmd, Ctrl or Alt held.

0
Home
1 2 3 4
Work, Writing, Tools, About
j / k
Next / previous section on this page
n / p
Next / previous project or essay
u
Up one level
l
Deutsch
t
Light or dark theme
?
This list
Esc
Close