Sub topic 11
Training a model
This chapter assumes you can split data into train and test sets and that you know what a scikit-learn pipeline is. Here you will see what happens inside fit, and which settings you choose and which the algorithm learns.
What training does
Training is a search for the parameter values that make a model's predictions match the known labels as closely as possible. Closeness is measured by a loss function, a number that is large when predictions are wrong. For classification, logistic regression uses log loss. It penalizes confident wrong probabilities heavily.
Most scikit-learn models learn by repeating a loop:
Parameters and hyperparameters
Parameters are values the algorithm learns from data, such as the coefficients in coef_. Hyperparameters are values you set before training, such as C (regularization strength) and max_iter (the iteration limit). The tuning chapter covers how to choose hyperparameters. Here you just set them.
scikit-learn marks learned attributes with a trailing underscore. You can inspect them after fit and not before.
Fitting a model
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import log_loss
X, y = load_breast_cancer(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
model = Pipeline([
("scale", StandardScaler()),
("clf", LogisticRegression(C=1.0, max_iter=1000)),
])
model.fit(X_train, y_train)
clf = model.named_steps["clf"]
print("iterations used:", clf.n_iter_)
print("coefficient shape:", clf.coef_.shape)
print("train log loss:", log_loss(y_train, model.predict_proba(X_train)))
print("train accuracy:", model.score(X_train, y_train))The output shows how many iterations the optimizer needed. It also shows one coefficient per feature, 30 in this dataset. The training loss and accuracy describe how well the model fits data it has already seen. They are not an estimate of performance on new data.
Common errors
- Fitting on test rows. Call
fitonly on training data. Calling it on the full dataset leaks information, which the leakage chapter describes. - Ignoring convergence warnings. A
ConvergenceWarningmeans the loop hitmax_iterbefore the loss settled. Raisemax_iteror scale the features. Unscaled features are a frequent cause. - Trusting the training score. A high training score only shows the model can fit the training set. Overfitting is covered in the next chapter.
- Forgetting randomness. Some models, such as random forests, start from random values. Set
random_stateso a rerun gives the same model. - Refitting by accident. Calling
fitagain discards what the model learned before. It does not add to it.
Exercise
Your pipeline emits a ConvergenceWarning during fit. Name two changes that might fix it, and say whether the warning is about training or test data.
Show answer
Increase max_iter, or scale the features (for example with StandardScaler in the pipeline). The warning concerns training only. The optimizer stopped before the loss on the training data settled, so the fitted parameters may not be the best ones.
Exercise
Which of these is a parameter and which is a hyperparameter: the entries of clf.coef_, and C?
Show answer
The entries of clf.coef_ are parameters, because the algorithm learns them during fit. C is a hyperparameter, because you set it before training.