A processing pipeline and cross-validation on breast cancer data
Training a classifier with feature scaling inside a pipeline to avoid data leakage.
Goal: Choosing model hyperparameters with cross-validation, then evaluating on a separate test set.
from sklearn.datasets import load_wine
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report
from sklearn.model_selection import GridSearchCV, train_test_split
X, y = load_wine(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, stratify=y, random_state=1)
grid = GridSearchCV(RandomForestClassifier(random_state=0),
{"n_estimators": [50, 150], "max_depth": [None, 4]}, cv=4, n_jobs=1)
grid.fit(X_tr, y_tr)
print("Best parameters:", grid.best_params_)
print(f"Cross-validation accuracy: {grid.best_score_:.3f}")
print(classification_report(y_te, grid.predict(X_te), digits=3))
We first split the data into training and test sets, run GridSearchCV on the training set only, then evaluate the best model once on the test set. Evaluating on the data used to choose the hyperparameters gives an optimistic estimate.
Best parameters: {'max_depth': None, 'n_estimators': 50}
Cross-validation accuracy: 0.970
precision recall f1-score support
0 0.938 1.000 0.968 15
1 1.000 0.944 0.971 18
2 1.000 1.000 1.000 12
accuracy 0.978 45
macro avg 0.979 0.981 0.980 45
weighted avg 0.979 0.978 0.978 45This example was actually run and tested on 21 November 2026 on a CPU — scikit-learn 1.9.1, python 3.13.18
Training a classifier with feature scaling inside a pipeline to avoid data leakage.
Computing the metrics that matter to a physician, not accuracy alone.
Searching for the best hyperparameters with the TPE algorithm instead of grid search.
Sections
No section has this name. Press “Search” to search all site content.
Favourites
My results & certificates
My academy progressMy quiz resultsKids’ progressAcademy certificatesQuiz certificatesStart any lesson or quiz and it will show up here so you can get back to it quickly.
Settings
I am the AI Frameworks & Libraries Assistant. Describe your project or ask me about a library, a comparison or a code example, and I will answer from the encyclopedia's database with links and sources.
Answers from the encyclopedia's database only, without a language model and without sending your question to any third party.
The assistant can make mistakes, so check the attached sources.