Learning path: Prepare Data for a Machine Learning Model · Step 4 of 7
Feature Scaling: StandardScaler, MinMaxScaler and Which Models Care
Put features on the same scale so each one gets a fair say. StandardScaler and MinMaxScaler fitted on the train rows, the formula checked by hand, and a wine test where KNN jumps from 0.806 to 0.972 while a decision tree stays at 0.944.
What you will learn
- Explain why a feature with big numbers drowns out the others in a distance
- Standardise features with StandardScaler and check the formula by hand
- Squeeze features into 0 to 1 with MinMaxScaler, and see why test rows can land just outside
- Tell which models need scaling (KNN, SVM, linear models, neural networks) and which don't (trees)
Before you start
- Train-Test Split and Data Leakage
- Basic pandas
Meet Ann and Tom. Ann earns $60,000 and she's 25. Tom earns $110,000 and he's 35. How far apart are they?
The salary gap is 50,000. The age gap is 10. Put both into one distance and the salary shouts while the age whispers. Age barely counts, even if it matters just as much.
Feature scaling fixes that. It puts every feature on a comparable scale, so every feature gets a fair say. In this lesson you'll use the two common scalers on Rain in Australia, then test which models actually care.
Three features, three scales
We keep three weather columns, drop the rows with blanks for now (filling them is covered in Handling Missing Data), and split first.
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.datasets import load_wine
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
df = pd.read_csv("weatherAUS.csv")
cols = ["Pressure9am", "Humidity3pm", "Rainfall"]
data = df[cols + ["RainTomorrow"]].dropna()
X, y = data[cols], data["RainTomorrow"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42)
print(X_train.shape, X_test.shape)
(99751, 3) (24938, 3)
stats = ["mean", "std", "min", "max"]
X_train.describe().loc[stats].round(1)
Pressure9am Humidity3pm Rainfall
mean 1017.7 51.3 2.3
std 7.1 20.6 8.5
min 982.0 0.0 0.0
max 1040.9 100.0 371.0
Pressure sits near 1,017. Humidity runs from 0 to 100. Rainfall is mostly near zero, with a maximum of 371. Three completely different scales.
StandardScaler: mean 0, spread 1
Standardisation subtracts the column's mean and divides by its spread (standard deviation):
z = (value - mean) / scale
Fit on X_train only, then transform:
std = StandardScaler().fit(X_train)
Z = std.transform(X_train)
Z = pd.DataFrame(Z, columns=cols)
Z.describe().loc[stats].round(2) + 0
Pressure9am Humidity3pm Rainfall
mean 0.00 0.00 0.00
std 1.00 1.00 1.00
min -5.02 -2.48 -0.27
max 3.27 2.36 43.19
Every column now has a mean of 0 and a standard deviation of 1. But there's no fixed range: Rainfall goes up to 43.19 because it has extreme days. A standardised value simply says how many standard deviations it sits from the mean.
(The + 0 just turns any -0.00 into 0.00 for display.)
Check it by hand
Take the first humidity value in the train rows and do the formula yourself, using the mean and scale the scaler learned:
v = X_train["Humidity3pm"].iloc[0]
mean, scale = std.mean_[1], std.scale_[1]
z = (v - mean) / scale
print(v, round(mean, 1), round(scale, 1), round(z, 2))
print(round(Z["Humidity3pm"].iloc[0], 2))
40.0 51.3 20.6 -0.55
-0.55
(40 - 51.3) / 20.6 gives -0.55, and the scaler's own answer for the same row is -0.55 too. That's all a scaler does: one subtraction and one division, for every value.
MinMaxScaler: 0 to 1
Min-max normalisation subtracts the column's minimum and divides by its range (max minus min). Again, fit on the train rows only:
mm = MinMaxScaler().fit(X_train)
M = mm.transform(X_train)
M = pd.DataFrame(M, columns=cols)
M.describe().loc[["min", "max"]].round(2)
Pressure9am Humidity3pm Rainfall
min 0.0 0.0 0.0
max 1.0 1.0 1.0
Every train column runs exactly from 0 to 1. Now send the test rows through the same scaler, transform only:
T = mm.transform(X_test)
print(T.min().round(3), T.max().round(3))
-0.025 1.002
The test values land from -0.025 to 1.002, just outside 0 and 1. That's correct, not a bug. The scaler learned its min and max from the train rows only, and a few test days were a bit more extreme.
Which one should you use?
| StandardScaler | MinMaxScaler | |
|---|---|---|
| Result | mean 0, std 1 | train rows in 0 to 1 |
| Fixed range? | No | Yes (test rows can land slightly outside) |
| Outliers | Copes better | One extreme value squeezes the rest |
| Good for | The safe default | Values with natural bounds, like pixels |
If you aren't sure, start with StandardScaler. Either way: fit on the train rows, then transform both.
Which models care? KNN vs a decision tree
The wine data comes with scikit-learn. Look at the biggest value of three of its features:
wX, wy = load_wine(return_X_y=True, as_frame=True)
top = wX[["proline", "alcohol", "hue"]].max()
print(top.tolist())
[1680.0, 14.83, 1.71]
Proline goes up to 1,680, hue stays below 2. One feature is huge and one is tiny. Split first, fit the scaler on the train rows:
wX_train, wX_test, wy_train, wy_test = train_test_split(
wX, wy, test_size=0.2, stratify=wy, random_state=42)
scaler = StandardScaler().fit(wX_train)
Xs_train = scaler.transform(wX_train)
Xs_test = scaler.transform(wX_test)
A small helper fits a model and scores it on the test rows. Run each model twice, on raw and on scaled data:
def score(model, A, B):
model.fit(A, wy_train)
return round(model.score(B, wy_test), 3)
knn = KNeighborsClassifier()
tree = DecisionTreeClassifier(
max_depth=5, random_state=42)
for name, m in [("KNN", knn), ("Tree", tree)]:
raw = score(m, wX_train, wX_test)
scaled = score(m, Xs_train, Xs_test)
print(name, "raw", raw, "scaled", scaled)
KNN raw 0.806 scaled 0.972
Tree raw 0.944 scaled 0.944
K-nearest neighbours measures distances, so proline drowned out everything else on the raw data. After scaling it jumps from 0.806 to 0.972. The decision tree scores 0.944 both times: it splits on one feature at a time, so the scale doesn't matter to it.
Rule of thumb
- Scale for anything that measures distances or follows gradients: KNN, support vector machines, linear and logistic regression, neural networks.
- No need for tree-based models: decision trees, random forests, boosting.
- When in doubt, scale. It rarely hurts.
Common mistakes
- Fitting the scaler on all rows before the split. The test rows leak into the mean and the spread.
- Calling
fit_transformon the test rows. They gettransformonly, with the train numbers. - Treating test values outside 0 to 1 as an error. With MinMaxScaler that's expected.
- Expecting standardised values to sit in a fixed range. Rainfall reached 43.19.
Quick recap
| Idea | Code | Result here |
|---|---|---|
| Standardise | StandardScaler().fit(X_train) | mean 0.00, std 1.00 |
| The formula | (v - mean_) / scale_ | (40 - 51.3) / 20.6 = -0.55 |
| Normalise | MinMaxScaler().fit(X_train) | train 0 to 1, test -0.025 to 1.002 |
| Distance models care | KNN | 0.806 raw, 0.972 scaled |
| Trees don't | DecisionTreeClassifier | 0.944 either way |
Try it yourself
Scale the wine data with MinMaxScaler instead of StandardScaler. Does the KNN score change?
The notebook and the dataset are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Encoding Categorical Data: OrdinalEncoder, OneHotEncoder and LabelEncoder
Next →Pipelines and ColumnTransformer: All Preprocessing and the Model in One Object
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Train-Test Split and Data Leakage: Split First, Learn After
Why the train-test split comes before everything else: an 80/20 split with stratify and random_state, a scaler that leaks test rows, and a column that secretly holds the answer. Shown on Rain in Australia.
Handling Missing Data: Count the Blanks, Then Fill Them with SimpleImputer
Count the blanks with isnull().sum(), see why dropna() would throw away 60% of the rows, and fill the gaps with SimpleImputer: median for numbers, most frequent for text, learned from the train rows only. Shown on Rain in Australia.
Encoding Categorical Data: OrdinalEncoder, OneHotEncoder and LabelEncoder
Models only understand numbers. Encode T-shirt sizes with OrdinalEncoder, colours with OneHotEncoder, avoid the dummy variable trap, handle a colour the encoder never saw, tame a date with 3,436 values, and encode the answer with LabelEncoder.
Pipelines and ColumnTransformer: All Preprocessing and the Model in One Object
Pack imputing, encoding, scaling and the model into one scikit-learn Pipeline with two ColumnTransformer lanes. One fit on the train rows, 21 columns in, 115 out, 0.849 test accuracy, and a raw row with a blank predicted directly.