2.1.5Data Preprocessing & Feature Engineering

Min-max scaling and z-score normalization

2,965 words13 min readdifficulty · medium

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.

Figure — Min-max scaling and z-score normalization

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)

xscaled=xxminxmaxxminx_{\text{scaled}} = \frac{x - x_{\text{min}}}{x_{\text{max}} - x_{\text{min}}}

Derivation from first principles:

We want a linear transformation xscaled=ax+bx_{\text{scaled}} = ax + b that maps:

  • xmin0x_{\text{min}} \rightarrow 0
  • xmax1x_{\text{max}} \rightarrow 1

From the first condition: 0=axmin+b    b=axmin0 = a \cdot x_{\text{min}} + b \implies b = -a \cdot x_{\text{min}}

From the second condition: 1=axmax+b=axmaxaxmin1 = a \cdot x_{\text{max}} + b = a \cdot x_{\text{max}} - a \cdot x_{\text{min}}

Solving for aa: 1=a(xmaxxmin)    a=1xmaxxmin1 = a(x_{\text{max}} - x_{\text{min}}) \implies a = \frac{1}{x_{\text{max}} - x_{\text{min}}}

Substituting back: b=xminxmaxxminb = -\frac{x_{\text{min}}}{x_{\text{max}} - x_{\text{min}}}

Therefore: xscaled=1xmaxxminxxminxmaxxmin=xxminxmaxxminx_{\text{scaled}} = \frac{1}{x_{\text{max}} - x_{\text{min}}} \cdot x - \frac{x_{\text{min}}}{x_{\text{max}} - x_{\text{min}}} = \frac{x - x_{\text{min}}}{x_{\text{max}} - x_{\text{min}}}

WHY this formula? The numerator (xxmin)(x - x_{\text{min}}) shifts the range to start at 0. The denominator (xmaxxmin)(x_{\text{max}} - x_{\text{min}}) is the original range, so dividing by it compresses everything into [0, 1].

Derivation: Map to [0, 1] first, then stretch by (ba)(b-a) and shift by aa.

Step 1: Find range

  • xmin=20x_{\text{min}} = 20, xmax=40x_{\text{max}} = 40
  • Range 4020=2040 - 20 = 20

Step 2: Apply formula to each value

  • x=20x = 20: 202020=0.00\frac{20-20}{20} = 0.00
  • x=25x = 25: 252020=0.25\frac{25-20}{20} = 0.25Why this step? 25 is 1/4 of the way between 20 and 40
  • x=30x = 30: 302020=0.50\frac{30-20}{20} = 0.50Why? Exactly midpoint
  • x=35x = 35: 352020=0.75\frac{35-20}{20} = 0.75
  • x=40x = 40: 402020=1.00\frac{40-20}{20} = 1.00

Result: [0, 0.25, 0.5, 0.75, 1.0]

Step 1: Apply generalized formula with a=1a=-1, b=1b=1 xscaled=1+(x100)(1(1))300100=1+2(x100)200x_{\text{scaled}} = -1 + \frac{(x - 100)(1 - (-1))}{300 - 100} = -1 + \frac{2(x - 100)}{200}

Step 2: Calculate

  • x=100x = 100: 1+2(0)200=1.0-1 + \frac{2(0)}{200} = -1.0
  • x=200x = 200: 1+2(100)200=0.0-1 + \frac{2(100)}{200} = 0.0Why? Middle value maps to middle of range
  • x=300x = 300: 1+2(200)200=1.0-1 + \frac{2(200)}{200} = 1.0

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 xmaxx_{\text{max}} or xminx_{\text{min}}
  • 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/max

Z-score Normalization (Standardization)

z=xμσz = \frac{x - \mu}{\sigma}

Derivation from first principles:

We want transformation z=ax+bz = ax + b such that:

  • E[z]=0E[z] = 0 (mean is zero)
  • Var(z)=1\text{Var}(z) = 1 (standard deviation is 1)

