The Scikit-Learn Workflow

Updated · 5 min read
hardPython 3.13aimachine-learningscikit-learncross-validationpipelines

The scikit-learn workflow is a disciplined way to choose and evaluate a model: wrap preprocessing and the model in a pipeline, compare candidates with cross-validation on the training data, pick one, and only then measure it once on the test set. Following it keeps your accuracy numbers honest.

This lesson completes the chapter's checkpoint: predict late fee payments with two algorithms, and compare them.

Cross-Validation

Cross-validation splits the training data into k parts (here 5). Each part takes a turn as the validation set while the model trains on the other four, giving five scores instead of one. Their average is a steadier estimate, and their spread shows how much results vary.

Compare on training data; test the winner once
StepDescription
1. Split onceIt is used to lock away a test set for the final check
2. Build pipelinesIt is used to keep preprocessing and model together
3. Cross-validateIt is used to compare candidates using only training data
4. Choose and fitIt is used to train the winner on all the training data
5. Test onceIt is used to report the final, honest score

Example: The Checkpoint

This program uses payments_history.csv from "Supervised Learning".

Python
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
 
data = pd.read_csv("payments_history.csv")
X, y = data.drop(columns="late"), data["late"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
 
candidates = {
    "logistic regression": make_pipeline(StandardScaler(), LogisticRegression()),
    "random forest": RandomForestClassifier(n_estimators=200, min_samples_leaf=5, random_state=0),
}
for name, model in candidates.items():
    scores = cross_val_score(model, X_train, y_train, cv=5)   # 5 train/validate splits of the training data
    print(f"{name:20} cross-validated accuracy {scores.mean():.1%} (+/- {scores.std():.1%})")
 
best = candidates["logistic regression"].fit(X_train, y_train)   # chosen, then tested once
print(classification_report(y_test, best.predict(X_test), target_names=["on time", "late"], digits=2))
Output
logistic regression  cross-validated accuracy 89.9% (+/- 1.1%)
random forest        cross-validated accuracy 87.9% (+/- 0.7%)
              precision    recall  f1-score   support
 
     on time       0.91      0.98      0.94       214
        late       0.79      0.42      0.55        36
 
    accuracy                           0.90       250
   macro avg       0.85      0.70      0.74       250
weighted avg       0.89      0.90      0.89       250

Explanation: Both candidates are compared with 5-fold cross-validation using only the training data: logistic regression averages 89.9%, the random forest 87.9%. Logistic regression is chosen, trained, and tested once. The report shows the full picture: 90% accuracy overall, but for late families, recall is only 0.42: the model catches 42% of late payers, and 79% of the families it flags really are late (precision). The threshold from "Logistic Regression and Classification" is the next lever to pull.

Reading a Classification Report

MetricDescription
PrecisionIt is used to say how many flagged examples really are positive
RecallIt is used to say how many real positives were flagged
F1-scoreIt is used to combine precision and recall into one number
SupportThe number of real examples in each class

Common Mistakes

Choosing models by test-set score. Choose with cross-validation; test once.

Preprocessing outside the pipeline. Scaling or filling values on all data leaks test information.

Reporting accuracy alone on imbalanced data. Show precision and recall for the rare class.

Interview Corner

What is cross-validation, and why use it?

Splitting the training data into k folds and training k times, each time validating on a different fold. It gives a steadier estimate than one split and lets you compare models without touching the test set.

Why use scikit-learn pipelines?

To bundle preprocessing with the model so the same steps are fit on training data only and applied identically to new data, preventing leakage and mistakes.

Practice

Exercise: a third candidate. Add gradient boosting to candidates, and compare all three with cross-validation using scoring="recall". Does the ranking change when you care about catching late payers instead of accuracy?

Check your understanding:

  1. Why compare candidates with cross-validation instead of the test set?
  2. Which model won, and by how much?
  3. What does a late-class recall of 0.42 mean?

Quick check: the scikit-learn workflow

4 questions
1Which model had the higher cross-validated accuracy?
2How often should you evaluate on the test set?
3What does a late-class recall of 0.42 mean?
4What does a pipeline prevent?

Key Takeaways

Quick reference

NeedCode
Pipelinemake_pipeline(StandardScaler(), LogisticRegression())
Cross-validationcross_val_score(model, X_train, y_train, cv=5)
Full reportclassification_report(y_test, predicted)

Was this tutorial helpful?

Lesson 126 of 186