30 Mins

3. Numerical Scaling & Normalization

Standardization (StandardScaler) vs Min-Max Normalization (MinMaxScaler)

Machine learning algorithms are highly sensitive to the scale of input features. When features have vastly different ranges—for instance, age ranging from 0 to 100 and annual income ranging from $10,000 to $1,000,000—models that compute mathematical distances (such as K-Nearest Neighbors, Support Vector Machines) or use gradient descent optimization (such as Linear Regression or Neural Networks) will perform poorly. The model will erroneously assume that features with larger numerical magnitudes are more important than features with smaller ranges.

To resolve this imbalance, we use Scaling and Normalization. The two most common techniques are Standardization (StandardScaler) and Min-Max Normalization (MinMaxScaler). Standardization shifts the mean of your feature to 0 and scales its variance to 1. The formula is: $z = \frac{x - \mu}{\sigma}$. This technique does not bound your features to a specific range, which is critical for algorithms that assume normally distributed data (such as linear algorithms).

Min-Max Normalization scales the data to a fixed, bounded range, typically between 0 and 1. The formula is: $x_{scaled} = \frac{x - x_{min}}{x_{max} - x_{min}}$. This is highly useful when you need absolute boundaries, or when your model does not make statistical assumptions about data distribution, such as deep neural networks working with image pixel values.

Below is a comparison table outlining when to use each technique:

FeatureStandardScalerMinMaxScaler
Mathematical Formula(x - mean) / std(x - min) / (max - min)
Output RangeUnbounded (typically -3 to 3)Bounded strictly between [0, 1]
AssumptionAssumes normal distributionNo distribution assumptions
Sensitivity to OutliersHighly affectedExtremely affected
Operator Note: Always choose StandardScaler as your default baseline scaling method unless you have a specific reason (such as neural network input constraints) to use MinMaxScaler.
Python 3
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler, MinMaxScaler

# Create a mock dataset representing Age and Income
data = {
    'Age': [25, 30, 45, 50, 22],
    'Income': [40000, 50000, 80000, 95000, 35000]
}
df = pd.DataFrame(data)

# Initialize scale transforms
min_max_scaler = MinMaxScaler()
standard_scaler = StandardScaler()

# Fit and transform the dataframe
scaled_minmax = min_max_scaler.fit_transform(df)
scaled_std = standard_scaler.fit_transform(df)

print("Original Data:\n", df)
print("\nMinMax Scaled (Range [0, 1]):\n", pd.DataFrame(scaled_minmax, columns=df.columns))
print("\nStandardized (Mean=0, Std=1):\n", pd.DataFrame(scaled_std, columns=df.columns))

Handling features with significant outliers using RobustScaler

Both StandardScaler and MinMaxScaler suffer from a critical vulnerability: they are highly sensitive to extreme outliers. For instance, if you apply MinMaxScaler to an income column where 99% of people earn around $50,000, but a single individual earns $10,000,000, MinMaxScaler will compress almost all the normal data into a tiny range near 0 (e.g., between 0.000 and 0.005). Similarly, StandardScaler will compute a highly distorted mean and standard deviation, pulling the normalized normal values away from a zero center.

RobustScaler solves this problem by using statistical metrics that are resistant to outliers. Instead of using the mean and standard deviation, RobustScaler utilizes the median and the Interquartile Range (IQR).

The formula used by RobustScaler is: x_scaled = (x - median) / IQR, where IQR is the difference between the 75th percentile (Q3) and the 25th percentile (Q1). Because the median and IQR disregard the extreme tail ends of distributions, the resulting scale is completely unaffected by outliers. While outliers are still scaled, they remain separated and do not compress the distribution of the rest of the dataset.

Operator Note: If your feature distributions have long tails or massive anomaly spikes that cannot be safely dropped, use RobustScaler to ensure your model can still learn from the variance in normal data.
Python 3
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler, RobustScaler

# Dataset with a severe income outlier (10 million)
data = {'Salary': [45000, 50000, 55000, 60000, 10000000]}
df = pd.DataFrame(data)

min_max = MinMaxScaler()
robust = RobustScaler()

df['MinMax_Scaled'] = min_max.fit_transform(df[['Salary']])
df['Robust_Scaled'] = robust.fit_transform(df[['Salary']])

