From Data to a Fair Score
The earlier lessons gave you every ingredient: labelled data, a fair split, a pipeline that keeps preprocessing honest and a baseline to beat. This lesson puts them together to train classifiers, models that predict a category, and to compare two different kinds fairly on the wine data.
Fit, Predict, Score
Every scikit-learn model follows the same three steps:
model.fit(X_train, y_train)learns from the training samples and their labels.model.predict(X_test)returns a predicted label for each new sample. It never seesy_test.model.score(X_test, y_test)predicts and compares with the true labels in one call; for classifiers it returns accuracy.

Follow the two inputs from the top. Training data enters only through fit.
Test features enter only through predict, and the test labels appear only at
the very end, in the comparison that produces the score. If test labels ever
reached fit, the score would no longer measure anything.
Two Kinds of Classifier
Logistic regression, despite its name, is a classifier. For each class it
learns one weight per feature and adds up the weighted features, then turns
the totals into probabilities and predicts the most likely class. Training
searches step by step for the weights that best fit the training labels. In
scikit-learn 1.9.1, LogisticRegression uses a search method called lbfgs
and stops after at most 100 steps, set by max_iter.
A decision tree, from the rules lesson, asks yes-or-no questions about the features. Without a depth limit it keeps asking questions until it classifies every training sample correctly, which, as the overfitting lesson will show, is not always a good thing.
Convergence Warnings
If logistic regression's search has not settled on its best weights after
max_iter steps, scikit-learn still returns a model but prints a
ConvergenceWarning. The model may then be weaker than it could be. The
warning itself suggests the two usual fixes: allow more steps, or scale the
data. Scaling usually works better, because features on very different
scales, such as the wine data's proline values in the hundreds or thousands and its hue
values around 1, make the search slow. A pipeline with StandardScaler, from
the leakage lesson, scales without leaking.
Exercise: Classify the Wines
You will train a baseline, logistic regression with and without scaling, and a decision tree, and compare their test accuracy.
Starting state: the course environment, active in your terminal. The wine data ships with scikit-learn.
-
Create the exercise folder. macOS and Linux:
mkdir -p ~/ai-practice/classify-wine cd ~/ai-practice/classify-wineWindows PowerShell:
mkdir $HOME\ai-practice\classify-wine cd $HOME\ai-practice\classify-wineSave this as
classify_wine.pyin that folder:"""Train two classifiers on the wine data and compare them with a baseline.""" from sklearn.datasets import load_wine from sklearn.dummy import DummyClassifier from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.tree import DecisionTreeClassifier X, y = load_wine(return_X_y=True) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0, stratify=y) models = { "baseline": DummyClassifier(), "logistic regression": LogisticRegression(), "scaled logistic regression": make_pipeline(StandardScaler(), LogisticRegression()), "decision tree": DecisionTreeClassifier(random_state=0), } for name, model in models.items(): model.fit(X_train, y_train) print(f"{name}: test accuracy {model.score(X_test, y_test):.3f}") -
Run it:
python classify_wine.pyIllustrative output; the path in the warning and the warning's exact position among the lines will differ:
baseline: test accuracy 0.400 .../sklearn/linear_model/_logistic.py:599: ConvergenceWarning: lbfgs failed to converge after 100 iteration(s) (status=1): STOP: TOTAL NO. OF ITERATIONS REACHED LIMIT Increase the number of iterations to improve the convergence (max_iter=100). You might also want to scale the data as shown in: https://scikit-learn.org/stable/modules/preprocessing.html ... logistic regression: test accuracy 0.933 scaled logistic regression: test accuracy 1.000 decision tree: test accuracy 0.889The four accuracy lines should match exactly. The warning appears once, while the unscaled logistic regression trains.
How the Script Works
The split. The wine data is split into 133 training and 45 test wines, stratified so that each grower keeps its share.
The models dictionary. models maps a readable name to an unfitted model.
DummyClassifier() is the baseline. LogisticRegression() uses the raw
measurements. make_pipeline(StandardScaler(), LogisticRegression()) scales
first, using statistics from the training wines only. The tree has
random_state=0 so that its training is repeatable.
The loop. For each name and model, fit trains on the training wines and
score reports test accuracy. The f-string {...:.3f} prints three decimals.
What the results show. The baseline predicts the most common grower for every wine and is right 18 times in 45, 0.400. Every real model beats it comfortably. The unscaled logistic regression stops at 100 steps with the warning and scores 0.933. The scaled version converges and scores 1.000 on these 45 wines. The tree scores 0.889 on test data although it classifies every training wine correctly, a gap the overfitting lesson examines. With 45 test wines, each mistake is worth about 0.022, so 0.933 against 1.000 means three mistakes against none, not a dramatic general difference.
If you replaced LogisticRegression() in the unscaled entry with
LogisticRegression(max_iter=5000), the warning would disappear, because the
search would have enough steps to settle. Scaling reaches the same goal with
far fewer steps.
Success: four accuracy lines that match, a single convergence warning from the unscaled model, and an explanation of why every model must be compared with the 0.400 baseline on the same test wines.
If something differs:
| What you see | Likely cause | Next step |
|---|---|---|
| No convergence warning | Warnings are switched off in your Python setup, or the model was changed | Check the script; the accuracy lines are what matters |
| The warning appears for the scaled model too | The scaler is missing from that entry | Use make_pipeline(StandardScaler(), LogisticRegression()) |
ValueError: X has 5 features, but ... is expecting 13 features as input | Predicting with data that has different columns from the training data | Use features with the same 13 columns, in the same order |
| Accuracies differ | random_state or stratify was changed | Restore the split line |
-
Clean up. macOS and Linux:
cd ~/ai-practice ls rm -rf classify-wine lsWindows PowerShell:
cd $HOME\ai-practice ls Remove-Item -Recurse classify-wine lsCheck that the first
lsshowsclassify-winebefore removing it. Do the independent task first.
Independent task: add lines to the end of the script that use the fitted
scaled logistic regression to predict the growers of the first three test
wines, X_test[:3], and print them beside their true labels, y_test[:3].
Predict whether they will match, given the model's test accuracy.
Check Your Understanding
- A colleague reports that their decision tree scores 1.000 on the wine data.
You discover they called
tree.score(X_train, y_train). Why is that score not a fair estimate? - What does a
ConvergenceWarningfrom logistic regression tell you, and what are the two usual fixes?
Answer and Reasoning
Independent task
scaled = models["scaled logistic regression"]
print("Predicted growers:", scaled.predict(X_test[:3]))
print("Actual growers: ", y_test[:3])
Both lines print [2 0 1]. The dictionary still holds the fitted pipeline,
so predict scales the three wines with the training statistics and returns
one grower per wine. They match, as expected from a model that classified all
45 test wines correctly; for a model with lower accuracy, some would differ.
Understanding check
- The tree was scored on the wines it learned from. A tree without a depth limit classifies its training data perfectly, so 1.000 says nothing about new wines. Its test accuracy, 0.889, is the fair estimate.
- The search for the best weights stopped at the step limit before settling,
so the model may be weaker than possible. Scale the features, for example
with
StandardScalerin a pipeline, or raisemax_iter.