Step 1: Mean condition E[z]=E[ax+b]=aE[x]+b=aμ+b=0E[z] = E[ax + b] = aE[x] + b = a\mu + b = 0     b=aμ\implies b = -a\mu

Step 2: Variance condition Var(z)=Var(ax+b)=a2Var(x)=a2σ2=1\text{Var}(z) = \text{Var}(ax + b) = a^2 \text{Var}(x) = a^2 \sigma^2 = 1     a=±1σ\implies a = \pm \frac{1}{\sigma}

We choose a=1σa = \frac{1}{\sigma} (positive to preserve order).

Step 3: Combine z=1σxμσ=xμσz = \frac{1}{\sigma} \cdot x - \frac{\mu}{\sigma} = \frac{x - \mu}{\sigma}

WHY this formula? (xμ)(x - \mu) centers the distribution at 0. Dividing by σ\sigma makes the spread exactly 1 standard deviation.

This converts absolute values to relative positions in the distribution.

Step 1: Calculate statistics

  • Mean: μ=60+70+80+90+1005=80\mu = \frac{60+70+80+90+100}{5} = 80
  • Variance: σ2=(6080)2+(7080)2+(8080)2+(9080)2+(10080)25\sigma^2 = \frac{(60-80)^2 + (70-80)^2 + (80-80)^2 + (90-80)^2 + (100-80)^2}{5} =400+100+0+100+4005=200= \frac{400 + 100 + 0 + 100 + 400}{5} = 200
  • Standard deviation: σ=20014.14\sigma = \sqrt{200} \approx 14.14

Step 2: Apply formula

  • x=60x = 60: z=608014.14=1.41z = \frac{60-80}{14.14} = -1.41Why? 60 is 1.41 std devs below average
  • x=70x = 70: z=708014.14=0.71z = \frac{70-80}{14.14} = -0.71
  • x=80x = 80: z=808014.14=0.00z = \frac{80-80}{14.14} = 0.00Why? At the mean
  • x=90x = 90: z=908014.14=0.71z = \frac{90-80}{14.14} = 0.71
  • x=100x = 100: z=1008014.14=1.41z = \frac{100-80}{14.14} = 1.41

Result: [-1.41, -0.71, 0, 0.71, 1.41]

Verification: Mean of z-scores = 0, std dev = 1 ✓

Min-max scaling:

  • xmin=30000x_{\text{min}} = 30000, xmax=200000x_{\text{max}} = 200000
  • Range =20000030000=170000= 200000 - 30000 = 170000
  • x=30000x = 30000: 3000030000170000=0.000\frac{30000-30000}{170000} = 0.000
  • x=45000x = 45000: 4500030000170000=15000170000=0.088\frac{45000-30000}{170000} = \frac{15000}{170000} = 0.088Why? All normal salaries squished near 0
  • x=200000x = 200000: 20000030000170000=1.000\frac{200000-30000}{170000} = 1.000 (the outlier)

Notice: The four normal salaries all fall in [0, 0.088] — completely compressed by the outlier.

Z-score normalization:

  • Mean: μ=30000+35000+40000+45000+2000005=3500005=70000\mu = \frac{30000+35000+40000+45000+200000}{5} = \frac{350000}{5} = 70000
  • Variance: σ2=(3000070000)2+(3500070000)2+(4000070000)2+(4500070000)2+(20000070000)25\sigma^2 = \frac{(30000-70000)^2 + (35000-70000)^2 + (40000-70000)^2 + (45000-70000)^2 + (200000-70000)^2}{5} =1.6×109+1.225×109+0.9×109+0.625×109+16.9×1095=21.25×1095=4.25×109= \frac{1.6\times10^9 + 1.225\times10^9 + 0.9\times10^9 + 0.625\times10^9 + 16.9\times10^9}{5} = \frac{21.25\times10^9}{5} = 4.25\times10^9
  • Standard deviation: σ=4.25×10965192\sigma = \sqrt{4.25\times10^9} \approx 65192
  • z45000=450007000065192=25000651920.38z_{45000} = \frac{45000-70000}{65192} = \frac{-25000}{65192} \approx -0.38
  • z200000=2000007000065192=130000651921.99z_{200000} = \frac{200000-70000}{65192} = \frac{130000}{65192} \approx 1.99

