Artificial Intelligence Fundamentals / Learn From Labelled Data

Train and evaluate a classifier

Lesson 10 of 26. Open to read. No account needed.

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 sees y_test.
  • model.score(X_test, y_test) predicts and compares with the true labels in one call; for classifiers it returns accuracy.

Training features and labels go into fit, which produces a fitted model. Test features go into the fitted model's predict, which produces predicted labels. The predicted labels are compared with the test labels, which predict never saw, to give the score.

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.

  1. Create the exercise folder. macOS and Linux:

    mkdir -p ~/ai-practice/classify-wine
    cd ~/ai-practice/classify-wine
    

    Windows PowerShell:

    mkdir $HOME\ai-practice\classify-wine
    cd $HOME\ai-practice\classify-wine
    

    Save this as classify_wine.py in 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}")
    
  2. Run it:

    python classify_wine.py
    

    Illustrative 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.889
    

    The 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 seeLikely causeNext step
No convergence warningWarnings are switched off in your Python setup, or the model was changedCheck the script; the accuracy lines are what matters
The warning appears for the scaled model tooThe scaler is missing from that entryUse make_pipeline(StandardScaler(), LogisticRegression())
ValueError: X has 5 features, but ... is expecting 13 features as inputPredicting with data that has different columns from the training dataUse features with the same 13 columns, in the same order
Accuracies differrandom_state or stratify was changedRestore the split line
  1. Clean up. macOS and Linux:

    cd ~/ai-practice
    ls
    rm -rf classify-wine
    ls
    

    Windows PowerShell:

    cd $HOME\ai-practice
    ls
    Remove-Item -Recurse classify-wine
    ls
    

    Check that the first ls shows classify-wine before 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

  1. 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?
  2. What does a ConvergenceWarning from 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

  1. 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.
  2. 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 StandardScaler in a pipeline, or raise max_iter.

References

Study this course with an account

Course access adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

See course access

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy