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.
def 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.