ML Scale
Features often come in wildly different units. A data set about houses might hold the floor area in square metres (50–300), the number of bedrooms (1–6) and the distance to the city centre in metres (200–30 000). Comparing these numbers directly is like comparing apples with kilometres.
Many algorithms care a lot about this. Models that measure distances (k-nearest neighbors, k-means, SVMs) or that are trained with gradient descent (logistic regression, neural networks) treat a feature measured in thousands as far more important than one measured in single digits. Scaling puts every feature on a comparable range.
Standardization
The most common method is standardization: subtract the mean and divide by the standard deviation. Each value becomes a z-score, and every scaled column ends up with mean 0 and standard deviation 1:
z = (x - mean) / stdimport numpy as np
area_m2 = np.array([55, 80, 120, 95, 210, 150])
z = (area_m2 - area_m2.mean()) / area_m2.std()
print("mean:", area_m2.mean().round(2), " std:", area_m2.std().round(2))
print("scaled:", z.round(3))
print("scaled mean:", z.mean().round(3), " scaled std:", z.std().round(3))mean: 118.33 std: 50.72
scaled: [-1.249 -0.756 0.033 -0.46 1.807 0.624]
scaled mean: 0.0 scaled std: 1.0
A positive z means "above average", a negative one "below average", and the size says by how many standard deviations.
StandardScaler
scikit-learn's StandardScaler does this for every column at once. Like a model, it has a fit step (learn each column's mean and std) and a transform step (apply them). fit_transform does both:
import pandas as pd
from sklearn.preprocessing import StandardScaler
houses = pd.DataFrame({
"area_m2": [55, 80, 120, 95, 210, 150],
"bedrooms": [1, 2, 3, 2, 5, 4],
"distance_m": [800, 2500, 12000, 4000, 25000, 9000],
})
scaler = StandardScaler()
scaled = scaler.fit_transform(houses)
print("learned means:", scaler.mean_.round(1).tolist())
print("learned stds: ", scaler.scale_.round(1).tolist())
print(pd.DataFrame(scaled, columns=houses.columns).round(2))learned means: [118.3, 2.8, 8883.3]
learned stds: [50.7, 1.3, 8158.9]
area_m2 bedrooms distance_m
0 -1.25 -1.36 -0.99
1 -0.76 -0.62 -0.78
2 0.03 0.12 0.38
3 -0.46 -0.62 -0.60
4 1.81 1.61 1.98
5 0.62 0.87 0.01
All three columns now live on the same scale, roughly between −2 and +2.
Scaling new data
Here is the most important rule of scaling: new data must be scaled with the statistics learned from the training data. Call transform (not fit_transform) on the new rows, so the same mean and std are used:
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
houses = pd.DataFrame({
"area_m2": [55, 80, 120, 95, 210, 150, 70, 180],
"bedrooms": [1, 2, 3, 2, 5, 4, 2, 4],
"distance_m": [800, 2500, 12000, 4000, 25000, 9000, 1500, 15000],
})
price_k = [210, 265, 300, 290, 430, 380, 250, 390]
scaler = StandardScaler()
X_scaled = scaler.fit_transform(houses)
model = LinearRegression().fit(X_scaled, price_k)
new_house = pd.DataFrame({"area_m2": [100], "bedrooms": [3], "distance_m": [5000]})
new_scaled = scaler.transform(new_house) # transform only!
print("new house scaled:", new_scaled.round(3))
print("predicted price (thousands):", model.predict(new_scaled).round(1))new house scaled: [[-0.385 0.099 -0.475]]
predicted price (thousands): [302.3]
If you called fit_transform on the single new house, its mean would be the house itself and every value would become 0 — a classic bug.
Comparing coefficients after scaling
Once features are standardized, a linear model's coefficients become comparable: each one is "change in the target per one standard deviation of that feature".
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
houses = pd.DataFrame({
"area_m2": [55, 80, 120, 95, 210, 150, 70, 180],
"bedrooms": [1, 2, 3, 2, 5, 4, 2, 4],
"distance_m": [800, 2500, 12000, 4000, 25000, 9000, 1500, 15000],
})
price_k = [210, 265, 300, 290, 430, 380, 250, 390]
raw = LinearRegression().fit(houses, price_k)
scaled = LinearRegression().fit(StandardScaler().fit_transform(houses), price_k)
print(f"{'feature':11}{'raw coef':>10}{'scaled coef':>13}")
for name, r, s in zip(houses.columns, raw.coef_, scaled.coef_):
print(f"{name:11}{r:10.4f}{s:13.2f}")feature raw coef scaled coef
area_m2 1.4224 73.82
bedrooms 20.1510 25.56
distance_m -0.0037 -29.21
The raw coefficient for distance_m looks tiny only because a metre is a tiny unit. After scaling you can see each feature's real weight in the model.
Other scalers
| Scaler | What it does | When to use it |
|---|---|---|
StandardScaler |
mean 0, std 1 | the default choice |
MinMaxScaler |
squeezes values into 0…1 | features with known bounds, image pixels |
RobustScaler |
subtracts the median, divides by the IQR | data with strong outliers |
import numpy as np
from sklearn.preprocessing import MinMaxScaler, RobustScaler
salaries = np.array([[32], [35], [38], [41], [45], [400]]) # one CEO
print("min-max:", MinMaxScaler().fit_transform(salaries).ravel().round(3))
print("robust: ", RobustScaler().fit_transform(salaries).ravel().round(3))min-max: [0. 0.008 0.016 0.024 0.035 1. ]
robust: [-0.909 -0.545 -0.182 0.182 0.667 43.697]
With min–max scaling the single outlier squashes all normal salaries close to 0. The robust scaler keeps them nicely spread out because the median and IQR ignore the extreme value.
Tip: Tree-based models (decision trees, random forests, gradient boosting) split on one feature at a time and don't need scaling. Scale for linear models, SVMs, KNN, k-means, PCA and neural networks.
Go further: Min-Max, Z-Score, Robust and Max-Abs Scaling in the Machine Learning track writes each scaler from scratch and says which one to choose for which data.
Test yourself
After StandardScaler, what are the mean and standard deviation of each training column?
- 0 and 1
- 1 and 0
- 0 and 100
- The same as before
You trained a model on scaled data. How should you scale a new sample?
scaler.fit_transform(new)scaler.transform(new)- Don't scale it
- Create a new StandardScaler for it
Which model type usually does NOT need feature scaling?
- K-nearest neighbors
- Support vector machine
- Decision tree
- K-means