TExcelTAD

Outlier Detection

An outlier is a value or a sample that lies far from the rest. Some outliers are errors: an age of 230, a body temperature of 3.7 (a missing decimal point), a price of 0.01 from a test transaction. Others are real but rare: a billionaire's income, a once-a-decade storm, a fraudulent payment. The first kind must be fixed or removed; the second kind may be exactly what a model must learn about. Detection methods can only flag candidates. Deciding which kind each one is takes knowledge of the domain.

Rule-based checks first

The cheapest and most reliable outlier test is a rule from the domain: values that are impossible, not just unusual.

python · try it yourself
import pandas as pd

patients = pd.DataFrame({
    "age":     [34, 51, 230, 45, 38, 0, 62, 29],
    "temp_c":  [36.8, 37.2, 36.5, 3.71, 38.9, 36.9, 98.6, 37.0],
    "height_cm": [172, 165, 180, 158, 1.75, 169, 177, 190],
})
rules = {
    "age": (0, 110),          # 0 is valid for newborns; check against the population
    "temp_c": (30, 45),       # outside this a person is dead or the unit is wrong
    "height_cm": (40, 250),
}
for col, (lo, hi) in rules.items():
    bad = patients[(patients[col] < lo) | (patients[col] > hi)]
    print(f"{col:9} outside [{lo}, {hi}]: rows {bad.index.tolist()} values {bad[col].tolist()}")
age       outside [0, 110]: rows [2] values [230]
temp_c    outside [30, 45]: rows [3, 6] values [3.71, 98.6]
height_cm outside [40, 250]: rows [4] values [1.75]

Each flagged value has a likely story: 230 is a typo for 23, 3.71 lost a decimal point (37.1), 98.6 is Fahrenheit, 1.75 is metres. Statistical methods would find some of these, but the rules find them with certainty and explain them. Write such rules down with the data dictionary.

The z-score and its weakness

For values without hard limits, a classic rule flags values far from the mean in units of the standard deviation:

zi=xi−xˉs,flag if ∣zi∣>3z_i = \frac{x_i - \bar{x}}{s}, \qquad \text{flag if } \lvert z_i \rvert > 3

For normally distributed data, only about 0.3% of values have ∣z∣>3\lvert z \rvert > 3. The weakness: the mean and ss are themselves pulled by the outliers they are meant to detect. One huge value inflates ss so much that other outliers no longer look extreme, an effect called masking.

Robust versions replace the mean by the median and ss by the median absolute deviation MAD=median⁡(∣xi−median⁡(x)∣)\text{MAD} = \operatorname{median}(\lvert x_i - \operatorname{median}(x) \rvert):

zirobust=0.6745 (xi−median⁡(x))MAD,flag if ∣zirobust∣>3.5z_i^{\text{robust}} = \frac{0.6745\,(x_i - \operatorname{median}(x))}{\text{MAD}}, \qquad \text{flag if } \lvert z_i^{\text{robust}} \rvert > 3.5

The factor 0.6745 makes it comparable with the ordinary z-score for normal data; the threshold 3.5 is a common recommendation (Iglewicz and Hoaglin). Another robust rule is Tukey's fences: flag values below q0.25−1.5 IQRq_{0.25} - 1.5\,\text{IQR} or above q0.75+1.5 IQRq_{0.75} + 1.5\,\text{IQR}, the same rule a box plot uses to draw its points.

From scratch with NumPy

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
x = np.round(rng.normal(50, 5, 40), 1)
x[[5, 17]] = [75.0, 78.0]          # two moderate outliers
x[30] = 900.0                      # one gross error (an extra digit)

z = (x - x.mean()) / x.std(ddof=1)
med = np.median(x)
mad = np.median(np.abs(x - med))
rz = 0.6745 * (x - med) / mad
q1, q3 = np.quantile(x, [0.25, 0.75])
iqr = q3 - q1
lo, hi = q1 - 1.5 * iqr, q3 + 1.5 * iqr

print(f"mean {x.mean():.1f}, std {x.std(ddof=1):.1f} | median {med:.1f}, MAD {mad:.2f}")
print("z-score > 3:        ", sorted(x[np.abs(z) > 3].tolist()))
print("robust z > 3.5:     ", sorted(x[np.abs(rz) > 3.5].tolist()))
print(f"Tukey [{lo:.1f}, {hi:.1f}]:", sorted(x[(x < lo) | (x > hi)].tolist()))
mean 72.4, std 134.4 | median 50.4, MAD 3.25
z-score > 3:         [900.0]
robust z > 3.5:      [75.0, 78.0, 900.0]
Tukey [37.9, 62.6]: [75.0, 78.0, 900.0]

The gross error 900 inflates the standard deviation to 134.4, so the ordinary z-score flags only 900 itself: the values 75 and 78 have z-scores close to 0. That is masking. The robust z-score and Tukey's fences flag all three, because the median (50.4) and the MAD (3.25) barely notice the 900.

Outliers in several dimensions

Some samples are unremarkable in every single column and still odd as a combination: a height of 150 cm and a weight of 110 kg are each common, together rare. Multivariate methods look at whole feature vectors. Isolation Forest builds random trees that split the data with random cuts; points that get isolated after only a few cuts are anomalies. In scikit-learn:

python · try it yourself
import numpy as np
from sklearn.ensemble import IsolationForest

rng = np.random.default_rng(0)
height = rng.normal(170, 8, 300)
weight = 0.9 * (height - 170) + 68 + rng.normal(0, 6, 300)
X = np.column_stack([height, weight])
X = np.vstack([X, [[150, 110], [195, 52]]])          # two odd combinations

forest = IsolationForest(contamination=0.01, random_state=0).fit(X)
flags = forest.predict(X) == -1                       # -1 = anomaly
print("flagged:", int(flags.sum()), "of", len(X))
for h, w in X[flags]:
    print(f"  height {h:5.1f} cm, weight {w:5.1f} kg")
print(f"height range {X[:, 0].min():.0f}-{X[:, 0].max():.0f}, weight range {X[:, 1].min():.0f}-{X[:, 1].max():.0f}")
flagged: 4 of 302
  height 154.5 cm, weight  30.7 kg
  height 145.1 cm, weight  38.8 kg
  height 150.0 cm, weight 110.0 kg
  height 195.0 cm, weight  52.0 kg
height range 145-195, weight range 31-110

contamination=0.01 tells the forest to flag about 1% of the samples. It flagged both planted combinations, and also two generated people at the edge of the cloud who are short and very light. A detector ranks the most unusual points, planted or not; whether each one is an error is still a human decision. Isolation Forest returns to the track in Classical ML Algorithms as an anomaly detection model in its own right.

Outliers within groups

An outlier is relative to a group. A salary of 9,000 a month is normal for a senior engineer and extreme for an intern; a 30 °C day is normal in July in Hanoi and impossible in January in Oslo. Computing robust z-scores per group finds values that the whole-column check misses:

python · try it yourself
import pandas as pd

pay = pd.DataFrame({
    "role":   ["intern"] * 6 + ["engineer"] * 6,
    "salary": [900, 950, 1000, 980, 1020, 6500, 6000, 6400, 5900, 6200, 6100, 6300],
})

def robust_z(s):
    med = s.median()
    mad = (s - med).abs().median()
    return 0.6745 * (s - med) / mad

pay["z_all"] = robust_z(pay["salary"]).round(1)
pay["z_role"] = pay.groupby("role")["salary"].transform(robust_z).round(1)
print(pay[(pay["z_all"].abs() > 3.5) | (pay["z_role"].abs() > 3.5)])
print("flagged across all roles:", int((pay["z_all"].abs() > 3.5).sum()))
     role  salary  z_all  z_role
0  intern     900   -6.8    -1.7
1  intern     950   -6.7    -0.8
2  intern    1000   -6.7     0.2
3  intern     980   -6.7    -0.2
4  intern    1020   -6.7     0.6
5  intern    6500    0.7   106.2
flagged across all roles: 5

Across all roles, the robust z-score flags the five ordinary interns (the column mixes two very different groups, so its median lies between them) and misses the one real problem. Within each role, only the intern paid 6,500 stands out, with a robust z-score of 106.2: probably a data entry error, or an engineer recorded with the wrong role.

What to do with an outlier

Finding Action
impossible value with a clear cause (unit, typo) fix it at the source if you can; otherwise correct it in the cleaning code, with a comment
impossible value, unknown cause set it to missing and treat it as such
real but extreme value keep it; consider robust models, a log transform, or capping (in Data Preparation)
the outliers are the target (fraud, faults) keep them all; this is an anomaly detection or imbalanced problem

Never silently drop outliers from the test set to make scores look better: the model will meet them in real use.

Pitfalls

  • Masking: a gross error inflates the standard deviation and hides other outliers. Use robust statistics.
  • Skewed data: on incomes or prices, symmetric rules flag much of the long tail. Look at a log scale or use quantiles.
  • Removing rare but real cases: the rare cases are often the ones that matter most.
  • Fitting on everything: thresholds and detectors used in a pipeline must be fitted on the training data.

Practice

  1. A heart-rate column contains 0 in 2% of rows and 300 in 0.1%. What are the likely causes, and how would you handle each?
Answer

0 is almost certainly "no reading" (sensor off or not attached): treat it as missing. 300 is above what a human heart produces for long; likely a sensor artefact (movement, poor contact): set to missing, or check the raw signal if available.

  1. For the data 10,11,12,12,13,14,4010, 11, 12, 12, 13, 14, 40, compute Tukey's fences with q0.25=11.5q_{0.25} = 11.5 and q0.75=13.5q_{0.75} = 13.5. Which values are flagged?
Answer

IQR=2\text{IQR} = 2, so the fences are 11.5−3=8.511.5 - 3 = 8.5 and 13.5+3=16.513.5 + 3 = 16.5. Only 40 lies outside them.

Test yourself

A single value of 900 among values around 50 makes the z-score miss two values of 75 and 78. This is called…

  1. Overfitting
  2. Masking
  3. Leakage
  4. Imputation

Which statistics does the robust z-score use?

  1. Mean and standard deviation
  2. Median and median absolute deviation
  3. Minimum and maximum
  4. Mode and range

A body temperature column contains 98.6 among values near 37. The best action is…

  1. Delete the row
  2. Recognise it as Fahrenheit and convert it to 37.0 °C, documenting the fix
  3. Keep it as is
  4. Replace it with the mean

When should outliers definitely be kept?

  1. Never
  2. When they are real rare cases the model must handle, such as fraud
  3. Only in the test set
  4. Only if there are fewer than ten