Lesson 2 of 5 Data Quality, Cleaning and Labeling

Detecting and Handling Outliers

This lesson explains statistical and model-based methods for detecting outliers and the judgement of what to do next, since some outliers are errors to fix and others are rare but real events a model must learn.

Learning outcomes

After completing this lesson, you will be able to:

  • Detect outliers with z-scores and the IQR rule.
  • Detect multivariate outliers with models such as Random Cut Forest.
  • Decide whether to correct, cap, remove or keep an outlier.

Statistical detection

Outliers are values far from the rest of the data, and they can distort training, especially for models sensitive to large values such as linear regression. The z-score method flags values more than a chosen number of standard deviations from the mean, commonly 3. It assumes a roughly normal distribution, and the mean and standard deviation are themselves pulled by the extreme values it is trying to detect.

The interquartile range (IQR) method flags values below Q1 minus 1.5 times the IQR or above Q3 plus 1.5 times the IQR, where Q1 and Q3 are the 25th and 75th percentiles. Because quartiles are not affected by extreme values, it works well on skewed data such as incomes or transaction amounts. During exploration, box plots and histograms show outliers visually. Detected outliers are then removed, capped at a threshold or kept, depending on whether they are errors or genuine rare events.

The following diagram shows the interquartile range method on one feature.

The interquartile range method on transaction amounts. Q1 and Q3 are the 25th and 75th percentiles, and values below Q1 − 1.5 × IQR or above Q3 + 1.5 × IQR are flagged. Because quartiles are not pulled by extreme values, the method works on skewed data where a z-score threshold would be distorted.
The values are illustrative.
Fill in the value

IQR fences

Exam skills 1.3.7

Calculate the interquartile range (IQR) fences used to flag outliers.

Log in to try this activity Interactive activities are free with an account.

Model-based detection

Some outliers are unusual only in combination: a normal payment amount, at an unusual hour, from an unusual country. Rules applied to one feature at a time miss them. Model-based methods consider all features together. The SageMaker AI Random Cut Forest (RCF) algorithm assigns an anomaly score to each record in multidimensional data, and it also works on streams, scoring records as they arrive.

Isolation Forest, available in scikit-learn, works on a similar principle: anomalies are easier to isolate with random splits than normal points. For streaming data, Amazon Managed Service for Apache Flink also provides an RCF function, so anomalies can be flagged in real time before data is stored.

Deciding what to do

The treatment depends on the cause. Errors such as negative ages or sensor glitches are corrected or removed. Extreme but valid values can be capped (winsorised) at a percentile, log-transformed or handled by robust models such as trees. Outliers that are the target, such as fraudulent transactions or equipment failures, must be kept, because removing them removes what the model must detect. The following table summarises the options.

SituationTreatment
Impossible or erroneous valueCorrect, set to missing and impute, or drop the row
Valid but extreme value hurting a linear modelCap at a percentile or log-transform
Outliers are the events to predictKeep them; consider anomaly detection models
Multivariate unusual recordsRandom Cut Forest anomaly scores

The following diagram matches three kinds of extreme reading from a vibration sensor to the treatment each needs.

Three kinds of extreme vibration reading need three treatments. Readings of 0 mean the sensor was disconnected and readings of 9,999 are an error code, so both are set to missing. Readings of 85 to 120 are genuine spikes just before motor failures, so they are kept, because they are the signal the model must learn.
Domain knowledge decides which outliers are noise.
Sort into groups

Remove, cap or keep?

Exam skills 1.3.7

Decide what to do with each unusual value.

Log in to try this activity Interactive activities are free with an account.
Worked example

Sensor data

A predictive maintenance dataset of vibration readings contains values of 0 (sensor disconnected), values of 9,999 (an error code) and a small number of very high but genuine readings recorded just before motor failures.

Value       Cause                       Action
0           Sensor disconnected         Set to missing; impute or flag
9,999       Error code                  Set to missing
85-120      Genuine pre-failure spikes  Keep: this is the signal to learn

Applying a blanket z-score filter would have removed the genuine spikes along with the error codes, leaving a model that never sees what precedes a failure. Domain knowledge decides which outliers are noise.

Check yourself

When must outliers not be removed?

Show answer

When they are what the model must find, such as fraud.

Exam Tips

Remember for the exam

  • Skewed data: IQR method rather than z-scores.
  • Multidimensional anomalies: Random Cut Forest.
  • Never remove outliers that are the target, such as fraud.
  • Cap or log-transform valid extremes for linear models.
  • Error codes and impossible values should become missing values.