Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Learning pathChoose and Tune a Model: Classic Algorithms to a Saved Pipeline
  1. 1
    K-Nearest Neighbours (KNN): Distance, k and Why Scaling Is a Must
  2. 2
    Naive Bayes: Prior Times Likelihood, a Spam Filter by Hand and GaussianNB
  3. 3
    Support Vector Machines (SVM): The Widest Road, C, Kernels and gamma
  4. 4
    Decision Trees: Gini, max_depth and Feature Importances on Rain in Australia
  5. 5
    Bagging and Random Forest: Many Shaky Trees, One Steady Answer
  6. 6
    Boosting: Residuals by Hand, AdaBoost, Gradient Boosting and XGBoost
  7. 7
    Voting and Stacking: Does a Team of Models Beat the Best One?
  8. 8
    Hyperparameter Tuning with GridSearchCV and RandomizedSearchCV
  9. 9
    Which Features Matter? Feature Importances, Permutation Importance and SHAP
  10. 10
    Project: The Classification Master Template, from Raw CSV to a Saved Model
  1. Blog
  2. /
  3. Machine Learning
  4. /
  5. Supervised Learning

Learning path: Choose and Tune a Model: Classic Algorithms to a Saved Pipeline · Step 10 of 10

Project: The Classification Master Template, from Raw CSV to a Saved Model

One notebook that takes Rain in Australia from raw CSV to a tested, saved model: six models auditioned on the same folds, the best two tuned, a 0.4 threshold picked from out-of-fold probabilities, and one test run with AUC 0.872.

Chaand Sheikh

·27 November 2026Model Selection and Tuning

What you will learn

  • Audition six classifiers on the same stratified folds with cross_validate
  • Tune only the best two, scoring F1 and ROC AUC together with refit="f1"
  • Choose a threshold from out-of-fold probabilities, before the test set
  • Test once, then save the whole pipeline with joblib

Before you start

  • Hyperparameter Tuning with GridSearchCV and RandomizedSearchCV
  • Cross-Validation: KFold and StratifiedKFold
  • ROC Curve, AUC and Choosing a Threshold

Think about a talent show. First come the auditions: six acts, each performing five rounds. Then the finals: only the top two get through, and they rehearse. And finally the big night: one show, in front of the real judges.

The rule that makes it fair: the judges see each act only once. If an act rehearsed in front of the judges, the score would mean nothing.

That's the whole template. The auditions are cross-validation on the training days. The finals are tuning. The big night is the test set, used once. In this project you'll put the last few topics together into one notebook you can reuse for any yes/no problem, here Rain in Australia (will it rain tomorrow?).

The classification master template Training days only (16,000) 1-2. Split,preprocess 3. Auditions6 models, 5 folds 4. Finalstune the top 2 5. Thresholdout-of-fold Test days (4,000): locked until step 6 6. Test once, AUC 0.872 save with joblib
Every choice (which model, which settings, which threshold) is made on the training days. The test days come out once, at the end.

Step 1: Load and split first

import warnings
warnings.filterwarnings("ignore")
import joblib
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import (
    train_test_split, StratifiedKFold, cross_validate,
    RandomizedSearchCV, GridSearchCV, cross_val_predict)
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from xgboost import XGBClassifier
from sklearn.metrics import (
    f1_score, recall_score, precision_score, roc_auc_score,
    RocCurveDisplay)

df = pd.read_csv("weatherAUS.csv")
df = df.dropna(subset=["RainTomorrow"])
df = df.sample(20_000, random_state=42)
X = df.drop(columns=["Date", "RISK_MM", "RainTomorrow"])
y = (df["RainTomorrow"] == "Yes").astype(int)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42)
print(X_train.shape, X_test.shape)
print(round(y_train.mean(), 2))
(16000, 21) (4000, 21)
0.22

20,000 random days keep every search to seconds. RISK_MM is tomorrow's rain, so it goes (the leak from Train-Test Split and Data Leakage), and so does the date. 16,000 days to learn from, 4,000 kept safe, and 22% of the training days are rainy.

Step 2: One preprocessing recipe

The two-lane recipe from Pipelines and ColumnTransformer: numbers get the median and a scaler, text gets the most frequent value and one-hot encoding. Build it once, reuse it in every model below.

num_cols = X.select_dtypes("number").columns
cat_cols = X.select_dtypes(exclude="number").columns
num_lane = Pipeline([
    ("impute", SimpleImputer(strategy="median")),
    ("scale", StandardScaler())])
cat_lane = Pipeline([
    ("impute", SimpleImputer(strategy="most_frequent")),
    ("onehot", OneHotEncoder(handle_unknown="ignore"))])
preprocess = ColumnTransformer([
    ("num", num_lane, num_cols),
    ("cat", cat_lane, cat_cols)])
print(len(num_cols), len(cat_cols))
16 5

Step 3: The auditions

Six contestants with their default settings: logistic regression, k-nearest neighbours, a decision tree, a random forest, an SVM and XGBoost. Plus one StratifiedKFold, so every contestant gets the very same five folds (see Cross-Validation).

