815. Flag outliers with Mahalanobis distance
Why it matters Anomaly detection on embeddings and out-of-distribution checks for classifiers often use Mahalanobis distance.
Euclidean distance ignores that features have different spreads and correlations. Mahalanobis distance measures how many standard deviations a point is from the mean along the data's own shape.
Write mahalanobis(X, points). Fit mean mu and covariance S on X (rows are samples, use the n - 1 sample covariance like np.cov(X, rowvar=False)). For each row p of points return sqrt((p - mu) S^-1 (p - mu)^T). Use np.linalg.solve rather than an explicit inverse. Return a 1D float array.
Inputs can be Python lists or NumPy arrays, so convert them with np.asarray first.
def mahalanobis(X, points)Example 1
Input: mahalanobis([[0.0, 0.0], [2.0, 0.0], [0.0, 2.0], [2.0, 2.0]], [[1.0, 1.0], [3.0, 1.0]])
Output: [0.0, 1.7321]
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Fit mu and the sample covariance on X only.
Hint 2
Solve S z = diff instead of inverting S.
Hint 3
Row-wise dot product of diff and z, then sqrt.
Common mistakes
- Using
np.cov(X)without rowvar=False, which treats rows as variables. - Using the population covariance when the problem asks for n - 1.
Understand the idea
Multiplying by the inverse covariance rescales each direction by its spread and removes correlation, so a step along a tight direction counts more than the same step along a loose one.
four corners of a 2 by 2 square have mean (1, 1) and sample covariance 4/3 I. The point (3, 1) is 2 away in x, so the distance is 2 / sqrt(4/3) = 1.732.
d = sqrt(diff^T S^-1 diff), with S^-1 diff from solve
Shapes and data flow
diff (k, d), solve(S, diff.T).T (k, d) -> row-wise dot -> (k,)
Similar questions
- Decide if a new prompt really converts better with a two-proportion z-testMedium
- Update your belief about a model's pass rate with a Beta priorMedium
- Put a bootstrap confidence interval on an evaluation scoreMedium
- Compare two eval runs with Welch's t-test statisticMedium