Why z-score is better here? The outlier gets a large z-score (≈2.0) but the normal salaries still spread across roughly [0.61,0.38][-0.61, -0.38] rather than being crushed into a tiny sliver near 0. However: z-score is still affected by outliers because they inflate both μ\mu and σ\sigma — 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: xrobust=xmedian(x)IQR(x)x_{\text{robust}} = \frac{x - \text{median}(x)}{\text{IQR}(x)} 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: x=xscaled(xmaxxmin)+xminx = x_{\text{scaled}} \cdot (x_{\text{max}} - x_{\text{min}}) + x_{\text{min}}

Z-score inverse: x=zσ+μx = z \cdot \sigma + \mu

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 2/weekandtheysaved2/week and they saved 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


#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?
xscaled=xxminxmaxxminx_{\text{scaled}} = \frac{x - x_{\text{min}}}{x_{\text{max}} - x_{\text{min}}}. The numerator (xxmin)(x - x_{\text{min}}) shifts the range to start at 0. The denominator (xmaxxmin)(x_{\text{max}} - x_{\text{min}}) normalizes by the original range, compressing to [0, 1].
What is the z-score normalization formula and what does it represent?
z=xμσz = \frac{x - \mu}{\sigma}. It represents how many standard deviations away from the mean a value is. The (xμ)(x - \mu) centers at 0, and ÷σ\div \sigma standardizes the spread to 1.
When should you use min-max scaling vs z-score normalization?
Use min-max when you need bounded output [0,1] and have few outliers. Use z-score when data is normally distributed, you need to handle new extreme values, or when algorithms assume standardized input (PCA, LDA).
Why must you fit scalers only on training data?
To prevent data leakage. The test set represents unseen future data. Using its statistics (min, max, mean, std) would leak information about the test distribution into the model, causing overly optimistic evaluation.
What happens if you apply min-max scaling with an extreme outlier?
The outlier becomes the new max (or min), compressing all normal values into a tiny range near 0 or 1. For example, if most values are 10-100 but one outlier is 1000, all normal values map to approximately 0-0.01.
How do you invert a min-max scaled value back to original scale?
x=xscaled(xmaxxmin)+xminx = x_{\text{scaled}} \cdot (x_{\text{max}} - x_{\text{min}}) + x_{\text{min}}. Multiply by the range to stretch back, then shift by the minimum.
What is the key mistake when scaling train and test sets?
Scaling them separately. This makes the same original value map to different scaled values in train vs test, misaligning the model's learned decision boundaries. Always fit on training data and apply the same transformation to test data.
What algorithms require feature scaling?
Gradient descent algorithms (linear/logistic regression, neural networks), distance-based algorithms (k-NN, k-means, SVM with RBF kernel), PCA, and any algorithm with L1/L2 regularization.
What algorithms do NOT need feature scaling?
Tree-based algorithms (decision trees, random forests, XGBoost, gradient boosting) because they split on relative rank-based thresholds, not absolute distances. Also Naive Bayes since it works with probabilities.

Concept Map

solves

affects

affects

method

method

derived from

maps min to 0, max to 1

extended to

uses mean and std

does not need

Feature Scaling

Feature magnitude dominance

Min-max Scaling

Z-score Normalization

Linear transform ax+b

Fixed range 0 to 1

Generalized range a,b

Gradient descent

Distance-based algorithms

Tree-based models

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.

Go deeper — visual, from zero

Test yourself — Data Preprocessing & Feature Engineering

Connections