models = {
    "LogReg": LogisticRegression(max_iter=1000),
    "KNN": KNeighborsClassifier(),
    "Tree": DecisionTreeClassifier(random_state=42),
    "Forest": RandomForestClassifier(random_state=42),
    "SVM": SVC(random_state=42),
    "XGBoost": XGBClassifier(random_state=42),
}
cv = StratifiedKFold(5, shuffle=True, random_state=42)

For each one, the loop builds preprocess + model, runs cross_validate with two scores, and stores the means:

scores = {}
for name, clf in models.items():
    pipe = Pipeline([("preprocess", preprocess),
                     ("clf", clf)])
    r = cross_validate(pipe, X_train, y_train, cv=cv,
        scoring=["f1", "roc_auc"], n_jobs=-1)
    scores[name] = [r["test_f1"].mean(),
                    r["test_roc_auc"].mean()]
board = pd.DataFrame(scores, index=["F1", "AUC"]).T
print(board.nlargest(6, "F1").round(3))
            F1    AUC
XGBoost  0.606  0.863
LogReg   0.588  0.863
SVM      0.585  0.859
Forest   0.557  0.862
KNN      0.527  0.802
Tree     0.508  0.685

Six models, five folds each: 30 fits. XGBoost leads on F1 with 0.606, logistic regression is second with 0.588, and both have AUC 0.863. The single decision tree comes last, F1 0.508 and AUC 0.685: one tree on its own overfits. All six were scored on the same folds, so the board is fair. The top two go to the finals.

Step 4: The finals, tune the best two

XGBoost gets a random search over the same 54-combination menu as in Hyperparameter Tuning, drawing 10. Logistic regression gets a full grid: four values of C times two class weights is only eight candidates.

xgb_menu = {"clf__n_estimators": [100, 200, 400],
            "clf__max_depth": [3, 5, 7],
            "clf__learning_rate": [0.03, 0.1, 0.3],
            "clf__scale_pos_weight": [1, 3]}
xgb_search = RandomizedSearchCV(
    Pipeline([("preprocess", preprocess),
              ("clf", XGBClassifier(random_state=42))]),
    xgb_menu, n_iter=10, cv=cv, scoring=["f1", "roc_auc"],
    refit="f1", n_jobs=-1, random_state=42)
lr_menu = {"clf__C": [0.01, 0.1, 1, 10],
           "clf__class_weight": [None, "balanced"]}
lr_search = GridSearchCV(
    Pipeline([("preprocess", preprocess),
              ("clf", LogisticRegression(max_iter=1000))]),
    lr_menu, cv=cv, scoring=["f1", "roc_auc"],
    refit="f1", n_jobs=-1)

One new thing: scoring is a list, so both F1 and AUC are recorded for every candidate. With more than one score, the search needs to know which one picks the winner, and refit="f1" says so. The results then live under mean_test_f1 and mean_test_roc_auc, and best_index_ points at the winning row.

searches = {"XGBoost": xgb_search, "LogReg": lr_search}
for name, s in searches.items():
    s.fit(X_train, y_train)
    i = s.best_index_
    f1 = s.cv_results_["mean_test_f1"][i]
    auc = s.cv_results_["mean_test_roc_auc"][i]
    print(name, "F1", round(f1, 3), "AUC", round(auc, 3))
    for k, v in s.best_params_.items():
        print("   ", k[5:], v)
XGBoost F1 0.64 AUC 0.869
    scale_pos_weight 3
    n_estimators 400
    max_depth 7
    learning_rate 0.03
LogReg F1 0.617 AUC 0.864
    C 0.1
    class_weight balanced

XGBoost goes from 0.606 to 0.64 F1, with AUC 0.869, and picks the same settings as the tuning article. (Its F1 there was 0.649 because those folds were not shuffled; different folds, slightly different means.) Logistic regression improves too, from 0.588 to 0.617, with C=0.1 and balanced class weights. XGBoost wins on both scores. And the test data still hasn't been touched.

ModelAudition F1Tuned F1Tuned AUC
XGBoost0.6060.640.869
Logistic regression0.5880.6170.864

Step 5: Choose the threshold before the test

The model gives every day a probability of rain, and by default it says "rain" at 0.5 or more. A day at 0.45 means no umbrella. But you can move that line, as in ROC Curve, AUC and Choosing a Threshold. At 0.4, the same day says rain.

To compare thresholds without touching the test set, we need honest probabilities for the training days. cross_val_predict gives out-of-fold probabilities: every training day is scored by a model trained on the other four folds, one that never saw it.

best = xgb_search.best_estimator_
proba = cross_val_predict(
    best, X_train, y_train, cv=cv,
    method="predict_proba")[:, 1]
scorers = [recall_score, precision_score, f1_score]
cols = ["recall", "precision", "F1"]
rows = {}
for t in [0.3, 0.4, 0.5, 0.6]:
    pred = proba >= t
    rows[t] = [f(y_train, pred) for f in scorers]
print(pd.DataFrame(rows, index=cols).T.round(2))
     recall  precision    F1
