
































Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!

































Notation
Throughout this handout: m is the number of training examples, n the number of features, K the
number of classes. Superscripts in parentheses index examples, x⁽⁽⁽; subscripts index features, x⁽.
Vectors are column vectors; θ (or w, b) denotes model parameters; X ∈ ℝⁿ is the design matrix
whose i-th row is x⁽⁽⁽⁽. By convention x⁽ = 1 so that the bias can be absorbed into θ.
1.2 Why not linear regression for classification?
A natural first idea is to fit a linear regression model hθ(x) = θ⁽x to the 0/1 labels and predict y = 1
whenever hθ(x) ≥ 0.5. This approach works poorly for two reasons. First, the output of a linear model is
unbounded, while a class probability must lie in [0, 1]; outputs such as −3 or 7 have no probabilistic
meaning. Second, and more seriously, least squares penalises predictions that are "too correct": an
extreme positive example far from the boundary produces a large squared error even though it is
correctly classified, and it pulls the regression line towards itself, shifting the 0.5 threshold and causing
previously correct points to be misclassified. We need a model whose output saturates and a loss that is
appropriate for categorical targets. Logistic regression provides both.
1.3 Logistic regression
Logistic regression keeps a linear score z = θ⁽x but passes it through the logistic (or sigmoid ) function
σ, which squashes any real number into the interval (0, 1):
Figure 1.1. The sigmoid function. It is monotonic, equals 0.5 at z = 0 and saturates at 0 and 1 for large |z|.
The output is interpreted as the estimated conditional probability that the example belongs to the positive
class:
The sigmoid has a convenient derivative, σ'(z) = σ(z)(1 − σ(z)), which will simplify the gradient
computations below. It also has a clean probabilistic interpretation: inverting σ gives the log-odds or
logit ,
so logistic regression is a linear model of the log-odds. A unit increase in feature x⁽ multiplies the odds
of the positive class by e^θ⁽, which makes the coefficients directly interpretable, a property still highly
valued in medicine and finance.
To turn a probability into a hard prediction we threshold it, typically at 0.5:
Since σ(z) ≥ 0.5 exactly when z ≥ 0, the rule is equivalent to predicting ŷ = 1 when θ⁽x ≥ 0. The set of
points where θ⁽x = 0 is the decision boundary. In the original feature space this is a hyperplane: a
straight line in two dimensions, a plane in three. The decision boundary is a property of the model and its
parameters , not of the data set: the data are used to learn θ, and θ then determines the boundary.
For example, with two features and θ = (−3, 1, 1)⁽, the model predicts y = 1 whenever −3 + x⁽ + x⁽ ≥ 0,
i.e. above the line x⁽ + x⁽ = 3.
Logistic regression is a linear classifier, but it can learn non-linear decision boundaries if we feed it
non-linear features. Mapping x = (x⁽, x⁽) to φ(x) = (1, x⁽, x⁽, x⁽², x⁽x⁽, x⁽²) and learning θ in this
expanded space, a parameter vector such as θ = (−1, 0, 0, 1, 0, 1) yields the boundary x⁽² + x⁽² = 1, a
circle. Higher-degree polynomial features produce ever more complex boundaries, at the price of a
higher risk of overfitting (Chapter 2).
Figure 1.2. Left: a linear decision boundary learned by logistic regression on two Gaussian blobs. Right: a
circular boundary obtained by adding degree-2 polynomial features.
We now need a criterion to choose θ. Using the squared error of linear regression, J(θ) = (1/2m) Σ
(hθ(x⁽⁽⁽) − y⁽⁽⁽)², is a bad idea here: composing the squared error with the sigmoid yields a non-
or, in vectorised form, ∇J(θ) = (1/m) X⁽(σ(Xθ) − y). Remarkably, this has the same form as the gradient
of linear regression; the difference lies only in the definition of hθ. Batch gradient descent repeatedly
updates all parameters simultaneously:
where α > 0 is the learning rate. If α is too small convergence is slow; if it is too large the iterates
oscillate or diverge. Practical points:
of J more spherical and speeds up gradient descent considerably.
descent after small batches (typically 32–512 examples). They are noisier but far cheaper per step
and scale to very large data sets; they are the standard in deep learning.
converge in fewer iterations and do not require hand-tuning of α. Library implementations (for
example scikit-learn's LogisticRegression) use such solvers by default.
Figure 1.4. Gradient descent iterates on the contour plot of a convex cost. Steps are large where the gradient
is steep and shrink as the minimum is approached.
With many features, especially polynomial ones, logistic regression can overfit. As discussed in detail in
Chapter 2, we penalise large weights by adding a regularisation term to the cost (the bias θ⁽ is
conventionally not regularised):
Note that scikit-learn parameterises the strength by C = 1/λ: smaller C means stronger regularisation.
1.4 Softmax classification (multinomial logistic regression)
Logistic regression generalises naturally to K classes. Instead of a single parameter vector we learn one
vector θ per class, collected as the rows of a matrix Θ∈ ℝ⁽⁽⁽⁽ⁿ⁽¹⁽. For an input x we compute one
score, or logit , per class, s⁽(x) = θ⁽⁽⁽⁽x, and convert the vector of scores into a probability
distribution with the softmax function :
The softmax exponentiates the scores, which makes them positive, and normalises them so that they sum
to one. It is a "soft" version of the argmax: the class with the highest score receives the largest
probability, but all classes receive some mass. The predicted class is the most probable one, ŷ = argmax p
p⁽
= argmax⁽ s⁽(x). For K = 2 the softmax reduces exactly to the sigmoid, since e^s⁽/(e^s⁽ + e^s⁽) =
σ(s⁽ − s⁽).
The decision boundary between two classes k and j is the set where s⁽(x) = s⁽(x), i.e. (θ⁽⁽⁽ −
θ⁽⁽⁽)⁽x = 0, which is again a hyperplane; the input space is therefore partitioned into K convex,
piecewise-linear regions.
Cost function. The labels are encoded as one-hot vectors: y⁽⁽⁽⁽ = 1 if example i belongs to class k
and 0 otherwise. The cost is the categorical cross-entropy , again the negative log-likelihood, now of a
categorical (multinoulli) distribution:
Only the term of the true class survives the inner sum, so the cost is the average of −log of the probability
assigned to the correct class. Its gradient with respect to the parameters of class k has the familiar
"prediction minus target" form:
Numerical stability
Computing exp(s⁽) directly overflows for large scores. Since softmax is invariant to adding a
constant to all scores, implementations subtract the maximum score first: softmax(s) = softmax(s −
max⁽ s⁽). Likewise, frameworks compute log-softmax and cross-entropy together ("log-sum-exp
trick") rather than taking the log of a probability that may underflow to zero.
1.5 Classification examples
MNIST (Modified National Institute of Standards and Technology) is the most famous benchmark in
machine learning. It contains 70,000 grey-scale images of handwritten digits, split into 60,000 training
and 10,000 test images, written by US Census Bureau employees and high-school students. Each image
The Iris dataset, introduced by R. A. Fisher in 1936, contains 150 flowers of three species, Iris setosa ,
Iris versicolor and Iris virginica , 50 per class. Each flower is described by four measurements in
centimetres: sepal length, sepal width, petal length and petal width. The dataset is small, clean, balanced
and low-dimensional, which makes it perfect for visualising decision boundaries.
Figure 1.6. Left: in the sepal plane, setosa is linearly separable while versicolor and virginica overlap. Right:
softmax regression on the two petal features partitions the plane into three convex regions.
Two observations generalise to many real problems. First, one class is easy and two are hard : setosa is
perfectly separable, while versicolor and virginica overlap and are responsible for nearly all errors.
Second, feature choice matters more than the algorithm : the petal features separate the classes far better
than the sepal features. Softmax regression on the petal features typically reaches 95–97% accuracy on
held-out data.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
X, y = load_iris(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, stratify=y, random_state=42)
softmax = LogisticRegression(C=10, max_iter=1000).fit(X_tr, y_tr) print(softmax.predict_proba(X_te[:1])) # e.g. [[0.00, 0.03, 0.97]]
Note the use of stratify=y: with small data sets a random split can easily produce a test set with an
unrepresentative class distribution; stratification preserves the class proportions in both splits.
1.6 Evaluating classifiers
The simplest metric is accuracy , the fraction of correctly classified examples:
Accuracy is intuitive and adequate when classes are balanced and errors have similar costs. It is,
however, dangerously misleading on imbalanced problems. A "5-detector" that always answers "not 5"
achieves about 90% accuracy on MNIST without having learned anything. A fraud detector that never
flags a transaction is 99.9% accurate if 0.1% of transactions are fraudulent, and completely useless. We
need metrics that look at the two classes separately.
The confusion matrix counts, for each true class (rows), how many examples were assigned to each
predicted class (columns). For a binary problem it has four cells:
For K classes the matrix is K × K; the diagonal holds the correct predictions and the off-diagonal cells
reveal which classes are confused with which (on MNIST, typically 4↔9, 3↔5, 7↔9). Inspecting the
confusion matrix is the first step of error analysis.
Precision answers the question: of the examples the model labelled positive, how many really are?
Recall (also called sensitivity or true positive rate ) answers: of all the truly positive examples, how many
did the model find?
The trivial "never positive" classifier has recall 0, immediately exposing it. The two metrics capture
different costs, and the application determines which matters more:
many good videos (low recall) as long as the ones it lets through are safe.
very costly, while a false alarm can be resolved by a subsequent check.
The precision/recall trade-off. A probabilistic classifier produces a score and compares it to a
threshold. Raising the threshold makes the classifier more conservative: precision usually increases and
recall decreases. Lowering it does the opposite. Recall decreases monotonically with the threshold,
while precision may occasionally fluctuate. The threshold is therefore a design parameter to be chosen
on validation data according to the operating point required by the application, not necessarily 0.5.
The Receiver Operating Characteristic (ROC) curve plots the true positive rate (recall) against the
false positive rate , FPR = FP / (FP + TN), as the threshold varies. A random classifier lies on the
diagonal; a perfect classifier passes through the top-left corner. The area under the curve (ROC AUC)
summarises the curve in a single number between 0.5 (random) and 1 (perfect), and has an elegant
interpretation: it is the probability that a randomly chosen positive example receives a higher score than a
randomly chosen negative one. As a rule of thumb, prefer the precision-recall curve when the positive
class is rare or when false positives matter more than false negatives, because the ROC curve can look
deceptively good when TN is huge.
Precision, recall and F1 are defined per class by treating each class in turn as "positive" against the rest.
They are then aggregated:
performance on rare classes is emphasised.
single-label multi-class problems micro-averaged precision, recall and F1 all equal the accuracy.
In scikit-learn, classification_report(y_true, y_pred) prints per-class precision, recall, F1 and support together
with the averages, and ConfusionMatrixDisplay plots the confusion matrix.
Key takeaways
Logistic regression models the log-odds as a linear function and is trained by minimising the convex
cross-entropy cost, equivalent to maximum likelihood. Its decision boundary is a hyperplane in
feature space, which can become non-linear in the original space through feature engineering.
Softmax regression extends it to K classes. Never evaluate a classifier on accuracy alone: inspect the
confusion matrix and report precision, recall and F1, choosing the decision threshold according to
the cost of each error type.
2 Algorithm Analysis
A learning algorithm that scores 100% on its training data may still be useless. This chapter develops the
tools to understand why a model generalises or fails to, how to diagnose the problem from data, and how
to fix it systematically rather than by trial and error.
2.1 Training error, test error and generalisation
Let the data be drawn i.i.d. from an unknown distribution 𝒟. The training error (or empirical risk) is the
average loss on the training set; the generalisation error (or true risk) is the expected loss on a new
example drawn from 𝒟:
Learning minimises the training error, but what we care about is the generalisation error, which we
cannot compute because 𝒟 is unknown. We estimate it on a test set that the learning algorithm never
sees. Since the parameters were chosen to fit the training set, the training error is an optimistically biased
estimate; the gap E_gen − E_train is the generalisation gap. Two goals follow: make the training error
small, and make the gap small. Failing at the first is underfitting ; failing at the second is overfitting.
2.2 Model capacity
The capacity (or complexity , or expressiveness ) of a model is, informally, its ability to fit a wide variety
of functions. A linear model in two variables can only represent planes; a degree-15 polynomial can
wiggle through almost any set of points; a deep neural network with millions of parameters can
memorise random labels. Capacity is controlled by:
number of neighbours k, with capacity decreasing as k grows);
explores;
Statistical learning theory formalises capacity through quantities such as the Vapnik–Chervonenkis
(VC) dimension : the largest number of points that the hypothesis class can shatter , i.e. classify correctly
under every possible labelling. Linear classifiers in ℝⁿ have VC dimension n + 1. Theory yields bounds
of the form
which hold with high probability. The bounds are loose in practice, but they convey the two key
messages: the gap grows with capacity and shrinks as the amount of data grows. Capacity must therefore
be matched to the complexity of the true underlying function and to the amount of training data
available.
The three terms on the right-hand side are, respectively, the squared bias , the variance and the
irreducible noise :
assuming linearity when the data are quadratic. High bias causes underfitting.
size. High-capacity models are sensitive to small fluctuations in the data. High variance causes
overfitting.
data (cleaning, better sensors, more informative features).
Increasing capacity typically lowers bias and raises variance; the optimal model balances the two. Note
that modern heavily over-parameterised networks exhibit a "double descent" behaviour in which test
error can decrease again beyond the interpolation threshold; the classical U-curve remains, however, the
right mental model for most classical algorithms.
2.4 Learning curves
Plotting error against model capacity requires fixing the data set. The complementary diagnostic is the
learning curve : training and validation error plotted as a function of the training set size m, for a fixed
model. The procedure is simple: for increasing m, train on the first m examples, then measure the error
on those m examples and on a fixed validation set.
With very few examples, any model fits them perfectly, so the training error starts near zero and rises as
m grows, because it becomes harder to fit every point. Conversely, the validation error starts high, since
a model trained on a handful of points generalises poorly, and decreases with m. The shape of the two
curves tells us which regime we are in.
Figure 2.3. Learning curves. Left: high bias, where both curves plateau quickly at a high error, close to each
other. Right: high variance, with a large gap at small m that closes slowly as data are added.
Diagnosis Training
error
Validation error Gap Will more data help?
High bias
(underfitting)
High High Small No: the curves have already
converged
High variance
(overfitting)
Low Much higher Large Yes: the validation curve keeps
decreasing
Diagnosis Training
error
Validation error Gap Will more data help?
Good fit Low Low, close to the training
error
Small Only marginally
This table is extremely practical. Collecting more data is often expensive, and learning curves tell us in
advance whether it is worth it. If the model suffers from high bias, doubling the data set will not help at
all; effort should go into features and model capacity instead.
2.5 Regularisation
Regularisation is any modification to the learning algorithm intended to reduce generalisation error
without necessarily reducing training error. The most common form adds a penalty Ω(θ) on the size of
the parameters to the cost:
The hyperparameter λ ≥ 0 controls the strength: λ = 0 recovers the unregularised model, and λ → ∞
forces all penalised weights to zero, producing a constant prediction (underfitting). Between these
extremes lies a value that minimises validation error. The intuition is that models with small weights are
smoother, since small changes in the input produce small changes in the output, and therefore less able to
chase noise.
The gradient of the penalty is λθ, so each gradient-descent step becomes θ := θ(1 − αλ) − α ∇J(θ): before
the usual update, every weight is multiplied by a factor slightly smaller than one. Hence the name weight
decay. L2 shrinks all weights smoothly towards zero but rarely makes any exactly zero. For linear
regression it has a closed form, θ = (X⁽X + λI)⁽¹X⁽y, which also makes the matrix to invert well-
conditioned when features are collinear.
L1 regularisation tends to drive many weights exactly to zero, producing sparse models. This performs
automatic feature selection and is useful when we suspect that only a few features are relevant.
Geometrically, the L1 constraint region is a diamond whose corners lie on the axes, and the level sets of
the cost tend to first touch it at a corner. Elastic Net combines both penalties, r θ‖ ‖ ⁽ + (1 − r)½ θ‖ ‖ ⁽², and is
preferable to pure Lasso when features are strongly correlated.
best.
chosen model.
After selection, the chosen configuration is usually retrained on training plus validation data before the
final test. With very large data sets (millions of examples) validation and test sets of 1% each are
sufficient; what matters is their absolute size, not their percentage. Validation and test sets must come
from the same distribution as the data the model will face in production.
∈ {0.001, 0.01, 0.1, 1, 10} × degree ∈{1, 2, 3}. It is exhaustive but its cost grows exponentially
with the number of hyperparameters. Scale-type hyperparameters (λ, learning rate, C) should be
searched on a logarithmic grid.
it explores more distinct values of each individual hyperparameter, and since typically only a few
hyperparameters really matter, it often finds better configurations than grid search (Bergstra &
Bengio, 2012).
validation performance as a function of the hyperparameters and choose the next configuration to
evaluate intelligently. Successive halving / Hyperband allocate more budget to promising
configurations and abandon poor ones early.
A practical recipe is to start coarse (wide, logarithmic ranges), identify the promising region, then refine.
If the best value lies at the edge of the grid, extend the grid in that direction.
2.7 Cross-validation
A single validation split has two drawbacks: it wastes data that could be used for training, and with small
data sets the resulting estimate has high variance, since a different random split could lead to a different
choice. k-fold cross-validation addresses both.
The data (excluding the test set) are partitioned into k folds of approximately equal size. For each i = 1,
…, k, the model is trained on the k − 1 remaining folds and evaluated on fold i. The cross-validation
estimate is the average of the k scores:
Figure 2.5. Five-fold cross-validation. Each example is used for validation exactly once and for training k −
1 times.
Reporting the standard deviation of the k scores together with the mean gives an indication of the
estimate's reliability. Typical choices are k = 5 or k = 10, a good compromise between bias (small k trains
on less data, pessimistic estimates) and computational cost (k trainings). Variants include:
for classification in scikit-learn and essential with imbalanced classes.
used only for very small data sets.
them must end up in the same fold, otherwise information leaks between training and validation.
window); random shuffling would let the model see the future.
performance of the whole selection procedure. It gives an unbiased estimate when no separate test
set can be afforded.
Cross-validation combines naturally with grid search. In scikit-learn, GridSearchCV performs k-fold CV
for every configuration and refits the best one on all the training data:
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler, PolynomialFeatures
from sklearn.linear_model import LogisticRegression from sklearn.model_selection import GridSearchCV
pipe = make_pipeline(PolynomialFeatures(), StandardScaler(),
LogisticRegression(max_iter=5000)) grid = {"polynomialfeatures__degree": [1, 2, 3],
"logisticregression__C": [0.01, 0.1, 1, 10, 100]}
search = GridSearchCV(pipe, grid, cv=5, scoring="f1_macro", n_jobs=-1)
search.fit(X_train, y_train) print(search.best_params_, search.best_score_)
print(search.score(X_test, y_test)) # evaluated once, at the very end
Data leakage
Every preprocessing step that learns from data (scaling statistics, PCA, feature selection,
imputation) must be fitted inside each training fold, never on the full data set beforehand. Wrapping
preprocessing and model in a Pipeline guarantees this. Leakage is one of the most common causes of
results that look excellent in the lab and fail in production.