Scale features with the median and IQR so outliers do not dominate

One huge outlier, like a single 10-hour request latency in your logs, wrecks mean and standard deviation scaling. Robust scaling uses the median and the interquartile range (IQR), which barely move.

Write robust_scale(X) for a 2D float array of shape (n, p). For each column return (x - median) / IQR, where IQR = 75th percentile minus 25th percentile, both from np.percentile with default linear interpolation. If a column's IQR is 0, divide by 1 instead. Return an array of the same shape.

Signaturedef robust_scale(X)

Example

the column [1, 2, 3, 4, 100] has median 3 and IQR 2, so it becomes [-1.0, -0.5, 0.0, 0.5, 48.5].

Understand the idea

Robust scaling centres each column on its median and divides by the interquartile range (75th percentile minus 25th). Both barely move when one value is extreme, unlike mean and standard deviation, which a single outlier can drag. Like describing a typical salary by the middle earner instead of the average that one billionaire inflates. Worked example: column [2, 4, 6, 8, 50]. With linear interpolation the 25th, 50th and 75th percentiles are 4, 6 and 8, so median 6 and IQR 4. Scaled: (2 - 6) / 4 = -1, then -0.5, 0, 0.5, and the outlier (50 - 6) / 4 = 11. The normal points keep a useful spread. With standard deviation scaling, the outlier would inflate the scale and squash the normal points close together. If a column's IQR is 0, divide by 1. Rule: per column, (x - median) / IQR using np.percentile defaults. This is a common preprocessing step for latency logs and financial data.

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

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

  • Sample 1: example columnrobust_scale([[1.0], [2.0], [3.0], [4.0], [100.0]])
  • Sample 2: random with an outlierrobust_scale(_X)
  • Test 3: constant columnrobust_scale([[5.0, 1.0], [5.0, 2.0], [5.0, 3.0]])