← Back to the chapter · Previous detail · Next detail →

Technical detail · Feature Scaling Lab: Preprocessing Workflow

Robust scaling implementation

Fit the training median and the 25th and 75th percentiles, then divide by their difference. This implementation returns 0.0 when IQR is zero. Its inverse multiplies by the fitted IQR and adds the median.

class RobustScaler:
    def __init__(self):
        self.median = None
        self.iqr = None

    def fit(self, data):
        """Learn median and IQR from training data"""
        import numpy as np
        self.median = np.median(data)
        q1 = np.percentile(data, 25)
        q3 = np.percentile(data, 75)
        self.iqr = q3 - q1

    def transform(self, value):
        """Scale using median and IQR"""
        if self.iqr == 0:
            return 0.0
        return (value - self.median) / self.iqr

    def inverse_transform(self, scaled_value):
        """Convert back to original scale"""
        return scaled_value * self.iqr + self.median

← Back to the chapter · Previous detail · Next detail →