Concept Explanation
Supervised learning is the part of machine learning where you already know the answers. You hand the algorithm a table of examples plus the correct output for each one, and it searches for a rule that maps input to output well enough to work on rows it has never seen.
The vocabulary is fixed and worth learning once:
| Term | Meaning |
|---|---|
Features (X) | The input columns — a 2-D array, shape (n_samples, n_features) |
Target (y) | The correct answer column — a 1-D array, shape (n_samples,) |
| Fit | Training: the model adjusts internal parameters to match X → y |
| Predict | Applying the trained rule to new X |
| Generalisation | Performing well on data not used in training — the only thing that matters |
Two Kinds of Problem
| Problem | Target is | Question | Example |
|---|---|---|---|
| Classification | A category | "Which one?" | Spam / not spam, digit 0–9 |
| Regression | A number | "How much?" | House price, tomorrow's demand |
That single distinction decides your model class, your loss function, and your metrics. Getting it wrong is the most common beginner error: predicting a price with a classifier throws away the ordering of the numbers entirely.
Scikit-learn's One Interface
Every estimator in scikit-learn — a linear model, a random forest, a neural net — exposes the same three methods:
model.fit(X_train, y_train) # learn
model.predict(X_test) # apply
model.score(X_test, y_test) # evaluate
This is the reason scikit-learn won. Swapping LogisticRegression() for RandomForestClassifier() is a one-word change; everything downstream is identical.
The Models You Should Know First
| Model | Type | When |
|---|---|---|
LinearRegression | Regression | A numeric target, roughly linear relationship |
LogisticRegression | Classification | Baseline classifier; fast, interpretable coefficients |
DecisionTreeClassifier | Both | Non-linear, human-readable rules, no scaling needed |
RandomForestClassifier | Both | Strong default on tabular data; hard to beat cheaply |
KNeighborsClassifier | Classification | Small datasets, decision boundary follows the data |
SVC | Classification | Medium data, clear margins between classes |
GradientBoosting / XGBoost | Both | Usually the winner on tabular competitions |
Start with LogisticRegression or RandomForest. A tuned simple model beats an untuned complex one more often than people expect.
Underfitting and Overfitting
This is the central tension of the whole field.
- Underfitting: the model is too simple. Training accuracy is bad and test accuracy is bad. Fix: more features, a more flexible model.
- Overfitting: the model memorised the training set. Training accuracy is excellent, test accuracy is poor. Fix: more data, fewer features, regularisation, a shallower tree.
train 0.62 / test 0.60 -> underfitting
train 0.99 / test 0.71 -> overfitting
train 0.88 / test 0.86 -> healthy
You cannot detect either without a held-out test set, which is why train_test_split is not optional.
Code Example #1 (Basic)
Classification and regression, side by side, on the same skeleton.
from sklearn.datasets import load_breast_cancer, fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression, LinearRegression
from sklearn.preprocessing import StandardScaler
# ---------- CLASSIFICATION: "malignant or benign?" ----------
data = load_breast_cancer()
X, y = data.data, data.target
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y # stratify keeps class balance
)
scaler = StandardScaler().fit(X_train) # fit on TRAIN only
clf = LogisticRegression(max_iter=2000)
clf.fit(scaler.transform(X_train), y_train)
print("Classification")
print(f" train accuracy: {clf.score(scaler.transform(X_train), y_train):.3f}")
print(f" test accuracy: {clf.score(scaler.transform(X_test), y_test):.3f}")
# ---------- REGRESSION: "how much is the house worth?" ----------
house = fetch_california_housing()
Xh, yh = house.data, house.target
Xh_train, Xh_test, yh_train, yh_test = train_test_split(
Xh, yh, test_size=0.2, random_state=42
)
reg = LinearRegression().fit(Xh_train, yh_train)
print("Regression")
print(f" train R2: {reg.score(Xh_train, yh_train):.3f}")
print(f" test R2: {reg.score(Xh_test, yh_test):.3f}")
# Which features push the price up the most?
for name, coef in sorted(zip(house.feature_names, reg.coef_),
key=lambda pair: abs(pair[1]), reverse=True)[:3]:
print(f" {name:<12} {coef:+.3f}")
Note what score() returns: accuracy for a classifier, R² for a regressor. Same method name, different metric — a small trap when you compare numbers across problem types.
Code Example #2 (Intermediate)
Comparing models honestly, and watching a tree overfit in real time.
import numpy as np
import pandas as pd
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
X, y = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0, stratify=y
)
# A pipeline bundles scaling + model so scaling can never leak across the split
candidates = {
"LogisticRegression": make_pipeline(StandardScaler(), LogisticRegression(max_iter=3000)),
"DecisionTree": DecisionTreeClassifier(random_state=0),
"RandomForest": RandomForestClassifier(n_estimators=300, random_state=0),
"KNN (k=5)": make_pipeline(StandardScaler(), KNeighborsClassifier(5)),
"SVC (rbf)": make_pipeline(StandardScaler(), SVC()),
}
rows = []
for name, model in candidates.items():
# 5-fold CV on the TRAINING set only -- the test set stays untouched
cv = cross_val_score(model, X_train, y_train, cv=5, scoring="accuracy")
model.fit(X_train, y_train)
rows.append({
"model": name,
"cv_mean": cv.mean().round(3),
"cv_std": cv.std().round(3),
"train": round(model.score(X_train, y_train), 3),
"test": round(model.score(X_test, y_test), 3),
})
results = pd.DataFrame(rows).sort_values("cv_mean", ascending=False)
print(results.to_string(index=False))
print()
# --- Watch overfitting appear as the tree gets deeper ---
print(f"{'depth':>6} {'train':>7} {'test':>7} gap")
for depth in [1, 2, 3, 5, 8, None]:
tree = DecisionTreeClassifier(max_depth=depth, random_state=0).fit(X_train, y_train)
tr = tree.score(X_train, y_train)
te = tree.score(X_test, y_test)
label = str(depth) if depth else "none"
print(f"{label:>6} {tr:>7.3f} {te:>7.3f} {tr - te:+.3f}")
The depth table is the lesson. At depth 1 both scores are poor — underfitting. With no depth limit, training accuracy hits 1.000 while test accuracy stalls: the tree has carved out a leaf for every training row. The gap column is overfitting, made numeric.
Common Mistakes
- Evaluating on the training set: 100% training accuracy proves only that the model can memorise. It says nothing about new data.
- Scaling before splitting:
StandardScaler().fit(X)on the full dataset leaks test-set statistics into training. Fit onX_train, thentransformboth — or use aPipelineand stop worrying. - Forgetting
stratify=yon imbalanced classification: a random split can put nearly all of a rare class on one side. - Using a classifier for a numeric target: predicting price as a "category" discards the fact that 200 is closer to 210 than to 900.
- Not scaling for distance-based models: KNN, SVC, and most linear models are dominated by whichever feature has the largest raw range. Trees and forests are immune.
- Judging on accuracy with imbalanced data: 99% of emails are not spam, so "always predict not-spam" scores 99%. Use precision, recall, or ROC-AUC.
- Tuning against the test set: try twenty configurations, pick the best test score, and that score is now optimistic. Tune with cross-validation; touch the test set once.
- Omitting
random_state: results shift every run and you cannot tell an improvement from noise. - Passing a 1-D array as
X: scikit-learn wants 2-D. Reshape withX.reshape(-1, 1)for a single feature.
Best Practices
- Split first, before anything else touches the data. Everything else is downstream of this one habit.
- Wrap preprocessing in a
Pipeline: it makes leakage structurally impossible rather than merely unlikely. - Always establish a baseline:
DummyClassifier(strategy="most_frequent")tells you the score to beat. If your model is close to it, you have learned nothing. - Report train and test together: a single number hides whether you are under- or overfitting.
- Prefer cross-validation to a single split on small data — one split of 100 rows is mostly luck.
- Set
random_stateeverywhere so a result is reproducible. - Start simple: logistic regression or a random forest, then justify anything more complex with measured improvement.
- Look at the coefficients or
feature_importances_: a model that scores well for an absurd reason is a bug you have not found yet. - Keep a locked test set and evaluate on it once, at the end.
Practice Exercises
- The Two Problems: Load
load_irisandfetch_california_housing. Train a classifier on the first and a regressor on the second, printing train and test scores for both. Write a comment explaining whyscore()means something different in each case. - The Overfitting Curve: Loop
max_depthfrom 1 to 15 on aDecisionTreeClassifierand record train and test accuracy at each depth. Plot both lines on one chart and mark the depth where the gap starts widening. - The Leak Hunt: Deliberately scale using
StandardScaler().fit(X)on the full dataset, then again correctly with aPipeline. Compare test scores across several random seeds and describe what the leak did to your estimate.