Overview
An outlier is a value far from where most of the column lies. It may be an error, such as an age of 999, or a real but rare case. Either way it can pull a mean, a scale or a fitted line toward itself. Detection needs a centre, a measure of spread and a rule for how many spreads away is too far. The three methods here differ in how they measure centre and spread. Quartiles and medians are barely moved by the outliers themselves, while the mean and the standard deviation are.
A short history
Rules for rejecting doubtful observations go back to astronomers in the 1800s. Clipping extreme values to a limit is called winsorizing after the statistician Charles Winsor. John Tukey's 1977 book Exploratory Data Analysis gave the box plot rule that flags points beyond 1.5 interquartile ranges from the quartiles. Robust statistics in the 1960s and 1970s, including Frank Hampel's work, added the median absolute deviation.
How it works
- Choose a method: iqr (quartiles), zscore (mean and standard deviation) or mad (median and median absolute deviation), and a threshold in that method's units.
- Call fit on the training data. For each column it computes the centre and spread, ignoring NaN, and stores the bounds lower_ and upper_.
- Call mask to get a table of true and false values marking every entry outside its column's bounds.
- Call scores to see how far each value is from the middle of its bounds. A score above 1 means outside.
- Call transform to treat the flagged values: clip moves them to the nearest bound, nan blanks them for a later imputation step, remove drops their rows.
- Apply the same fitted bounds to validation and test data.
Watch out for
- The z-score uses the mean and standard deviation, which the outliers themselves inflate. One huge value widens the bounds enough to hide itself. This is called masking.
- Extreme values in a skewed column, such as income, are often real. Clipping them removes signal. Try a log transform first and look at the flagged rows before treating them.
- The check is one column at a time. A row whose values are each ordinary but impossible together, such as age 5 and height 190 cm, is not flagged.
- With treatment remove the row count changes, so the labels must be cut the same way with kept_rows.
- If more than half of a column holds the same value, the median absolute deviation is zero. The bounds collapse to the median and every other value is flagged.
Use cases
When to use it
Before scaling or fitting models that are sensitive to extreme values, such as linear models, distance-based models and neural networks, and whenever a column has known impossible values.
In industry
- Finance
- Analysts winsorize extreme returns and accounting ratios before fitting models, so a few firms do not dominate the estimates.
- Manufacturing and sensors
- Plants flag readings outside limits learned from normal operation, which may be faulty sensors or real process faults.
- Data entry and billing
- Organisations catch impossible values, such as an age of 500 or a misplaced decimal point, before reports are built.
Choosing it: what must hold
- Numeric columns where extreme values are errors or would distort the model, not the signal you are looking for.
- Bounds fitted on the training data only and reused on later data.
- A method matched to the shape: z-scores assume a roughly bell-shaped column, while quartile and median rules tolerate skew.
- A decision on treatment: clip, remove the row, or blank the value for later imputation.
When to choose something else
| If | Use instead |
|---|---|
| The extreme values are the target, as in fraud or fault detection | An anomaly detection model, and keep the values |
| The column is strongly skewed by nature, such as income | A log or power transformation before any outlier rule |
| A point is unusual only in combination with other columns | A multivariate method such as Mahalanobis distance or isolation forest |
| The model is tree-based | Often no treatment, since trees split on order and are little affected |
Math foundations
Tukey's fences (iqr)
The bounds sit interquartile ranges beyond the quartiles. The usual is 1.5. Quartiles ignore how extreme the tails are, so a few outliers do not move the fences.
The z-score rule
A value is flagged when it lies more than standard deviations from the mean, usually 3. For normal data about 0.27 percent of values fall outside.
Median absolute deviation
The typical distance from the median . It plays the role of the standard deviation but is not moved by the outliers.
The modified z-score (mad)
For normal data the MAD equals 0.6745 standard deviations, so this factor puts on the same scale as an ordinary z-score. The usual threshold is 3.5.
Clipping
Also called winsorizing. A value outside the bounds is moved to the nearest bound. Values inside are unchanged.
Symbols
- one value of a column
- the 25th and 75th percentiles of the column
- the threshold setting
- the lower and upper bounds (lower_ and upper_)
- the mean and standard deviation of the column
- the median of the column
- the median absolute deviation
- the modified z-score
- the value after clipping
Worked by hand
A column holds 1, 2, 3, 4 and 100. Find the iqr bounds with , then check what the z-score rule with makes of the value 100.
The iqr rule flags 100 and clipping moves it to 7. The z-score rule does not flag it, because 100 has dragged the mean to 22 and the standard deviation to 39. That is masking.
Visual example
Loading the example.
Try this
- Switch the method from iqr to zscore. The three far values are no longer flagged, because they stretched the bounds themselves. That is masking.
- With zscore, lower the number of far values to 1 and they are caught again. Then try mad.
- Change the treatment and compare the lower strip: clip moves the values to the bound, nan blanks them, remove drops their rows.
Code sample
import numpy as np
from impl import OutlierHandler
from config import OutlierConfig
x = np.array([10.0, 11.0, 12.0, 13.0, 14.0, 500.0])
handler = OutlierHandler(OutlierConfig(method="iqr", threshold=1.5, treatment="clip")).fit(x)
print(handler.mask(x)[:, 0]) # [False False False False False True]
print(handler.transform(x)[:, 0]) # 500.0 is pulled down to the upper fence, 17.5Read the implementation (87 lines)
"""Outlier detection (IQR fences, z-score, modified z-score) and treatment (clip, remove, mark as NaN).
NumPy only. `fit` learns a lower and an upper bound per column from the training data; `mask` flags values
outside the bounds and `transform` treats them. NaN values are ignored when fitting and are never flagged.
"""
from __future__ import annotations
import numpy as np
try:
from .config import OutlierConfig
except ImportError: # run from the template's own folder
from config import OutlierConfig
_MAD_TO_SIGMA = 0.6744897501960817 # 75th percentile of the standard normal: MAD = 0.6745 * sigma for normal data
def _as_2d(X) -> np.ndarray:
"""Return X as a float array (n_samples, n_features); a 1-D input becomes one column."""
X = np.asarray(X, dtype=float)
return X[:, None] if X.ndim == 1 else X
class OutlierHandler:
"""Per-column outlier bounds. After `fit`: `lower_` and `upper_`, each of shape (n_features,)."""
def __init__(self, config: OutlierConfig | None = None) -> None:
self.config = config or OutlierConfig()
self.lower_: np.ndarray | None = None
self.upper_: np.ndarray | None = None
def fit(self, X) -> "OutlierHandler":
"""Learn the bounds from X, shape (n_samples, n_features)."""
X = _as_2d(X)
k = self.config.threshold
if self.config.method == "iqr":
q1, q3 = np.nanpercentile(X, [25, 75], axis=0)
spread = q3 - q1
self.lower_, self.upper_ = q1 - k * spread, q3 + k * spread
elif self.config.method == "zscore":
mean, std = np.nanmean(X, axis=0), np.nanstd(X, axis=0)
self.lower_, self.upper_ = mean - k * std, mean + k * std
else: # mad: modified z-score = 0.6745 * (x - median) / MAD
median = np.nanmedian(X, axis=0)
mad = np.nanmedian(np.abs(X - median), axis=0)
reach = k * mad / _MAD_TO_SIGMA
self.lower_, self.upper_ = median - reach, median + reach
return self
def _check(self, X) -> np.ndarray:
if self.lower_ is None:
raise RuntimeError("call fit before using the handler")
X = _as_2d(X)
if X.shape[1] != self.lower_.shape[0]:
raise ValueError(f"X has {X.shape[1]} columns, the handler was fitted on {self.lower_.shape[0]}")
return X
def mask(self, X) -> np.ndarray:
"""Boolean array, same shape as X (n_samples, n_features): True where a value is an outlier."""
X = self._check(X)
with np.errstate(invalid="ignore"):
return (X < self.lower_) | (X > self.upper_)
def scores(self, X) -> np.ndarray:
"""Distance of each value from the centre of its bounds, in units of the half-width (above 1 = outlier)."""
X = self._check(X)
centre = 0.5 * (self.lower_ + self.upper_)
half = 0.5 * (self.upper_ - self.lower_)
return np.abs(X - centre) / np.where(half > 0, half, 1.0)
def transform(self, X) -> np.ndarray:
"""Treat the outliers of X. "remove" returns fewer rows (see `kept_rows`)."""
X = self._check(X)
flagged = self.mask(X)
if self.config.treatment == "clip":
return np.where(np.isnan(X), X, np.clip(X, self.lower_, self.upper_))
if self.config.treatment == "nan":
return np.where(flagged, np.nan, X)
return X[~flagged.any(axis=1)]
def kept_rows(self, X) -> np.ndarray:
"""Indices of the rows that "remove" keeps (use it to drop the same rows from the labels)."""
return np.flatnonzero(~self.mask(X).any(axis=1))
def fit_transform(self, X) -> np.ndarray:
"""Fit on X and return the treated X."""
return self.fit(X).transform(X)- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Draw 500 values from a normal distribution and replace five of them with values 20 times larger. Fit an OutlierHandler for each method (iqr with threshold 1.5, zscore with 3.0, mad with 3.5) through OutlierConfig. Compare lower_ and upper_, count the true entries of mask, and check which methods catch all five. Then repeat with fifty planted values.
Check on learning
- With five data points and the standard deviation used here, no value can ever have a z-score above 2. Why does a small sample make the z-score rule powerless?
A way to think about it
Put four points at one place and move the fifth far away. Watch how the mean and the standard deviation both grow with the distance.
- A column of house prices has a long right tail and the iqr rule flags 8 percent of rows. Would you clip them? What would you try first?
A way to think about it
Ask whether the flagged houses are errors or real expensive houses. Consider what the column looks like after taking a logarithm.
- Why are the bounds learned on the training data and then reused, instead of recomputed on each new batch?
A way to think about it
Think about a single new row arriving for prediction, and about a test batch whose distribution has shifted. What would bounds computed there mean?
- Compare the treatments clip, nan and remove for a sensor that sometimes reports a wild reading. What does each one claim about the true value?
A way to think about it
Clip claims the truth was at the edge. Blanking claims it is unknown. Removing claims the whole row is untrustworthy. Match the claim to what you know about the fault.