Freedom Sale
Independence Day Special — Unlock the AI Path 70% off our most popular AI course · Limited time offer
--Days
--Hrs
--Min
--Sec
Claim Your Discount
✦ Intermediate ⏱ 40 min

🔬 Build a Breast Cancer Classifier with scikit-learn

🎯 What You'll Build

A binary classifier that predicts whether a tumour is malignant or benign — with feature importance analysis, confusion matrix, and cross-validation.

📋 What You'll Need

1

Load and explore the dataset

The Wisconsin Breast Cancer dataset is built into scikit-learn — 569 samples, 30 features, binary target.

from sklearn.datasets import load_breast_cancer
import pandas as pd

data = load_breast_cancer()
df = pd.DataFrame(data.data, columns=data.feature_names)
df['target'] = data.target   # 0 = malignant, 1 = benign

print(df.shape)              # (569, 31)
print(df['target'].value_counts())
# 1    357  (benign)
# 0    212  (malignant)

print(df.describe().T[['mean','std','min','max']].head(5))
2

Train a Random Forest classifier

Split the data, train the model, and check accuracy.

from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
import numpy as np

X = data.data
y = data.target

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

# Pipeline: scale + classify
pipeline = Pipeline([
    ('scaler', StandardScaler()),
    ('clf',    RandomForestClassifier(n_estimators=100, random_state=42)),
])

pipeline.fit(X_train, y_train)

test_acc = pipeline.score(X_test, y_test)
print(f"Test accuracy: {test_acc:.4f}")   # ~0.9737

# 5-fold cross-validation for a reliable estimate
cv_scores = cross_val_score(pipeline, X, y, cv=5, scoring='accuracy')
print(f"CV accuracy:  {cv_scores.mean():.4f} +/- {cv_scores.std():.4f}")
Test accuracy: 0.9737
CV accuracy:  0.9649 +/- 0.0167
3

Confusion matrix and classification report

See exactly which tumours the model gets wrong.

from sklearn.metrics import classification_report, ConfusionMatrixDisplay
import matplotlib.pyplot as plt

y_pred = pipeline.predict(X_test)

print(classification_report(y_test, y_pred, target_names=['Malignant','Benign']))

fig, ax = plt.subplots(figsize=(5,4))
ConfusionMatrixDisplay.from_predictions(
    y_test, y_pred,
    display_labels=['Malignant','Benign'],
    cmap='Blues', ax=ax
)
plt.title('Breast Cancer Classifier — Confusion Matrix')
plt.tight_layout()
plt.savefig('confusion_matrix.png', dpi=120)
plt.show()
precision    recall  f1-score   support
   Malignant       0.98      0.95      0.96        42
      Benign       0.97      0.99      0.98        72
    accuracy                           0.97       114
4

Feature importance chart

Find which measurements matter most for the prediction.

import pandas as pd

rf          = pipeline.named_steps['clf']
importances = pd.Series(rf.feature_importances_, index=data.feature_names)
top10       = importances.nlargest(10)

plt.figure(figsize=(8,5))
top10.sort_values().plot(kind='barh', color='#1e3a5f')
plt.title('Top 10 Most Important Features')
plt.xlabel('Importance score')
plt.tight_layout()
plt.savefig('feature_importance.png', dpi=120)
plt.show()
print(top10)
💡 Tip: In cancer classification, recall for the malignant class (0) is more important than overall accuracy — a false negative (missed cancer) is far worse than a false positive. Adjust the threshold with pipeline.predict_proba(X_test)[:,0] > 0.3 to catch more malignant cases.

🎉 You Did It!

A 97% accurate cancer classifier in under 50 lines. The same Pipeline pattern — StandardScaler + Classifier — works for any tabular classification problem. Swap RandomForestClassifier for SVC, XGBClassifier, or LogisticRegression and compare accuracy.

Found something wrong?

Spotted a bug, broken code, or something that doesn't look right? Tell us what's off and we'll fix it.