Model Training
From the loss function to hyperparameter tuning: how to train a model and choose its settings methodically.
What do we learn?
- Parameters: learned from the data, such as the weights \(\mathbf{w}\).
- Hyperparameters: set by us, such as
Candmax_depthandn_neighbors.
Iterative optimization
Many models are trained with gradient descent:
$$\mathbf{w} \leftarrow \mathbf{w} – \eta \, \nabla_{\mathbf{w}} L(\mathbf{w})$$
where \(\eta\) is the learning rate. You will go deeper into this in the Deep Learning track.
Start with a baseline
from sklearn.dummy import DummyClassifier
from sklearn.model_selection import cross_val_score
base = DummyClassifier(strategy="most_frequent")
print(cross_val_score(base, X, y, cv=5, scoring="balanced_accuracy").mean())If your model does not clearly beat this number, review the data before making the model more complex.
Hyperparameter tuning
from scipy.stats import loguniform
from sklearn.model_selection import RandomizedSearchCV, StratifiedKFold
from sklearn.svm import SVC
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
pipe = make_pipeline(StandardScaler(), SVC())
search = RandomizedSearchCV(
pipe,
{"svc__C": loguniform(1e-2, 1e3), "svc__gamma": loguniform(1e-4, 1e1)},
n_iter=40, cv=StratifiedKFold(5, shuffle=True, random_state=0),
scoring="f1_macro", random_state=0, n_jobs=-1)
search.fit(X_train, y_train)
print(search.best_params_, search.best_score_)
best = search.best_estimator_ # retrained on all of X_trainAfter choosing the settings, evaluate best once on the test data.
Reproducibility
- Fix
random_statein the split and the models. - Record the library versions, the settings and the results.
- Save the trained model together with the whole processing pipeline (for example with
joblib).
Checklist
- A sound data split.
- A baseline.
- A processing pipeline inside
Pipeline. - Hyperparameter tuning with cross-validation.
- A single final evaluation on the test set.
Lesson terms
- Grid search
- Trying every combination of the specified hyperparameter values and choosing the best according to cross-validation.
- Hyperparameter
- A setting chosen before training and not learned directly from the data, such as the tree depth or the learning rate.
- The baseline
- A simple model used as a reference for comparison, such as predicting the most frequent class.
Abstract
Training a model means finding the parameters that minimize the loss function on the training data, with closed-form solutions or iterative optimization methods such as gradient descent. Hyperparameters, such as the depth of a tree or the strength of regularization, are chosen with grid or random search with cross-validation. Good training starts with a simple baseline and ensures reproducibility by fixing seeds and documenting the settings.
Review questions
-
What is the difference between a parameter and a hyperparameter?
A parameter is learned from the data during training (such as regression weights), and a hyperparameter is set before training (such as C or max_depth).
-
Why do we start with a baseline?
To know whether the complex model adds real value, and to detect data problems early.
Sources and references
Complete the lesson
You have completed all the lessons in the track! You can now request the track completion certificate.
Request the certificate