Reading history

End-to-End Machine Learning Project in Python

5 min read 2 views

Build a complete machine learning workflow in Python: split data, compare models with cross-validation, tune with GridSearchCV and evaluate on a test set.

This project brings the previous lessons together into one complete, realistic workflow: load data, set aside a test set, compare several models fairly with cross-validation, tune the best one, and only then measure it once on unseen data. The same steps apply to almost any tabular classification problem, from loan approval to customer churn. The example uses scikit-learn’s breast cancer dataset.

In this project you will practise

  • A clean train-test split with stratification
  • Comparing models with cross-validation
  • Pipelines that include scaling
  • Hyperparameter tuning with GridSearchCV
  • A final evaluation with a confusion matrix and classification report

Note: this is a teaching exercise with a public benchmark dataset. Real medical decisions need validated clinical tools and qualified professionals.

The Complete Script

import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.model_selection import GridSearchCV, cross_val_score, train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

# 1. Load the data
data = load_breast_cancer(as_frame=True)
X, y = data.data, data.target            # 0 = malignant, 1 = benign
print("Shape:", X.shape, "| benign share:", round(y.mean(), 2))

# 2. Hold back a test set and do not touch it until the end
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

# 3. Compare candidate models with cross-validation on the training set
candidates = {
    "Logistic regression": make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
    "KNN (k=7)": make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=7)),
    "Random forest": RandomForestClassifier(n_estimators=200, random_state=0),
}
for name, model in candidates.items():
    scores = cross_val_score(model, X_train, y_train, cv=5)
    print(f"{name:20s} CV accuracy {scores.mean():.3f}")

# 4. Tune the most promising model
search = GridSearchCV(
    make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
    param_grid={"logisticregression__C": [0.01, 0.1, 1, 10]},
    cv=5,
)
search.fit(X_train, y_train)
print("Best C:", search.best_params_["logisticregression__C"])

# 5. Final check on the untouched test set
best = search.best_estimator_
pred = best.predict(X_test)
print("Confusion matrix [rows = actual malignant, benign]:")
print(confusion_matrix(y_test, pred))
print(classification_report(y_test, pred, target_names=data.target_names, digits=3))

Output

Shape: (569, 30) | benign share: 0.63
Logistic regression  CV accuracy 0.980
KNN (k=7)            CV accuracy 0.971
Random forest        CV accuracy 0.956
Best C: 0.1
Confusion matrix [rows = actual malignant, benign]:
[[40  2]
 [ 1 71]]
              precision    recall  f1-score   support

   malignant      0.976     0.952     0.964        42
      benign      0.973     0.986     0.979        72

    accuracy                          0.974       114
   macro avg      0.974     0.969     0.972       114
weighted avg      0.974     0.974     0.974       114

Step by Step

1. Load and inspect

as_frame=True returns a pandas DataFrame with named columns. There are 569 samples and 30 numeric features, and 63% are benign, so the classes are moderately imbalanced. Always check the class balance first: here, a model that always said “benign” would already score 63%, and that is the baseline to beat.

2. Lock away the test set

The stratified split keeps 114 samples aside. Everything that follows, including model choice and tuning, uses only the training set, so the final score is an honest estimate.

3. Compare candidates fairly

Three different model families are scored with 5-fold cross-validation. Logistic regression and KNN get a StandardScaler inside their pipelines; the random forest does not need one. Logistic regression comes out on top, a reminder that simple models are often hard to beat on clean, well-measured data.

4. Tune the winner

GridSearchCV tries four values of the regularisation strength C. The parameter name logisticregression__C means “the C setting of the pipeline step called logisticregression“. The best value, 0.1, applies slightly more regularisation than the default of 1.0.

5. Evaluate once on the test set

The tuned model reaches 97.4% accuracy. The confusion matrix shows exactly what went wrong: 2 of the 42 malignant samples were predicted benign (missed cases) and 1 benign sample was flagged as malignant. In a screening setting the missed cases are the more serious error, so the next step would be to lower the threshold for calling a sample benign and accept a few more false alarms.

Taking It Further

ImprovementHow
Fewer missed casesUse predict_proba and a stricter threshold for “benign”
Score by recall instead of accuracyGridSearchCV(..., scoring="recall") with pos_label set correctly
Try gradient boostingSee the XGBoost lesson
Save and reuse the modeljoblib.dump(best, "model.joblib")
Serve predictionsWrap the pipeline in a small web API, following the ML lifecycle

Common Mistakes in ML Projects

  1. Looking at the test set early and then “fixing” the model to suit it.
  2. Not checking class balance, so a 63% score looks meaningful when it is only the baseline.
  3. Comparing models on different splits, which makes the comparison unfair.
  4. Stopping at accuracy instead of looking at which mistakes the model makes.

Practice Exercises

Exercise 1. Add a DummyClassifier(strategy="most_frequent") to the candidates. What score does it get, and why include it?

Show answer

About 0.63, the share of the majority class. A baseline shows how much real learning the other models do. If a model barely beats the dummy, something is wrong.

Exercise 2. Count how many malignant test samples are missed if you only call a sample benign when P(benign) > 0.9.

Show answer
p_benign = best.predict_proba(X_test)[:, 1]
pred_strict = (p_benign > 0.9).astype(int)
missed = ((y_test == 0) & (pred_strict == 1)).sum()
print("Missed malignant cases:", missed)

Compare the count with the default threshold, and also count the new false alarms.

Frequently Asked Questions

Why did the simple model beat the random forest?

The features are clean, numeric and strongly related to the label in a mostly linear way, so a linear model fits well and has little room to overfit. Forests shine more when relationships are non-linear or involve interactions between features.

Can I use this workflow for my own CSV file?

Yes. Load the file with pd.read_csv, separate the target column, add a ColumnTransformer for missing values and text categories, and keep the rest of the steps the same.

Summary

  • Split first and keep the test set untouched until the end.
  • Compare models with cross-validation on the training set, using pipelines.
  • Tune the best candidate with GridSearchCV.
  • Report the final result with a confusion matrix, not just accuracy.

Next: Gradient Boosting and XGBoost.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *