How do you calculate Euclidean distance between two vectors using NumPy? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you calculate Euclidean distance between two vectors using NumPy?

message-square
0

Use np.linalg.norm(a - b) (or np.linalg.norm(A - B, axis=1) for row-wise batch distances across 2D arrays)—which delegates directly to optimized BLAS routines to compute $\sqrt{\sum_i (a_i - b_i)^2}$ with built-in numerical overflow/underflow scaling.

Basic Example

import numpy as np

a = np.array([1.0, 2.0, 3.0])
b = np.array([4.0, 6.0, 3.0])

# 1. Recommended (cleanest, numerically stable, BLAS-backed):
dist = np.linalg.norm(a - b)
print(dist)
# Output: 5.0

# 2. Batch row-wise distances between N pairs of vectors (shape: (N, D)):
A = np.array([[0.0, 0.0], [1.0, 2.0], [3.0, 4.0]])
B = np.array([[3.0, 4.0], [1.0, 2.0], [0.0, 0.0]])
row_dists = np.linalg.norm(A - B, axis=1)
print(row_dists)
# Output: [5. 0. 5.]

Key Details & Edge Cases

  • Always pass axis=1 (or axis=-1) when computing row-wise distances on 2D arrays:
    • Calling np.linalg.norm(A - B) without axis= computes the Frobenius norm across the entire 2D matrix (returning a single scalar $\sqrt{\sum_{i,j}(A_{ij} - B_{ij})^2}$) rather than one distance per row! Always specify axis=-1 for batches of vectors.
  • Avoid Python lists ([1, 2] - [3, 4] raises TypeError):
    • Subtracting two raw Python list objects raises TypeError: unsupported operand type(s) for -: 'list' and 'list'. Convert inputs with np.asarray(a, dtype=float) first if inputs might be lists or tuples.
  • Integer overflow trap with manual np.sqrt(np.sum((a - b) ** 2)):
    • On int8, int16, or int32 arrays, squaring large differences via (a - b) ** 2 wraps around silently (int32 overflows past $\pm 2.14 \times 10^9$), producing nan or wrong distances—whereas np.linalg.norm(a - b) automatically promotes integers to float64 and avoids intermediate overflow.
  • All-pairs pairwise distance matrix (scipy.spatial.distance.cdist vs. broadcasting):
    • To compute every pairwise distance between matrix X (M, D) and matrix Y (N, D) into an (M, N) matrix:
      • Best for large matrices: from scipy.spatial.distance import cdist; dist_matrix = cdist(X, Y, metric="euclidean") (fast C loop without allocating an (M, N, D) intermediate array).
      • Pure NumPy: np.linalg.norm(X[:, None, :] - Y[None, :, :], axis=-1) (clean for small/medium arrays, but uses $O(M \cdot N \cdot D)$ RAM).
  • Skip np.sqrt() when only comparing relative distances (nearest-neighbor search):
    • Because $\sqrt{x}$ is strictly monotonic for $x \ge 0$, comparing squared Euclidean distances via diff = a - b; sq_dist = np.dot(diff, diff) (or np.einsum("ij,ij->i", diff, diff) for 2D batches) avoids the square-root overhead and runs 2–4× faster in tight inner loops.

Comparison of Euclidean Distance Methods in NumPy & SciPy

Method Syntax 2D Batch Support ((N, D)) Overflow Safe on int Arrays? Best Used When
np.linalg.norm(a - b) (Recommended) np.linalg.norm(a - b, axis=-1) Yes (axis=-1) Yes (auto-casts to float) General-purpose 1D vector or 2D batch row-wise Euclidean distance.
Squared Distance (np.dot / einsum) d = a - b; np.dot(d, d) Yes (np.einsum("ij,ij->i", d, d)) Cast to float64 first Nearest-neighbor ranking or clustering where exact $\sqrt{\cdot}$ scale isn’t needed.
np.sqrt(np.sum((a - b) ** 2)) np.sqrt(np.sum((a - b) ** 2, axis=-1)) Yes (axis=-1) No (risks int32 wrap-around) Teaching/explicit formula code on pre-validated floating-point arrays.
scipy.spatial.distance.cdist cdist(X, Y, metric="euclidean") Yes (all (M, N) pairs) Yes Computing full pairwise distance matrices between two large sets of vectors.