Ir para o conteúdo

Lição 19 · Pitfalls and Checks

Outliers and Anomalies

Detect outliers with IQR fences and robust z-scores, use context to find unusual values, investigate their causes, and decide what to do and report.

An outlier is a value far from most of the others. An anomaly is something that does not fit the expected pattern, even if its size is ordinary. Some are errors. Some are the most valuable facts in the dataset: fraud, a failing machine, a new kind of customer.

A detection rule only flags candidates. It never tells you what to do with them.

Two common rules

The IQR rule marks values below Q1 − 1.5 × IQR or above Q3 + 1.5 × IQR. The 1.5 is a convention, not a law.

The z-score rule marks values many standard deviations from the mean. It has a weakness: extreme values inflate the mean and standard deviation, which can hide them. This is called masking. A robust z-score uses the median and the MAD instead. A common version multiplies the distance from the median by 0.6745 and divides by the MAD, with 3.5 as a suggested cutoff.

Python Three rules on the same data

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The classic z-score finds nothing, because the two large values stretched the standard deviation. The other two rules flag both. If at least half the values are identical, the MAD can be zero and this formula fails, so check for that case.

Skewed data

In a strongly right-skewed distribution, such as order values, many perfectly normal large values can fall outside the IQR fences. Apply rules on a log scale when that matches the data, or use thresholds based on subject knowledge. If a rule flags a large share of your rows, it is probably the wrong rule.

Context matters

A value can be normal overall and strange in context. A temperature of 28 °C may be ordinary in summer and odd in winter. Check values within their group.

Python Flag within each group

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The same value, 95, is unusually high for the kiosk and unusually low for the mall. One rule applied to all the values together cannot see that.

Multivariate and time anomalies

Some rows are strange only as a combination: a height of 190 cm and a weight of 45 kg may each be common, but rare together. Scatter plots can reveal these. Over time, look for spikes, drops, level shifts and flat lines (a sensor stuck on one value). For daily data with a weekly pattern, compare a Saturday with other Saturdays.

Investigate before acting

Why is it unusual?

Error Typing, units, software bug
Other population Test or wholesale account
Real and rare A true extreme event
Unknown Keep it and flag it
1 / 2

Look at the full row, related rows, the source record and the time it happened. Ask the data owner. Unit mix-ups can show up as values off by a factor such as 100 or 1,000.

Options and consequences

Situation Reasonable action
Confirmed error, true value known Correct it and log the change
Confirmed error, true value unknown Mark as missing and log it
Different population (test orders) Exclude with a written rule
Real extreme value Keep it; use robust summaries and show it
Unclear Keep it, flag it and compare results both ways

Capping extremes at a limit (a related method is called winsorizing) changes the data. Use it only for a clear purpose, report it and never overwrite the original.

Sensitivity check

Report how much your conclusion depends on the unusual values.

Python With and without flagged rows

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The mean and total change dramatically; the median barely moves. Both versions belong in your notes, with your reason for the headline figure.

Never remove points just because they weaken your result. Base the rule on the data's meaning, apply it to all groups in the same way and say how many rows it affected.

Keep a record of flags

Rather than deleting rows, add columns such as is_flagged, flag_reason and decision. Your code can then include or exclude flagged rows with one filter, and anyone can review the cases later.

Also record the rule and its settings. "Robust z above 3.5 within each store, computed on March data" can be repeated. "Removed the weird ones" cannot. When new data arrives, recheck the rule, because thresholds that worked for one season may flag normal values in the next.

Try it yourself

In the first example, add a third large value, then a fourth. Watch which rules still flag them. At what point would you stop calling the large values outliers and start asking whether there are two groups?

Prevent the next one

If an investigation finds an error, ask how it got in. A form that accepts any number, an import that mixes units or a retry that saves the same record twice can all be fixed at the source. Pass the finding to the system's owner with an example record, after removing personal details that they do not need. Until the fix is live, keep your rule in the analysis and count how often it fires. A sudden increase tells you that something changed.

A common mistake

Do not apply an outlier rule again and again until nothing is flagged. Each round changes the quartiles or median, so new values can fall outside, and you may slowly trim away real variation. Apply a planned rule once, then investigate.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Why can the ordinary z-score miss large outliers?

    This masking makes extreme values look less extreme.
  2. 2. What does a detection rule give you?

    Only investigation can show what a flagged value is.
  3. 3. Why flag values within groups?

    Context such as store, season or weekday changes what is typical.
  4. 4. An extreme value is real. What is a sound approach?

    Real values are part of the story; make their influence visible.

Summary

  • Outlier rules flag candidates; they do not decide what is wrong.
  • Robust rules resist masking better than plain z-scores.
  • Check unusual values within groups, combinations and time patterns.
  • Investigate causes, log every change and keep originals.
  • Show how conclusions change with and without flagged rows.

Next: Common EDA Pitfalls

Seu progresso fica salvo neste navegador. Não precisa de conta.