Sub topic 11
Training a model
This chapter covers what happens inside fit, how to check that training worked, and the errors that most often show up at this step. It assumes you can read scikit-learn code, that you have already split your data (including a held-out test set), and that you have a preprocessing pipeline and a baseline score to compare against. The next chapter covers overfitting in detail. Here the goal is a model that trained correctly.
What training means
Training is a search for the parameter values that make a model's predictions match the known labels as closely as possible. Two kinds of numbers are involved:
- Parameters are learned from data during
fit. Examples are the coefficients of a logistic regression and the split thresholds of a decision tree. - Hyperparameters are set by you before
fit. Examples are the regularization strengthC, the maximum tree depth, andmax_iter. A later chapter covers tuning them.
"Closely" is defined by a loss function, which turns the gap between predictions and labels into one number. Logistic regression minimizes log loss. Linear regression minimizes squared error. An optimizer is the procedure that changes the parameters to reduce that number. Many models use some form of gradient descent: compute the direction in which the loss falls fastest, take a step, and repeat.
Not every model works this way. A decision tree builds splits greedily with no gradient. Ordinary linear regression has a closed-form solution. The common thread is that fit uses only the training rows and produces a fitted object.
The fit and predict contract
Every scikit-learn estimator follows the same contract:
fit(X, y)learns parameters and returns the estimator itself.predict(X)andpredict_proba(X)use the learned parameters and never change them.- Learned attributes end in an underscore, such as
coef_orn_iter_. If they are missing, the model has not been fitted.
Calling fit a second time normally discards the earlier state and starts over. The exception is an estimator created with warm_start=True, which continues from the previous parameters.
Worked example: train, then inspect
The test set is split off first and then left alone. Training and model comparison use only the training and validation parts.
from sklearn.datasets import load_breast_cancer
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import log_loss
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True, as_frame=True)
X_dev, X_test, y_dev, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
X_train, X_val, y_train, y_val = train_test_split(
X_dev, y_dev, test_size=0.25, stratify=y_dev, random_state=42
)
baseline = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
model = make_pipeline(
StandardScaler(),
LogisticRegression(max_iter=1000),
)
model.fit(X_train, y_train)
for name, est in [("baseline", baseline), ("logistic", model)]:
print(
name,
"train acc:", round(est.score(X_train, y_train), 3),
"val acc:", round(est.score(X_val, y_val), 3),
)
print("train log loss:", log_loss(y_train, model.predict_proba(X_train)))
print("val log loss: ", log_loss(y_val, model.predict_proba(X_val)))
clf = model.named_steps["logistic"]
print("iterations used:", int(clf.n_iter_[0]))
print("number of coefficients:", clf.coef_.shape[1])Read the output in this order:
- Model against baseline. If the model's validation score is not clearly above the baseline's, training has not added value. Check the features and the target before changing the model.
- Training against validation. Training scores are almost always a little better than validation scores. A large gap is a symptom of overfitting, which the next chapter diagnoses.
- Iterations used. If
n_iter_equalsmax_iter, the optimizer probably stopped before converging. - Log loss as well as accuracy. Accuracy only counts right and wrong. Log loss also penalizes confident wrong probabilities, so it shows more of what the optimizer was minimizing.
Convergence and scaling
Gradient-based solvers converge slowly when features have very different ranges. In the breast cancer data, some columns are in the thousands and others are below 1. The ConvergenceWarning is how scikit-learn tells you the optimizer stopped without finding a stable solution. This code turns that warning into a testable result:
import warnings
from sklearn.datasets import load_breast_cancer
from sklearn.exceptions import ConvergenceWarning
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
def fits_cleanly(estimator, X, y):
with warnings.catch_warnings():
warnings.simplefilter("error", ConvergenceWarning)
try:
estimator.fit(X, y)
except ConvergenceWarning:
return False
return True
raw = LogisticRegression(max_iter=100)
scaled = make_pipeline(StandardScaler(), LogisticRegression(max_iter=100))
print("unscaled converged:", fits_cleanly(raw, X, y))
print("scaled converged: ", fits_cleanly(scaled, X, y))With the same iteration budget, the unscaled model typically fails to converge and the scaled one does not. The fix is to scale the features, which also makes coefficients comparable. Raising max_iter is the second option. Ignoring the warning is not a fix, because the coefficients may be far from the best ones.
Training behavior by model family
| Model family | How it learns | Scaling needed? | Common training problem |
|---|---|---|---|
| Linear and logistic regression | Closed form or gradient-based solver | Yes for gradient solvers and regularization | `ConvergenceWarning` |
| Decision tree | Greedy splits on feature thresholds | No | Grows until it memorizes the training set |
| Random forest, gradient boosting | Many trees combined | No | Too many deep trees or rounds |
| k-nearest neighbors | Stores the data, computes at prediction time | Yes | Slow prediction on large data |
| Neural network | Gradient descent on weights | Yes | Slow or unstable loss, sensitive settings |
Common errors
- Fitting on the wrong rows. Calling
fiton the full dataset, or on the test set, makes every later score meaningless. Fit only on the training rows. - Fitting preprocessing separately. If you call
fit_transformon the training data and again on validation data, the two sets get different scalings. Put preprocessing in the pipeline sofitruns it on training rows andpredictreuses the learned values. - Ignoring randomness. Splits, tree building, and stochastic solvers use random numbers. Set
random_stateso results can be reproduced, and remember that one seed gives one sample of how the model behaves. - Reading the training score as quality. A model can score near 100% on rows it has seen. Judge it on rows it has not.
- Class imbalance. With 2% positives, the optimizer can lower loss by predicting the majority class almost everywhere. Options are
class_weight="balanced", resampling, or a metric that reflects the imbalance. Compare against the baseline. - Unexpected state. Reusing one estimator object across experiments can carry over settings or, with
warm_start=True, fitted state. Create a fresh object, or usesklearn.base.clone, for each run. - Using the validation set for training. Once you refit on training plus validation data, you no longer have a validation score for that model. Do this only as a deliberate final step.
A checklist for a trained model
- The estimator was fitted only on training rows, inside a pipeline.
- No
ConvergenceWarningappeared, orn_iter_is belowmax_iter. - The model beats the baseline on the validation metric.
- Training and validation scores are close enough to proceed. If they are not, the next chapter explains why.
random_stateis set where randomness is involved.
Exercise
You fit LogisticRegression(max_iter=100) on unscaled features and get a ConvergenceWarning. Name two fixes, and say which one also keeps the model reliable when you add regularization.
Show answer
Scale the features with StandardScaler inside the pipeline, or raise maxiter. Scaling is the better fix for regularization, because a penalty on coefficients treats all coefficients alike, which is only fair when features share a comparable scale. Raising maxiter alone gives the solver more time but leaves the scale problem in place.
Exercise
A model scores 0.99 accuracy on the training rows and 0.93 on validation rows. The baseline scores 0.63 on validation. Is the model useful, and what should you check next?
Show answer
Yes. It beats the baseline by a wide margin. The 0.06 gap between training and validation is worth checking, so compare the two scores with cross-validation and look for overfitting, which the next chapter covers. Do not use the test set for this check.