Skip to main content
Quick Reference

ML Cheatsheet

Classical machine learning on one page — splits, linear models, trees, metrics, and the traps around leakage, accuracy, and R².

10 sections 10 tables 14 code snippets

Fit, then hold out

A split

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=0
)

One honest score

# score the held-out rows once

The three jobs

NameMeaning
SupervisedFeatures X and a label y. The fit learns a map from one to the other
UnsupervisedNo label. Clustering and PCA look for structure in X
TrainThe rows used to fit. A score on these rows is optimistic
ValidationThe rows used to choose a model. This is not the number you publish
TestTouched once, after the model is frozen
stratify=yOn a classification split, keep the class mix in both sides

This page is classical machine learning. Neural networks and deep learning are left out.

Leakage

Learn the scale on train

scaler = StandardScaler()
scaler.fit(X_train)

Apply that scale

X_test_s = scaler.transform(X_test)

What counts as a leak

LeakWhy the score lies
fit on every rowThe test mean and variance enter the model
fit on the test rowsThe holdout is no longer unseen
Answer in a columnA future price or a diagnosis code will not exist at prediction time
Random time splitLater rows teach the model about earlier ones
Duplicate rowsThe same example sits on both sides, so memory looks like skill
Resample firstSynthetic rows built before the split can use test neighbors

Features

Make the columns usable

StepRule
ScaleNeeded for distance models, penalized linear models, and PCA. A tree ignores units
StandardScalerMean 0 and variance 1, computed on the training rows
One-hotOne column per category. Integer codes invent an order a linear model will trust
Drop oneWith an intercept, k one-hot columns sum to a constant, so plain coefficients are not unique
ImputeFill missing values from the training rows only. A missingness flag can be its own column
Target encodingUses the label. Fit it inside the training fold or the label leaks

Linear models

A probability

LogisticRegression().fit(X_train, y_train)

A shrunk line

Ridge().fit(X_train, y_train)

What the fit means

ModelDetail
Linear regressionPredicts a number. Ordinary least squares minimizes squared error
Logistic regressionPredicts a class probability. The score is a log-odds, then a sigmoid
CoefficientThe association given the other columns. It is not a cause
L2, RidgeShrinks coefficients toward zero. None are forced to zero
L1, LassoCan set coefficients to zero. Among correlated columns the choice is unstable
Scale firstThe penalty depends on units. An unscaled column with a huge range is punished more

Trees

A forest

RandomForestClassifier(random_state=0).fit(X_train, y_train)

Trees and ensembles

ModelDetail
One treeSplits on thresholds. A deep tree memorizes the training rows
Random forestAverages trees on bootstrap samples and random feature subsets. Variance drops
BoostingAdds trees that fit the remaining error. Too many trees, or a high learning rate, overfit
ScalingNot required. A split looks at order, not at units
ImportanceA split statistic. It favors a column with many possible cuts, and it is not an effect
VotesA forest probability is a share of votes. That share is not automatically calibrated

Clusters and PCA

Three groups

KMeans(n_clusters=3, random_state=0)

Two directions

PCA(n_components=2)

Structure without a label

MethodDetail
kNNPredicts from the nearest training rows. Scale first or a wide column dominates
Choice of kA tiny k memorizes. A huge k slides toward the global average
k-meansLooks for round clusters and needs k in advance. Run several starts
PCADirections of high variance. The label is never used, so a loud direction can be useless
ScaleRequired before k-means and PCA, or the largest unit picks the result
ElbowA hint for k. It is not a proof

Metrics

A rare class

# accuracy stays high if almost every label is negative

Match the cost

MetricWhat it says
AccuracyShare correct. Predicting the majority class can look excellent
PrecisionOf the predicted positives, how many are true
RecallOf the true positives, how many were found
F1The harmonic mean. Macro-F1 treats each class the same
ROC-AUCHow often a true positive outranks a true negative. A rare class can still score high while precision is poor
RMSE and R²RMSE is in the units of y and punishes a huge miss. R² of 0 matches the mean. Below 0 is worse

Tuning

Five folds on the training rows

cross_val_score(model, X_train, y_train, cv=5)

Choices that are not learned in one fit

ChoiceRule
HyperparameterTree depth, k, and the penalty. Chosen on validation, not inside one training fit
Cross-validationAverage several folds of the training rows. Report the spread, not only the mean
Test setNot a tuning set. Each peek makes the published number optimistic
StratifyKeep the class mix in every classification fold
random_stateMakes one run reproducible. It is not an error bar
Early stopWatch validation loss. Stopping on training loss does not limit overfitting

Fit and overfit

The gap

# low train error and high test error is overfitting

Read the two errors

PatternMeaning
High on bothUnderfit. The model is too simple, or the columns do not carry the label
Low train, high testOverfit. The fit memorized noise
More rowsThe usual fix for overfitting, along with a simpler model or a stronger penalty
BiasError from a form that cannot represent the pattern
VarianceError from fitting this particular sample. A forest cuts it by averaging
Learning curveScore against training size. A wide train-to-validation gap is overfitting

Interview traps

Traps worth memorising

TrapWhat happensPrefer
Score the training rowsMemory looks like skillA held-out score
scaler.fit(X) before the splitThe test mean enters the modelfit on train, transform on test
Shuffle a time seriesThe future trains the pastA cutoff in time, with no shuffle across it
A column that is the labelThe model cheats with a value you will not have laterDrop anything unavailable at prediction time
Accuracy on a rare classAlways predicting the majority looks strongPrecision, recall, and a precision-recall curve
ROC-AUC aloneFalse alarms barely move the curve when positives are rareAdd precision-recall
City names as 0, 1, 2A linear model treats the codes as a scaleOne-hot, and drop one column if there is an intercept
Test R² below 0Worse than predicting the mean of those labelsDo not ship on the training score
A Lasso zeroAmong correlated columns, one survivor is an unstable pickDo not read a zero as proof of no link
Forest importance as a causeIt is a split statisticA change in the column, measured on held-out rows
Resample the full tableSynthetic rows can be built from test neighborsResample inside the training fold only
Tune on the test setThe final number is no longer honestFreeze the model, then touch the test once

Scale inside the fit

pipe = make_pipeline(StandardScaler(), LogisticRegression())
pipe.fit(X_train, y_train)

Cut on time

# split a time series by date, not at random

How to use this page: split first, fit every preprocessor on the training rows, and pick a metric that matches the cost of a mistake. A high training score is not a result.