print("Comparison of Scalers with Outlier:\n")
print(df)

Fit vs transform lifecycle: scaling features without leaking test set properties

One of the most catastrophic errors in feature engineering is Data Leakage. Data leakage occurs when training data is inadvertently mixed with information from the evaluation/testing set. This leads to overly optimistic performance evaluation during validation, but terrible accuracy when deployed in production.

When scaling numerical data, you must apply the identical scale transformation to both your training set and your testing set. However, you must compute the scaling parameters (like mean, standard deviation, minimum, maximum, or median) ONLY on the training dataset.

To achieve this, we use the two phases of the Scikit-Learn scaling lifecycle: 'fit()' and 'transform()'. The fit method calculates the parameters (e.g., the mean and variance of the training set) and stores them inside the scaler object. The transform method applies these pre-computed parameters to execute the math.

You must run '.fit_transform()' on your training data to learn and apply parameters. Then, you must run ONLY '.transform()' on your validation and testing data. Never call fit or fit_transform on your testing set, or you will leak the test distribution's statistical properties into your training environment.

Operator Note: Think of fit as learning rules, and transform as applying rules. You should only ever learn rules from your training split.
Python 3
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

# Create a mock dataframe
np.random.seed(42)
X = pd.DataFrame({'Feature_1': np.random.rand(10) * 100})

# Split into Train and Test
X_train, X_test = train_test_split(X, test_size=0.3, random_state=42)

scaler = StandardScaler()

# Correct: Fit and transform training set
X_train_scaled = scaler.fit_transform(X_train)

# Correct: ONLY transform test set (No fit! uses training mean and std)
X_test_scaled = scaler.transform(X_test)

print("Scaler Mean (Learned strictly from Train set):", scaler.mean_[0])
print("\nScaled Train (Mean = 0):\n", X_train_scaled)
print("\nScaled Test (Transformed via train parameters):\n", X_test_scaled)

Evaluating scaling outputs on models sensitive to features magnitude

Not all machine learning models require features to be scaled. For example, Tree-based algorithms (such as Decision Trees, Random Forests, and Gradient Boosting Models) make split decisions based on single features at a time. Therefore, scaling features has absolutely zero impact on their performance or final decisions.

However, models that compute geometric distance or rely on gradient-descent optimization are highly sensitive to feature magnitudes. These include K-Nearest Neighbors (KNN), Support Vector Machines (SVM), Principal Component Analysis (PCA), Linear Regression (with regularization like Lasso or Ridge), and Neural Networks.

Let us evaluate the impact of scaling on a distance-sensitive model like KNN. Without scaling, a feature like 'Annual Income' (varying by thousands) will dominate Age (varying by tens) during distance calculation. This essentially renders Age useless. Scaling places both features on equal footing, allowing the model to find true mathematical neighbors.

Operator Note: When using distance-based algorithms, regularization penalties (L1/L2), or gradient-descent optimized architectures, scaling is a mandatory preprocessing step, not an optional optimization.
Python 3
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import MinMaxScaler

# Features: [Age (years), Annual Income (USD)]
X_train = np.array([[22, 120000], [24, 115000], [50, 40000], [48, 42000]])
y_train = np.array([0, 0, 1, 1]) # Class 0: Tech, Class 1: Retiree

# Unscaled model
knn_unscaled = KNeighborsClassifier(n_neighbors=1)
knn_unscaled.fit(X_train, y_train)

# Scaled model
scaler = MinMaxScaler()
X_train_scaled = scaler.fit_transform(X_train)
knn_scaled = KNeighborsClassifier(n_neighbors=1)
knn_scaled.fit(X_train_scaled, y_train)

# Predict for a person: Age 45, Income 43000 (Should be Class 1: Retiree)
test_point = np.array([[45, 43000]])
test_point_scaled = scaler.transform(test_point)

print("Unscaled Prediction (distorted by high income magnitude):", knn_unscaled.predict(test_point))
print("Scaled Prediction (correctly considers both age and income):", knn_scaled.predict(test_point_scaled))

Knowledge Check

Ready to test your understanding of 3. Numerical Scaling & Normalization?

Back