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

Technical detail · Feature Scaling Lab: Preprocessing Workflow

Z-score implementation and reversal

The implementation fits the training mean and population standard deviation with NumPy. A constant feature returns 0.0. Otherwise, reversing the transform multiplies by the fitted standard deviation and adds the fitted mean. Save these parameters instead of fitting again on test rows.

class ZScoreNormalizer:
    def __init__(self):
        self.mean = None
        self.std = None

    def fit(self, data):
        """Learn mean and std from training data"""
        import numpy as np
        self.mean = np.mean(data)
        self.std = np.std(data)

    def transform(self, value):
        """Normalize a single value"""
        if self.std == 0:
            return 0.0
        return (value - self.mean) / self.std

    def inverse_transform(self, normalized_value):
        """Convert back to original scale"""
        return normalized_value * self.std + self.mean

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