Euclidean (L2) distance function.
Functions
euclidean_distance(x1: np.ndarray, x2: np.ndarray) -> float
Compute Euclidean (L2) distance between two points.
The Euclidean distance is the straight-line distance between two points in Euclidean space.
Theory
d(x, y) = \sqrt{\sum_{i=1}^n (x_i - y_i)^2}
This is a special case of the Minkowski distance with p = 2.
Parameters
x1
np.ndarray of shape (n_features,)
First point.
x2
np.ndarray of shape (n_features,)
Second point.
Returns
dist
float
Euclidean distance.
Notes
Complexity:
- Time: O(n) where n is the number of features.
Compute distance between two 2D points:
python
>>> import numpy as np
>>> from tuiml.algorithms.clustering.distance import euclidean_distance
>>> x1 = np.array([0, 0])
>>> x2 = np.array([3, 4])
>>> euclidean_distance(x1, x2)
5.0
euclidean_pairwise(X: np.ndarray, Y: np.ndarray=None) -> np.ndarray
Compute pairwise Euclidean distances efficiently using vectorization.
Uses the algebraic identity to avoid explicit broadcasting:
\|x - y\|^2 = \|x\|^2 + \|y\|^2 - 2 \langle x, y \rangle
Parameters
X
np.ndarray of shape (n_samples_X, n_features)
First set of samples.
Y
np.ndarray of shape (n_samples_Y, n_features)
= None
Second set of samples. Defaults to X.
Returns
dist_matrix
np.ndarray of shape (n_samples_X, n_samples_Y)
Distance matrix.