Intermediate⏱ 26 min⚑ 90 XP🧩 5-question quiz

Supervised Learning: Regression and Classification

Learn how models learn from labelled examples: loss functions, linear and logistic regression from the inside, regularization, and your first scikit-learn models with honest baselines.


In Module 03 (Python for AI) you learned to load, clean and explore data with NumPy and pandas. Now we put that data to work. Supervised learning is the most widely used kind of machine learning: you show a model many examples where the right answer is known, and it learns a function that produces good answers for examples it has never seen. Spam filters, credit scoring, demand forecasting, medical risk scores and the click-through predictors behind most recommendation systems are supervised learning.

Even the largest language models start this way: next-token prediction is supervised learning where the "label" is the next token in real text. The core ideas you learn in this lesson (a model with parameters, a loss function, an optimizer and honest evaluation on held-out data) carry all the way to the frontier.

The setup: features, labels and a loss

Each example is described by features xx (inputs, such as a house's size and location) and a label yy (the answer, such as its sale price). A dataset of nn examples is usually stored as a matrix XX with shape nΓ—dn \times d for dd features, plus a vector yy of length nn.

There are two main kinds of supervised task:

TaskLabelExamples
RegressionA numberPrice, temperature, delivery time
ClassificationA categorySpam or not, tumour benign or malignant, which product category

A model is a function f(x;w)f(x; w) with adjustable parameters ww. A loss function measures how wrong one prediction is. Training means finding parameters that minimize the average loss over the training set. Generalization, performing well on new data, is what we actually care about, so we always evaluate on data the model did not train on.

Rendering diagram…

The diagram shows the loop at the heart of supervised learning: the model's parameters are repeatedly adjusted to reduce training loss, and only at the end is the model scored on a test set it has never seen. Keeping that test set untouched is what makes the final score honest; the evaluation lessons will make this precise.

Linear regression

The simplest regression model is a weighted sum of the features plus an intercept:

y^=w1x1+w2x2+β‹―+wdxd+b(inΒ matrixΒ form:Β y^=Xw+b)\hat{y} = w_1 x_1 + w_2 x_2 + \dots + w_d x_d + b \qquad \text{(in matrix form: } \hat{y} = Xw + b\text{)}

Training minimizes the mean squared error (MSE):

MSE(w,b)=1nβˆ‘i=1n(yiβˆ’y^i)2\mathrm{MSE}(w, b) = \frac{1}{n} \sum_{i=1}^{n} \left(y_i - \hat{y}_i\right)^2

Squaring makes all errors positive, punishes large errors much more than small ones, and gives a smooth bowl-shaped loss with a single minimum. For this loss there is a closed-form solution, the normal equation

w=(X⊀X)βˆ’1X⊀yw = (X^\top X)^{-1} X^\top y

(with a column of ones in XX for the intercept, and assuming X⊀XX^\top X is invertible), although libraries solve it with more numerically stable methods such as QR or SVD decompositions. For larger models without a closed form, we use gradient descent: compute the gradient of the loss with respect to each parameter and take a small step downhill.

Let's train one on a real medical dataset bundled with scikit-learn: predicting a measure of diabetes progression one year after baseline from ten measurements such as age, BMI and blood pressure.

import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.dummy import DummyRegressor
from sklearn.metrics import mean_absolute_error, r2_score

X, y = load_diabetes(return_X_y=True)          # 442 patients, 10 features
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)

baseline = DummyRegressor(strategy="mean").fit(X_train, y_train)
model = LinearRegression().fit(X_train, y_train)

for name, m in [("baseline (predict mean)", baseline), ("linear regression", model)]:
    pred = m.predict(X_test)
    print(f"{name:24s} MAE={mean_absolute_error(y_test, pred):6.1f}  R2={r2_score(y_test, pred):.3f}")

# The same weights from least squares, to show there is no magic
Xb = np.c_[np.ones(len(X_train)), X_train]
w = np.linalg.lstsq(Xb, y_train, rcond=None)[0]
print("intercept matches:", np.isclose(w[0], model.intercept_))

Output:

baseline (predict mean)  MAE=  58.3  R2=-0.000
linear regression        MAE=  45.1  R2=0.359
intercept matches: True

Read this carefully. The baseline that always predicts the training mean has an RΒ² of about zero by construction (RΒ² measures the fraction of variance explained relative to predicting the mean). Linear regression cuts the mean absolute error (MAE) from 58 to 45 and explains about 36% of the variance. That is useful but far from perfect, which is realistic for medical outcomes. Without the baseline, "MAE 45.1" would be uninterpretable. Always compare with a trivial baseline.

