Cap outliers with IQR fences learned from training data

Why it matters Salary, transaction and latency features have heavy tails, and train-fitted IQR caps are a standard robust step before linear models.

Capping (winsorizing) keeps extreme values from dominating a model without deleting rows.

Write iqr_cap(train, test, k=1.5). train and test are 1D sequences. Compute Q1 and Q3 of train with np.percentile (default linear interpolation), IQR = Q3 - Q1, low = Q1 - k * IQR and high = Q3 + k * IQR. Return (capped, low, high) where capped is test clipped into [low, high] as a float array, and low and high are floats.

Signaturedef iqr_cap(train, test, k=1.5)

Example

train [1, 2, 3, 4, 5, 6, 7, 8], test [-10, 4, 30] gives ([-2.5, 4.0, 11.5], -2.5, 11.5).

Understand the idea

The interquartile range (IQR) is the width of the middle half of the data. Values far outside that middle band are treated as outliers and pulled back to a fence, like a cricket boundary rope that stops the ball from rolling forever.

Worked example: train values 1 to 8. With linear interpolation Q1 = 2.75 and Q3 = 6.25, so IQR = 3.5. With k = 1.5 the fences are 2.75 - 5.25 = -2.5 and 6.25 + 5.25 = 11.5. Test value -10 becomes -2.5, 4 stays 4, and 30 becomes 11.5.

Rule: low = Q1 - k * IQR, high = Q3 + k * IQR, x_capped = min(max(x, low), high).

Unlike a z-score rule, quartiles are barely affected by the outliers themselves, so the fences stay stable. Learn the fences once on training data and reuse them in production so every request is treated the same way.

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

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

  • Sample 1: exampleiqr_cap([1, 2, 3, 4, 5, 6, 7, 8], [-10, 4, 30])
  • Sample 2: k 3iqr_cap([10, 12, 11, 13, 12, 50], [0, 12, 100], 3.0)
  • Test 3: randomiqr_cap(_tr, _te)
  • Test 4: constant trainiqr_cap([5, 5, 5, 5], [4, 5, 6])