Cheat sheets › Chapter 5
Generalization cheat sheet
Make models that work on data they have never seen. Every lesson in one page: the key idea, the pseudocode and the terms.
Bias and variance
Train the same kind of model on different samples of data and each version guesses a little differently. Picture each guess as a dart. The bullseye is the true answer. Ideally the darts land tight and centered.
# imagine training the same model on many different samples
for each sample of data:
model = train(sample)
record its guess for one test point
bias = how far the average guess is from the truth
variance = how much the guesses scatter
total error ≈ bias² + variance + noiseCross-validation
cross-validation cuts the data into equal slices called folds. Here there are 5, shown in different colors.
folds = split the data into 5 equal parts
scores = []
for each fold:
test = this fold
train = the other 4 folds
scores.add(train_and_score(train, test))
final score = average(scores)Terms: cross-validation, fold
L1 and L2 regularization
regularization adds a penalty to the loss: the bigger the weights, the bigger the fee. Now the model only keeps a weight large if it truly earns its keep by reducing the error.
loss = prediction error
+ λ × size of the weights # the penalty
L2 (ridge): penalty = sum of weights² → shrinks all weights
L1 (lasso): penalty = sum of |weights| → pushes some to exactly 0
bigger λ = stronger penalty = simpler modelTerms: regularization
Feature scaling
Lopsided scales turn the error landscape into a long, narrow valley. Gradient descent zigzags across it, wasting steps.
income = [32000, 54000, 81000] # huge numbers age = [25, 41, 63] # small numbers # min-max scaling: squeeze into 0..1 scaled = (x − min) / (max − min) # or standardize: (x − mean) / std
Terms: feature scaling
Hyperparameter tuning
Some settings aren’t learned from data: you pick them before training, like the learning rate or how deep a tree may grow. These are called hyperparameters, and they can make or break a model.
# settings you choose before training
options = learning_rate in [0.001, 0.01, 0.1]
× tree_depth in [2, 4, 8, 16]
for each combination:
score = cross_validate(model with these settings)
best = the combination with the highest score
# random search: try random combinations insteadTerms: hyperparameter, grid search
Data leakage
One feature, “was given treatment X”, is only known after a doctor diagnosed the disease. The model learned a shortcut, not medicine. That is data leakage.
# leak: information about the answer sneaks into the features features = [age, symptoms, "was given treatment X"] # ← leak! model.learn(features, has_disease) score on test = 99% # suspiciously perfect in the real clinic: much worse # fix: only use what you would really know at prediction time features = [age, symptoms]
Terms: data leakage
Revise with flashcards and quizzes. Free practice for every lesson in this chapter.
Open in the app