Interpreting the weights

Each weight says how much the prediction changes per unit change in that feature, holding the others fixed. That is interpretable, but beware two traps: weights are only comparable across features if the features are on the same scale, and when features are strongly correlated, individual weights can be unstable or even flip sign while predictions stay good. A weight is a statement about the model, not proof of a causal effect.

Classification with logistic regression

For a yes/no label we want a probability between 0 and 1. Logistic regression passes the linear score through the sigmoid function:

z=Xw+b,p=Οƒ(z)=11+eβˆ’z=P(y=1∣x)z = Xw + b, \qquad p = \sigma(z) = \frac{1}{1 + e^{-z}} = P(y = 1 \mid x)

Large positive scores give probabilities near 1, large negative scores near 0. Training minimizes log loss (binary cross-entropy):

LogLoss=βˆ’1nβˆ‘i=1n[yilog⁑pi+(1βˆ’yi)log⁑(1βˆ’pi)]\mathrm{LogLoss} = -\frac{1}{n} \sum_{i=1}^{n} \Big[ y_i \log p_i + (1 - y_i) \log (1 - p_i) \Big]

Why not just maximize accuracy? Accuracy only changes when a prediction crosses the 0.5 threshold, so it is flat almost everywhere and gives the optimizer no direction. Log loss changes smoothly with every probability and heavily punishes confident wrong answers, which also makes the output probabilities meaningful. It is the maximum-likelihood objective for a Bernoulli label, and the same cross-entropy loss trains neural network classifiers and language models. Its gradient is remarkably simple. For one example, the sigmoid's derivative is Οƒβ€²(z)=Οƒ(z)(1βˆ’Οƒ(z))=p(1βˆ’p)\sigma'(z) = \sigma(z)(1-\sigma(z)) = p(1-p), and the derivative of the loss with respect to pp is βˆ’yp+1βˆ’y1βˆ’p-\tfrac{y}{p} + \tfrac{1-y}{1-p}. Multiplying them, almost everything cancels:

βˆ‚β„“βˆ‚z=(βˆ’yp+1βˆ’y1βˆ’p)p(1βˆ’p)=pβˆ’y,βˆ‡wLogLoss=1nX⊀(pβˆ’y).\frac{\partial \ell}{\partial z} = \left(-\frac{y}{p} + \frac{1-y}{1-p}\right) p(1-p) = p - y, \qquad \nabla_w \mathrm{LogLoss} = \frac{1}{n} X^\top (p - y).

The gradient is just the prediction error, weighted by the inputs, which has the same form as the gradient of MSE for linear regression.

The code below trains logistic regression twice on a breast cancer dataset: once from scratch with gradient descent using exactly that gradient, and once with scikit-learn.

import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, stratify=y, random_state=0)

scaler = StandardScaler().fit(X_train)           # fit on training data only
Xtr, Xte = scaler.transform(X_train), scaler.transform(X_test)

def sigmoid(z):
    return 1 / (1 + np.exp(-z))

# Logistic regression by batch gradient descent on log loss (+ small L2)
w, b, lr, lam = np.zeros(Xtr.shape[1]), 0.0, 0.1, 1e-3
for step in range(2000):
    p = sigmoid(Xtr @ w + b)
    grad_w = Xtr.T @ (p - y_train) / len(y_train) + lam * w
    grad_b = np.mean(p - y_train)
    w -= lr * grad_w
    b -= lr * grad_b

acc_scratch = np.mean((sigmoid(Xte @ w + b) >= 0.5) == y_test)
clf = LogisticRegression(max_iter=1000).fit(Xtr, y_train)
print(f"from scratch: {acc_scratch:.3f}   scikit-learn: {clf.score(Xte, y_test):.3f}")
print("P(benign) for first 3 test patients:", clf.predict_proba(Xte[:3])[:, 1].round(3))

Both reach roughly 96% test accuracy (the exact numbers differ slightly because scikit-learn uses a different regularization strength and optimizer). Three details matter:

  • Scaling. Features range from fractions to thousands. Standardizing them (zero mean, unit variance) makes gradient descent converge far faster and makes regularization treat features fairly. The scaler is fit on the training set only; fitting it on all data would leak information about the test set.
  • Stratify. stratify=y keeps the class proportions equal in both splits, which matters for small or imbalanced datasets.
  • Probabilities, then decisions. predict_proba returns probabilities; predict applies a 0.5 threshold. In a cancer screen, missing a malignant tumour costs far more than a false alarm, so the right threshold is a business or clinical decision, not 0.5 by default. The model evaluation lesson covers choosing thresholds and checking whether probabilities are calibrated.

For more than two classes, softmax regression (multinomial logistic regression) generalizes the sigmoid to a probability distribution over KK classes; scikit-learn handles this automatically.

Regularization: preferring simpler models

With many features or few examples, a linear model can fit noise in the training data, producing large, unstable weights. Regularization adds a penalty on weight size to the loss:

RidgeΒ (L2):L=MSE+Ξ±βˆ‘jwj2LassoΒ (L1):L=MSE+Ξ±βˆ‘j∣wj∣\text{Ridge (L2):}\quad \mathcal{L} = \mathrm{MSE} + \alpha \sum_{j} w_j^2 \qquad\qquad \text{Lasso (L1):}\quad \mathcal{L} = \mathrm{MSE} + \alpha \sum_{j} |w_j|

Ridge shrinks all weights smoothly and handles correlated features gracefully. Lasso pushes some weights exactly to zero, performing feature selection. Elastic net mixes both. The strength Ξ±\alpha (alpha in scikit-learn) is a hyperparameter: a setting chosen by you, not learned from the training loss, and tuned on validation data. In scikit-learn's LogisticRegression the equivalent knob is C, which is the inverse of regularization strength, so smaller C means stronger regularization. Why regularization helps generalization is the subject of the next lesson.

Other model families, briefly

Linear models are only one inductive bias, meaning one set of assumptions about what the function looks like. Others you will meet in this module and beyond:

  • k-nearest neighbours: predict from the labels of the most similar training examples. No training, but slow prediction and sensitive to scaling.
  • Decision trees and ensembles: learn if-then rules; boosted tree ensembles are still the strongest default for tabular data (lesson 4 of this module).
  • Neural networks: stack many learned transformations; dominant for images, audio and text (Module 06, Deep Learning).

Common pitfalls and misconceptions

  • No baseline. A number without a baseline means nothing.
  • Evaluating on training data. Training error is optimistic, sometimes wildly so.
  • Fitting preprocessing on all data. Scalers, imputers and encoders must be fit on training data only. Pipelines (lesson 6) make this automatic.
  • Treating weights as causal effects. Correlation in observational data does not tell you what happens if you intervene.
  • Accuracy on imbalanced data. If 99% of cases are negative, a model that always says "negative" is 99% accurate and useless.

Hands-on exercise

  1. Run both code blocks above. Confirm your numbers are close to those shown.
  2. In the regression example, replace LinearRegression with Ridge(alpha=...) from sklearn.linear_model for alpha in [0.01, 0.1, 1, 10]. Record test MAE for each. Which works best, and why is choosing alpha by test score technically cheating? (Hint: you will fix this with cross-validation in lesson 3.)
  3. In the classification example, change the learning rate lr of the from-scratch model to 0.001 and 5.0. What happens to accuracy after 2,000 steps, and why?
  4. Use clf.predict_proba to compute predictions at thresholds 0.3, 0.5 and 0.7. Count how many malignant cases (label 0) are missed at each threshold.

Expected outcome: you see the baseline-versus-model gap, observe regularization changing results, connect learning rate to convergence, and see that the decision threshold trades one kind of error for another.

Key takeaways

  • Supervised learning fits a parameterized function to labelled examples by minimizing a loss, then judges it on held-out data.
  • Linear regression minimizes squared error and has a closed-form solution; logistic regression maps a linear score to a probability with the sigmoid and minimizes log loss.
  • Log loss, not accuracy, is the training objective because it is smooth and rewards well-calibrated probabilities.
  • Always compare with a trivial baseline, scale features for gradient-based models, and fit preprocessing on training data only.
  • Regularization (ridge, lasso) penalizes large weights; its strength is a hyperparameter tuned on validation data.

Why do regularized, simpler models often beat more flexible ones on new data, and how flexible should a model be? The next lesson answers that with the bias–variance tradeoff.

Further reading

  • James, Witten, Hastie, Tibshirani and Taylor, "An Introduction to Statistical Learning" (free online at statlearning.com): chapters on linear regression and classification.
  • scikit-learn User Guide, "Linear Models" section (scikit-learn.org).
  • Andrew Ng, Machine Learning Specialization (DeepLearning.AI and Stanford Online): course 1 covers linear and logistic regression with gradient descent.

Save your progress and earn XP

Create a free account to take the quiz, track progress and unlock badges.