Flag outliers with the modified z-score based on the median

Why it matters Fraud, latency and sensor monitoring often use median-based scores because a few huge values should not be able to hide themselves.

A plain z-score uses the mean and standard deviation, which the outlier itself inflates. The modified z-score uses the median and the median absolute deviation (MAD) instead.

Write modified_z_outliers(x, thresh=3.5). x is a 1D sequence. Let med be the median and MAD the median of |x - med|. If MAD > 0, z = 0.6745 * (x - med) / MAD. If MAD is 0, fall back to z = (x - med) / (1.253314 * meanAD) where meanAD is the mean of |x - med|. If meanAD is also 0, z is all zeros. Return (z, flags) where z is a float array and flags is a bool array that is True where |z| > thresh.

Signaturedef modified_z_outliers(x, thresh=3.5)

Example

x [10, 11, 12, 11, 10, 50] gives z [-0.6745, 0, 0.6745, 0, -0.6745, 26.3055] and flags [False, False, False, False, False, True].

Understand the idea

An outlier rule should not be fooled by the outlier. The mean and standard deviation move a lot when one crazy value enters, so a big value can make itself look normal. The median and the MAD (median absolute deviation) barely move, so they give a fair yardstick, like judging a class by its middle student instead of its topper.

Worked example: x = 10, 11, 12, 11, 10, 50. The median is 11. Deviations are 1, 0, 1, 0, 1, 39, and their median is 1. So z for 50 is 0.6745 * 39 / 1 = 26.3, clearly above 3.5, while 12 gets only 0.67.

Rule: z = 0.6745 * (x - median) / MAD, flag |z| > 3.5. If MAD is 0, use (x - median) / (1.253314 * mean absolute deviation).

The 0.6745 constant makes z comparable to an ordinary z-score when the data really is normal. This score is a common first step for cleaning metrics and logs.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplemodified_z_outliers([10, 11, 12, 11, 10, 50])
  • Sample 2: mad zeromodified_z_outliers([5, 5, 5, 5, 9])
  • Test 3: all equalmodified_z_outliers([2, 2, 2])
  • Test 4: two sidedmodified_z_outliers([-40, 1, 2, 3, 2, 1, 2, 60], 3.0)