0.3    0.82       0.47  0.60
0.4    0.75       0.54  0.63
0.5    0.68       0.61  0.64
0.6    0.59       0.67  0.63

Lower the threshold and recall goes up while precision goes down. 0.5 has the best F1, 0.64. But if a missed rainy day bothers you more than a false alarm, a lower line pays off. We pick 0.4: it catches 75% of the rainy days, about three in four, at the price of more false alarms. That's a choice about costs, and it's made on training data only.

Step 6: The big night, test once

Everything is decided: XGBoost, its settings and a threshold of 0.4. Now the test days come out, once.

threshold = 0.4
p = best.predict_proba(X_test)[:, 1]
rows = {}
for t in [0.5, threshold]:
    pred = p >= t
    rows[t] = [f(y_test, pred) for f in scorers]
print(pd.DataFrame(rows, index=cols).T.round(2))
print("test AUC:", round(roc_auc_score(y_test, p), 3))
     recall  precision    F1
0.5    0.68       0.60  0.64
0.4    0.76       0.53  0.62
test AUC: 0.872

Test AUC 0.872, very close to 0.869 from the folds, so the model didn't just memorise the training days. At 0.4, recall is 0.76: about three in four rainy days caught, on days the model has never seen. F1 at 0.4 is a little lower than at 0.5 (0.62 against 0.64), exactly the trade we chose in step 5. We don't switch back now: changing the threshold after seeing the test score would turn the test set into a validation set.

fig, ax = plt.subplots(figsize=(4.5, 2.8))
RocCurveDisplay.from_estimator(best, X_test, y_test, ax=ax)
ax.plot([0, 1], [0, 1], "k--")
plt.savefig("roc_test.png", dpi=110, bbox_inches="tight")
plt.show()
ROC curve of the tuned XGBoost pipeline on the 4,000 test days. The curve rises steeply, passing a true positive rate of about 0.8 at a false positive rate near 0.25, and sits well above the dashed coin-flip diagonal. Legend: Pipeline (AUC = 0.87).
The ROC curve on the test set. The dashed line is a coin flip; the tuned pipeline sits far above it, AUC 0.87.

Save the whole pipeline

joblib.dump(best, "rain_model.joblib")
['rain_model.joblib']

One file holds the preprocessing and the model together. Load it with joblib.load("rain_model.joblib"), call predict_proba on raw rows, and apply your 0.4 threshold. The threshold isn't stored inside the pipeline, so keep it with the file.

Common mistakes

  • Preprocessing before the split. Split first; the pipeline fits its imputers and scaler inside each fold.
  • Different folds for different models. Make one cv object and pass it everywhere, or the leaderboard isn't fair.
  • Tuning every contestant. Audition with defaults, then spend tuning time on the top two.
  • Choosing the threshold on the test set. Use out-of-fold probabilities from the training days.
  • Saving only the model. Save the whole pipeline, or the raw rows at prediction time won't be prepared the same way.

Quick recap

StepToolRain in Australia
1. Splittrain_test_split(stratify=y)16,000 / 4,000 days, 22% rainy
2. PreprocessColumnTransformer16 number and 5 text columns
3. Auditionscross_validate, same foldsXGBoost 0.606, LogReg 0.588
4. Finalsrandom / grid search, refit="f1"XGBoost F1 0.64, AUC 0.869
5. Thresholdcross_val_predict0.4: recall 0.75 on train folds
6. Test once, saveroc_auc_score, joblib.dumpAUC 0.872, recall 0.76 at 0.4

Try it yourself

Add a seventh contestant, KNeighborsClassifier(n_neighbors=25), to models. Where does it land on the board?

The starter notebook (same steps, with to-dos), the finished notebook and weatherAUS.csv are in the StudyEasy AI Community, free to join.

Built this? Share your solution in the StudyEasy AI Community.

Join free on Skool →
← Previous
Which Features Matter? Feature Importances, Permutation Importance and SHAP
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Related articles
Linear Regression and the Cost Function: Draw a Line, Score It

Draw a straight line through six kids' ages and weights, measure every miss, and turn the misses into one score, the mean squared error. Then let np.polyfit find the line with the lowest score.

Gradient Descent Explained: Feel the Slope, Step Downhill

Instead of handing over the best line, let the computer walk to it: measure the slope of the cost, step downhill with a learning rate, repeat. Shown step by step on six kids' ages and weights.

Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags

Predict a yearly medical bill with scikit-learn's LinearRegression: first from age alone, then from every column inside a pipeline. Each coefficient reads like a price tag, and smoker_yes is by far the biggest.

Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat

Score a regression model honestly: MAE, MSE and RMSE from four darts, then the insurance model on 268 test people, a DummyRegressor baseline to beat, R-squared and adjusted R-squared, and a residual plot.

On this page
  • Step 1: Load and split first
  • Step 2: One preprocessing recipe
  • Step 3: The auditions
  • Step 4: The finals, tune the best two
  • Step 5: Choose the threshold before the test
  • Step 6: The big night, test once
  • Save the whole pipeline
  • Common mistakes
  • Quick recap
  • Try it yourself
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.