EXERCISE
1StandardScaler transforms every value using the same formula: subtract the mean, divide by the standard deviation.
StandardScaler is like converting every student''s score to "how many standard deviations above or below the class average." An A student in a hard class and an A student in an easy class get different raw scores, but similar scaled scores.
Manual calculation vs StandardScaler:
import numpy
# Manual: scale the first weight value (790)
weights = [790,1160,929,865,1140,929,1109,1365,1112,1150,
980,990,1112,1252,1326,1330,1365,1280,1119,1328,
1584,1428,1365,1415,1415,1465,1490,1725,1523,1705,
1605,1746,1235,1390,1405,1395]
mean_w = numpy.mean(weights)
std_w = numpy.std(weights)
scaled_790 = (790 - mean_w) / std_w
print(f"Manual scaled: {round(scaled_790, 2)}")
# Output: Manual scaled: -2.10
Using StandardScaler (the ML way):
from sklearn.preprocessing import StandardScaler
import pandas as pd
df = pd.read_csv("cars2.csv")
X = df[["Weight", "Volume"]]
scaler = StandardScaler()
scaledX = scaler.fit_transform(X)
print(f"Scaled first row: {[round(v, 2) for v in scaledX[0]]}")
# Output: Scaled first row: [-2.1, -1.59]
# Verify: mean ≈ 0, std ≈ 1
print(f"Mean after scaling: {[round(v, 4) for v in scaledX.mean(axis=0)]}")
# Output: Mean after scaling: [0.0, 0.0]
print(f"Std after scaling: {[round(v, 4) for v in scaledX.std(axis=0)]}")
# Output: Std after scaling: [1.0, 1.0]
Pro Tip:
fit_transform()does two things.fit()learns the mean and std from your training data.transform()applies the formula. On NEW data, you only calltransform()— using the mean and std from training. Using fresh statistics on test data is a classic data leakage bug.