🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Scikit-learn Workflow: Split, Fit, and Evaluate

Python MLModel TrainingđŸŸĸ Free Lesson

Scikit-learn Workflow: Split, Fit, and Evaluate

A machine learning script has a shape that stays the same no matter the dataset: you separate the data you are allowed to learn from the data you are allowed to be judged on, fit a transformation on the first part only, train a model, and then measure it with a metric that matches the actual cost of being wrong. Most "our model works in the notebook but not in production" stories are violations of one clause in that sentence — usually a scaler that saw the test set, a split that leaked duplicates, or an accuracy score on a dataset where 96 % of rows are the negative class.

This lesson walks that shape end to end with scikit-learn, explains why each step exists, and shows the pipeline form that makes the whole thing hard to get wrong.


Anatomy of a defensible experiment

Every sklearn experiment has the same five moving parts: a feature matrix, a target vector, a split, an estimator with a fit/predict contract, and a metric. The estimator contract is what makes the library composable — anything with fit and predict can be dropped into the same slot, which is exactly why the discipline of "fit on training only" can be enforced mechanically rather than by memory.

python
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report

df = pd.read_csv("churn.csv")
X = df.drop(columns=["churned"])
y = df["churned"].astype(int)

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

model = RandomForestClassifier(n_estimators=300, random_state=42, n_jobs=-1)
model.fit(X_train, y_train)
print(classification_report(y_test, model.predict(X_test), digits=3))

The stratify=y argument keeps the positive-class rate the same in both halves. Without it, a rare event can end up almost entirely in the test set — or worse, entirely in the training set, giving you a model that has never seen the failure mode you care about.

Why the split comes before any preprocessing

Fitting a scaler, an encoder, or a feature selector on the full dataset lets information from the test rows influence the training rows. The model then receives a slightly optimistic view of the world, and the reported score drifts upward by an amount that appears only after deployment. The same applies to duplicate customers, to rows collected in the same session, and to any target-derived feature.

python
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder

numeric = ["tenure", "monthly_charges", "support_tickets"]
categorical = ["plan", "region"]

preprocess = ColumnTransformer(
    transformers=[
        ("num", StandardScaler(), numeric),
        ("cat", OneHotEncoder(handle_unknown="ignore"), categorical),
    ]
)

pipe = Pipeline([
    ("prep", preprocess),
    ("model", RandomForestClassifier(n_estimators=300, random_state=42)),
])

# fit runs scalers on the training fold only, every single time
pipe.fit(X_train[numeric + categorical], y_train)
score = pipe.score(X_test[numeric + categorical], y_test)
print(f"held-out accuracy: {score:.3f}")

A Pipeline guarantees the ordering: nothing inside can be fitted until the previous step produces output, and the test data is only ever transformed with parameters learned from training. Cross-validation applied to a pipeline preserves the same guarantee per fold.

Picking metrics that reflect the cost of a mistake

Accuracy answers "how often was the label right", which is useless when classes are imbalanced or when false positives and false negatives have different prices. Choose the metric from the decision you will actually make with the model.

SituationMetricReason
Balanced classes, symmetric costAccuracySimple and comparable
Fraud or disease screening (rare positives)Recall at fixed precisionMissing a positive is expensive
Ranking a feed or search resultsAverage precision / PR-AUCRewards good ordering under skew
Probabilities feed a downstream thresholdLog loss / Brier scorePunishes confident wrong answers
Segments with wildly different base ratesMacro F1Averages per-class performance
Regression with occasional outliersMAEMedian-like, robust to spikes
python
from sklearn.model_selection import cross_validate
from sklearn.metrics import make_scorer, f1_score, precision_score, recall_score

scoring = {
    "accuracy": "accuracy",
    "f1": "f1",
    "precision": make_scorer(precision_score),
    "recall": make_scorer(recall_score),
}

results = cross_validate(
    pipe, X_train[numeric + categorical], y_train,
    cv=5, scoring=scoring, return_train_score=True,
)

for name in scoring:
    print(f"{name:10} train={results[f'train_{name}'].mean():.3f} "
          f"test={results[f'test_{name}'].mean():.3f}")

The gap between the printed train and test columns is your generalisation estimate. A tiny gap with poor scores means underfitting; a large gap means the model memorised patterns that the next batch of customers will not share.

Cross-validation instead of a single split

One split is one sample of a random process, and its score carries real variance — especially with small datasets. Five-fold cross-validation rotates the held-out fold across the data so every row is scored exactly once, giving a mean you can quote and a spread you can report alongside it.

python
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.ensemble import GradientBoostingClassifier

cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(
    GradientBoostingClassifier(random_state=42),
    X_train[numeric + categorical], y_train,
    cv=cv, scoring="f1",
)

print(f"F1 per fold: {[round(s, 3) for s in scores]}")
print(f"mean={scores.mean():.3f}  std={scores.std():.3f}")

If the per-fold numbers swing by more than a few points, the dataset is too small or too heterogeneous for a single headline figure — fix that before tuning hyperparameters, because tuning will happily optimise the noise.

When the minority class is the whole point

Class imbalance is not a cosmetic issue; it changes what a correct-looking model means. If only 4 % of customers churn, a model that always predicts "stays" scores 96 % accuracy and is worth nothing. Three levers address this, and they solve different problems. Resampling (changes the training distribution so the learner sees more positives), class weighting (penalises mistakes on the rare class more heavily, usually the cleanest option because no rows are invented), and thresholding (leaves the model alone and moves the decision boundary to match your cost ratio).

Threshold choice is the most underrated of the three. A model that outputs probabilities does not come with a decision rule; 0.5 is a convention, not a fact. If a missed positive costs you fifty times a false alarm, you should be drawing the line wherever that ratio implies, then reporting precision and recall at that threshold. Plot the precision-recall curve once, pick the operating point from the business cost, and write the chosen threshold into the configuration that serves the model so training and inference agree on what "positive" means.

Model selection without cheating the test set

Hyperparameter search must run inside cross-validation on the training data, and the test set should be touched exactly once, after every choice is frozen. Repeatedly checking the test score while you iterate turns it into a validation set, and your final number becomes a leaderboard-style overfit rather than an estimate.

python
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import randint

search = RandomizedSearchCV(
    pipe,
    param_distributions={
        "model__n_estimators": randint(100, 600),
        "model__max_depth": randint(3, 12),
        "model__min_samples_leaf": randint(1, 10),
    },
    n_iter=20, cv=cv, scoring="f1", random_state=42, n_jobs=-1,
)
search.fit(X_train[numeric + categorical], y_train)
print(search.best_params_)
print(f"best CV F1: {search.best_score_:.3f}")

# the single, final, honest evaluation
print(classification_report(y_test, search.predict(X_test[numeric + categorical]), digits=3))

Once you have written that final classification_report line, resist running it again after every tweak. If you need to iterate further, the test set has become validation data and you need a fresh holdout to get a trustworthy number.

Shipping the fitted object

A model is only useful if the exact transformation that produced it travels with the weights. Serialising the whole pipeline with joblib keeps scaler means, encoder categories, and trees in one artifact, so the serving code cannot accidentally apply a different preprocessing than the one the model was trained under.

python
import joblib

joblib.dump(search.best_estimator_, "churn_pipeline.joblib")
loaded = joblib.load("churn_pipeline.joblib")

new_rows = pd.DataFrame({
    "tenure": [14], "monthly_charges": [79.5], "support_tickets": [2],
    "plan": ["plus"], "region": ["north"],
})
print(loaded.predict_proba(new_rows)[:, 1])

Log the model version, the training data fingerprint, and the metrics next to the file. When a stakeholder asks why predictions changed last Tuesday, that metadata is the only thing standing between you and a full retrain to find out.

Common Mistakes

Fitting a scaler or encoder on the full dataset before splitting

Fix: Wrap preprocessing and the model in a Pipeline so each fold learns its own parameters

Reporting accuracy on a 4 % positive-rate problem

Fix: Use precision, recall, F1, or PR-AUC and state the threshold you chose

Tuning hyperparameters against the test set repeatedly

Fix: Search inside cross-validation on training data, then evaluate the test set once

Ignoring class imbalance with stratify omitted

Fix: Pass stratify=y and inspect class counts before and after the split

Serialising only the model and re-implementing preprocessing at serving time

Fix: Persist the entire pipeline artifact so training and inference share one code path

Best Practices

  • Set random_state everywhere a stochastic step exists so experiments are reproducible
  • Print train and test scores together — the gap is the most informative number in the report
  • Fit feature selection inside the pipeline, never on the whole frame up front
  • Freeze the metric and threshold before looking at test results
  • Version the trained artifact alongside the data snapshot and the metrics JSON

Key Takeaways

  • Split first, then fit every transformation on training data only
  • Pipelines make the correct ordering the default instead of a rule you must remember
  • Accuracy is the wrong metric whenever classes are imbalanced or costs are asymmetric
  • Cross-validation gives a mean and a spread; a single split gives neither
  • The test set is a one-time audit — touching it repeatedly converts it into validation data
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement