🎓 A1Learner
🔍
0 of 50 lessons completed

Python ML Scale Features and Encode Categories

Scaling puts numbers on one shared scale. Encoding turns words into numbers, so a model can read them.

Fare dwarfs age before scaling

Fare has a much bigger spread than age. A distance model would mostly feel the fare.

import seaborn as sns
df = sns.load_dataset("titanic")
print("Age mean:", round(float(df["age"].mean()), 1))
print("Age spread:", round(float(df["age"].std()), 1))
print("Fare mean:", round(float(df["fare"].mean()), 1))
print("Fare spread:", round(float(df["fare"].std()), 1))

StandardScaler centres both columns

After scaling, each column has a mean of 0 and a spread of 1. Age and fare now count the same.

import seaborn as sns
from sklearn.preprocessing import StandardScaler
df = sns.load_dataset("titanic")
filled = df[["age", "fare"]].fillna(df[["age", "fare"]].median())
scaled = StandardScaler().fit_transform(filled)
print("Scaled age mean:", round(float(scaled[:, 0].mean()), 2))
print("Scaled age spread:", round(float(scaled[:, 0].std()), 2))
print("Scaled fare mean:", round(float(scaled[:, 1].mean()), 2))
print("Scaled fare spread:", round(float(scaled[:, 1].std()), 2))

MinMaxScaler squeezes both into 0 to 1

The smallest value in each column becomes 0. The largest value becomes 1.

import seaborn as sns
from sklearn.preprocessing import MinMaxScaler
df = sns.load_dataset("titanic")
filled = df[["age", "fare"]].fillna(df[["age", "fare"]].median())
squeezed = MinMaxScaler().fit_transform(filled)
print("Age low:", round(float(squeezed[:, 0].min()), 2))
print("Age high:", round(float(squeezed[:, 0].max()), 2))
print("Fare low:", round(float(squeezed[:, 1].min()), 2))
print("Fare high:", round(float(squeezed[:, 1].max()), 2))

One-hot turns words into columns

Sex gives two columns and embarked gives four. Each row has a 1 in its own column and 0 elsewhere.

import seaborn as sns
from sklearn.preprocessing import OneHotEncoder
df = sns.load_dataset("titanic")
encoder = OneHotEncoder(sparse_output=False, handle_unknown="ignore")
encoder.fit_transform(df[["sex", "embarked"]].fillna("missing"))
print(list(encoder.get_feature_names_out(["sex", "embarked"])))

Label encoding turns words into numbers

LabelEncoder gives female the number 0 and male the number 1. The first four rows show the codes.

import seaborn as sns
from sklearn.preprocessing import LabelEncoder
df = sns.load_dataset("titanic")
encoder = LabelEncoder()
codes = encoder.fit_transform(df["sex"])
print(list(encoder.classes_))
print([int(c) for c in codes[:4]])

Example

import seaborn as sns
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler

df = sns.load_dataset("titanic")
X = df[["age", "fare"]].copy()
X["age"] = X["age"].fillna(X["age"].median())
y = df["survived"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# KNN and the forest on the raw numbers.
knn_raw = KNeighborsClassifier()
knn_raw.fit(X_train, y_train)
forest_raw = RandomForestClassifier(random_state=42)
forest_raw.fit(X_train, y_train)

# The same two models on scaled numbers.
scaler = StandardScaler()
train_scaled = scaler.fit_transform(X_train)
test_scaled = scaler.transform(X_test)
knn_scaled = KNeighborsClassifier()
knn_scaled.fit(train_scaled, y_train)
forest_scaled = RandomForestClassifier(random_state=42)
forest_scaled.fit(train_scaled, y_train)

print("KNN raw:", round(accuracy_score(y_test, knn_raw.predict(X_test)), 4))
print("KNN scaled:", round(accuracy_score(y_test, knn_scaled.predict(test_scaled)), 4))
print("Forest raw:", round(accuracy_score(y_test, forest_raw.predict(X_test)), 4))
print("Forest scaled:", round(accuracy_score(y_test, forest_scaled.predict(test_scaled)), 4))

Key points

  • Scaler: a tool that resizes numbers onto a shared scale
  • Use StandardScaler to give each column a mean of 0 and a spread of 1
  • Use MinMaxScaler to squeeze each column into the range 0 to 1
  • One-hot encoding: one new column per word, with 1 for a match and 0 elsewhere
  • Use OneHotEncoder to turn a word column into one-hot columns
  • Label encoding: one number per word, like female 0 and male 1
  • Label numbers can fake an order, so one-hot is safer for plain words
  • KNN and logistic regression need scaling, because distance and size drive them
  • Tree models do not need scaling, because they split one column at a time

In this example, the features are age and fare only. The median age fills the blanks first, so scaling has clean numbers to work on. KNN and a random forest both train on the raw numbers. Then a StandardScaler is fit on the training rows only, and both models train again on the scaled numbers. Scaling lifts the KNN score, because fare no longer swamps age in the distance. The forest score barely moves, because a tree splits one column at a time and never measures distance.

Note

Fit a scaler on the training rows only, never on the whole table.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Which model needs scaling, and which one does not?