Min-max scaling and z-score normalization
Overview
Feature scaling transforms numerical features to a common scale without distorting differences in ranges. Two fundamental methods are min-max scaling (range-based) and z-score normalization (distribution-based). Both solve the same problem: preventing features with larger magnitudes from dominating distance-based algorithms and gradient descent.

Why Feature Scaling Matters
When you MUST scale:
- Gradient descent optimization (neural networks, linear/logistic regression)
- Distance-based algorithms (k-NN, k-means, SVM with RBF kernel)
- PCA and dimensionality reduction
- Regularization (L1/L2) — unscaled features get unfairly penalized
When you DON'T scale:
- Tree-based models (decision trees, random forests, XGBoost) — they split on relative thresholds
- Naive Bayes — works with probabilities, not distances
Min-max Scaling (Normalization)
Derivation from first principles:
We want a linear transformation that maps:
From the first condition:
From the second condition:
Solving for :
Substituting back:
Therefore:
WHY this formula? The numerator shifts the range to start at 0. The denominator is the original range, so dividing by it compresses everything into [0, 1].
Derivation: Map to [0, 1] first, then stretch by and shift by .
Step 1: Find range
- ,
- Range
Step 2: Apply formula to each value
- :
- : — Why this step? 25 is 1/4 of the way between 20 and 40
- : — Why? Exactly midpoint
- :
- :
Result: [0, 0.25, 0.5, 0.75, 1.0]
Step 1: Apply generalized formula with ,
Step 2: Calculate
- :
- : — Why? Middle value maps to middle of range
- :
Result: [-1.0, 0.0, 1.0]
Properties of Min-max Scaling
Advantages:
- Preserves original distribution shape (just rescaled)
- Bounded output — useful for algorithms expecting specific ranges (e.g., neural networks with sigmoid)
- All features contribute equally to distance calculations
- Interpretable: 0.5 means "halfway between min and max"
Disadvantages:
- Sensitive to outliers — a single extreme value drastically changes or
- New test data outside training range produces values outside [0, 1]
- Not suitable when new data might have different range
Why it feels right: Each dataset gets scaled to [0, 1], seems consistent.
Why it's wrong: The same original value maps to different scaled values in train vs test. A value of 50 might become 0.5 in training but 0.7 in testing if the test set has a smaller range. The model learned decision boundaries based on training scale, now they're misaligned.
Fix: Fit scaler on training data only, apply same transformation to test:
scaler.fit(train) # Learn min and max from training
train_scaled = scaler.transform(train)
test_scaled = scaler.transform(test) # Use training min/maxZ-score Normalization (Standardization)
Derivation from first principles:
We want transformation such that:
- (mean is zero)
- (standard deviation is 1)
Step 1: Mean condition
Step 2: Variance condition
We choose (positive to preserve order).
Step 3: Combine
WHY this formula? centers the distribution at 0. Dividing by makes the spread exactly 1 standard deviation.
This converts absolute values to relative positions in the distribution.
Step 1: Calculate statistics
- Mean:
- Variance:
- Standard deviation:
Step 2: Apply formula
- : — Why? 60 is 1.41 std devs below average
- :
- : — Why? At the mean
- :
- :
Result: [-1.41, -0.71, 0, 0.71, 1.41]
Verification: Mean of z-scores = 0, std dev = 1 ✓
Min-max scaling:
- ,
- Range
- :
- : — Why? All normal salaries squished near 0
- : (the outlier)
Notice: The four normal salaries all fall in [0, 0.088] — completely compressed by the outlier.
Z-score normalization:
- Mean:
- Variance:
- Standard deviation:
Why z-score is better here? The outlier gets a large z-score (≈2.0) but the normal salaries still spread across roughly rather than being crushed into a tiny sliver near 0. However: z-score is still affected by outliers because they inflate both and — for extreme cases, use robust scaling (median and IQR).
Properties of Z-score Normalization
Advantages:
- Less sensitive to outliers than min-max (but not immune)
- No bounded range — handles new data with any values
- Creates comparable scales when features have different units
- Works well with normally distributed data
- Required for algorithms assuming standardized inputs (PCA, LDA)
Disadvantages:
- Output not bounded (unlike [0,1])
- Harder to interpret (what does z=-0.73 mean intuitively?)
- Assumes somewhat bell-shaped distribution
- Breaks down with extreme outliers
Why it feels right: Z-score is "standardization," sounds universally applicable.
Why it's problematic: Z-score assumes distribution shape is roughly preserved. With skew, most z-scores cluster one side, and the "1 standard deviation" interpretation becomes misleading. The mean is pulled by outliers.
Fix: Use robust scaling with median and IQR: Or apply log transformation first to reduce skew, then z-score.
When to Use Which Method
| Criterion | Min-max Scaling | Z-score Normalization |
|---|---|---|
| Data distribution | Any | Normal or near-normal preferred |
| Outliers present | Avoid (sensitive) | Better but not perfect |
| Need bounded output | Yes [0,1] or [a,b] | No (unbounded) |
| Neural networks | Good (bounded for activations) | Good (standardized gradients) |
| k-NN, k-means | Good | Good |
| PCA | Acceptable | Preferred (PCA assumes centered data) |
| Test has new extremes | Problematic | Handles better |
| Interpretability | High (percentage of range) | Medium (std devs from mean) |
Implementation Considerations
Fitting and Transforming
ALWAYS fit on training data only:
from sklearn.preprocessing import MinMaxScaler, StandardScaler
# Min-max
scaler_minmax = MinMaxScaler()
scaler_minmax.fit(X_train) # Learn min and max
X_train_scaled = scaler_minmax.transform(X_train)
X_test_scaled = scaler_minmax.transform(X_test)
# Z-score
scaler_std = StandardScaler()
scaler_std.fit(X_train) # Learn mean and std
X_train_scaled = scaler_std.transform(X_train)
X_test_scaled = scaler_std.transform(X_test)Why fit only on training? Prevents data leakage. The test set represents "unseen future data" — using its statistics leaks information about test distribution into your model.
Feature-wise vs Global Scaling
Feature-wise (standard): Each column scaled independently
- Use when features have different units/meanings
- Preserves feature relationships within their own scale
Global (rare): All features scaled using same min/max or mean/std
- Only if features represent same quantity (e.g., pixel intensities)
Inverse Transformations
Both methods are reversible:
Min-max inverse:
Z-score inverse:
Use case: Convert predictions back to original scale for interpretation.
Recall
Explain to a 12-year-old Imagine you and your friend are comparing savings. You have saved ₹500 over 5 weeks. Your friend saved $10 over 5 weeks. Now you want to know who's better at saving, but you can't compare directly because of different currencies!
Min-max scaling is like saying "What percentage of your total did you save each week?" You both convert your money to percentages from 0% to 100%. Now you can compare!
Z-score is like asking "How far above or below your average week was each week?" If your average is ₹100/week, and one week you saved ₹150, you're +50 above average. If your friend's average is 3 one week, they're +1 above their average. Z-score tells you "how many 'typical amounts' above or below average you are" so you can compare even with different currencies.
Both methods turn "apples and oranges" into the same unit so you can fairly compare them!
Connections
- 2.1.01-Data-cleaning-techniques — scaling applied after handling missing values and outliers
- 2.1.04-One-hot-and-label-encoding — categorical encoding happens before scaling
- 2.2.01-Feature-selection-methods — scaling required before correlation-based selection
- 3.1.02-Gradient-descent-optimization — scaling dramatically speeds convergence
- 4.1.05-Principal-component-analysis — PCA requires centered/standardized data
- 5.3.02-Batch-normalization — neural network layer-wise standardization during training
- 2.1.06-Robust-scaling-and-power-transforms — advanced scaling for outliers and skewed distributions
#flashcards/ai-ml
What is feature scaling and why is it necessary? :: Feature scaling transforms numerical features to a common scale. It's necessary because features with larger magnitudes dominate distance calculations and gradient descent, causing algorithms to overweight them unfairly.
What is the min-max scaling formula and what does each component do?
What is the z-score normalization formula and what does it represent?
When should you use min-max scaling vs z-score normalization?
Why must you fit scalers only on training data?
What happens if you apply min-max scaling with an extreme outlier?
How do you invert a min-max scaled value back to original scale?
What is the key mistake when scaling train and test sets?
What algorithms require feature scaling?
What algorithms do NOT need feature scaling?
Concept Map
Hinglish (regional understanding)
Intuition Hinglish mein samjho
Hinglish (regional understanding)
Intuition Hinglish mein samjho
Dekho, ye feature scaling ka concept samajhna bahut zaroori hai kyunki real-world data mein har feature ka scale alag hota hai. Socho tum house price predict kar rahe ho — area 500 se 5000 square feet tak jaata hai, aur bedrooms sirf 1 se 5 tak. Ab jab model in dono ko compare karega, toh area ka number itna bada hai ki wo automatically dominate kar dega, chahe importance ke hisaab se bedrooms utne hi matter karte hon. Toh scaling ka core idea yehi hai — sab features ko ek common scale pe le aao taaki koi feature sirf apne bade numbers ki wajah se boss na ban jaaye.
Ab do main tareeke hain. Min-max scaling feature ko ek fixed range mein daal deta hai, usually 0 se 1. Formula simple hai: value se minimum minus karo, phir puri range (max minus min) se divide kar do. Iska matlab minimum wali value 0 ban jaati hai, maximum wali 1, aur baaki sab beech mein proportionally aa jaate hain. Jaise ages [20,25,30,35,40] scale hokar [0, 0.25, 0.5, 0.75, 1.0] ban gaye — dekho 30 exactly middle tha toh 0.5 pe aa gaya. Zaroorat pade toh tum isse -1 se 1 jaise kisi bhi range mein bhi map kar sakte ho generalized formula se.
Ye kyun important hai? Kyunki jo algorithms distance ya gradient descent pe kaam karte hain — jaise k-NN, k-means, neural networks, logistic regression, PCA — un sab mein scaling nahi karoge toh results galat aa jaayenge. Lekin ek cheez yaad rakhna: tree-based models jaise decision trees, random forest ya XGBoost ko scaling ki zaroorat nahi, kyunki wo relative thresholds pe split karte hain, magnitude se farak nahi padta. Toh scaling ek tool hai jo tumhe soch-samajh ke, algorithm ke hisaab se lagana hai — har jagah blindly nahi.