GNGiseldo Neo and Alana NeoBooks
Mathematical Foundations for Machine Learning3 / 8

What Is Learning?

In the previous chapter, we formalized a learning method as an algorithm that receives a sample and returns a hypothesis. This description clarifies as training is organized, but still leaves open the central question of this chapter: when can we affirm that there was learning?

Hitting the known examples is not enough. A program could store each pair of the sample and return the memorized response when it found exactly the same input. Your training error would be zero, but it would not know how to respond to a new input. Learning requires some form of generalization.

In this chapter, we will say that a method learns when using a finite sample to produce a hypothesis whose performance remains good in examples not yet observed, from the process of interest. This idea involves three elements:

  1. a measure of quality or error;
  2. a statement on data outside the sample;
  3. a probabilistic guarantee, because different samples can lead to different hypotheses.

Returning notation.

In supervised learning, we consider:

  • an entry space XX;
  • an output space YY;
  • an unknown distribution PP over X×YX\times Y;
  • a training sample
D={(xi,yi)}i=1N; D=\{(x_i,y_i)\}_{i=1}^{N};
  • a hypothesis class H\mathcal{H};
  • a loss function ℓ\ell;
  • a AA algorithm that produces
h^=A(D)∈H. \widehat{h}=A(D)\in\mathcal{H}.

In a deterministic model, we can assume y=f(x)y=f(x) for some target function ff. In noise problems, we work with the conditional distribution P(Y∣X=x)P(Y\mid X=x). The ideas of error and generalization are valid in both cases.

Empirical risk measures performance in the examples observed:

R^D(h)=1N∑i=1Nℓ(h(xi),yi). \widehat{R}_D(h) =\frac{1}{N}\sum_{i=1}^{N}\ell(h(x_i),y_i).

The expected risk measures the average performance in the generating process:

R(h)=E(X,Y)∼P[ℓ(h(X),Y)]. R(h) =\mathbb{E}_{(X,Y)\sim P} \bigl[\ell(h(X),Y)\bigr].

The first can be calculated from the training; the second is what really interests us, but it depends on an unknown distribution.

Learned as generalization.

A hypothesis generalizes when your error in new data is close to the error observed in the sample. Intuitively, we wish that

R(h^)≈R^D(h^). R(\widehat{h}) \approx \widehat{R}_D(\widehat{h}).

This approach does not occur automatically. The algorithm itself chose h^\widehat{h} after observing DD, so the hypothesis may have explored accidental sample details. The more flexible the H\mathcal{H} class, the greater its ability to adjust real patterns — and also noise.

Two types of failure help organize this discussion:

  • subajuste (underfitting): the class or training is too simple to capture the relevant pattern; the training and test errors tend to be high;
  • overfit (* overfitting*): the hypothesis adapts excessively to the sample; the training error is low, but the error in new data is high.

The goal is not to get the least training error at any cost. We want to balance adjustment and generalization capacity.

The test set does not participate in learning

If we repeatedly use test performance to choose features, hyperparameters or models, the test ceases to represent unseen data. These choices should be made with training and validation data; the test is reserved for the final evaluation.

The role of probability.

The sample is random. Two teams can collect NN examples of the same population and get different sets. Consequently, the algorithm can produce different hypotheses.

A guarantee of learning usually has the form:

PD(R(A(D))≤ε)≥1−δ, P_D\bigl(R(A(D))\leq\varepsilon\bigr) \geq1-\delta,

where:

  • ε\varepsilon is the error tolerance;
  • δ\delta is the maximum probability of warranty failure;
  • the probability is taken over the random choice of the sample DD.

We read the expression as follows: with the probability of at least 1−δ1-\delta, the algorithm returns a hypothesis whose risk does not exceed ε\varepsilon. In more general formulations, we compare R(A(D))R(A(D)) to the best achievable risk within H\mathcal{H}.

This is the origin of the expression probably approximately correct: “probably” refers to 1−δ1-\delta confidence and “approximately” to ε\varepsilon tolerance.

What determines the difficulty.

The amount of data required depends on several factors:

  • the desired precision, controlled by ε\varepsilon;
  • the desired confidence, controlled by δ\delta;
  • the complexity of the hypothesis class H\mathcal{H};
  • the noise level;
  • the quality and representativeness of the sample;
  • the loss function and the type of warranty sought.

Demanding lower error or higher confidence usually requires more examples. Very expressive classes also need more data so that we can distinguish generalizable patterns from accidental adjustments.

Three questions from the chapter.

The next sections will develop three supplementary questions.

  1. How to measure the discrepancy? We need to define error, loss and notion of proximity between a hypothesis and the desired behavior.
  2. When is the observed error reliable? We will study probabilistic guarantees that relate sample and population.
  3. How to estimate performance in practice? We will discuss divisions between training, validation and testing.

These questions connect theory and engineering. The theory provides conditions and limits; the experimental protocol produces evidence about a concrete model.

Motivating example.

Suppose a spam classifier hits 990990 from 1 0001\,000 training messages. The empirical error rate is

R^D(h)=101 000=0,01. \widehat{R}_D(h)=\frac{10}{1\,000}=0{,}01.

We still cannot conclude that your future error will be 1%1\%. Maybe the messages have been used to choose specific keywords, maybe the sample contains very similar messages or maybe the spam pattern has changed.

If we evaluate the classifier once in 2 0002\,000 independent test messages and find 6060 errors, the test estimate will be

R^test(h)=602 000=0,03. \widehat{R}_{\text{test}}(h) =\frac{60}{2\,000} =0{,}03.

The difference between 1%1\% in training and 3%3\% in the test suggests a generalization gap. To interpret the uncertainty of this estimate, we will need probabilistic tools.

Preparation exercises.

  1. Explain why memorizing a sample is not enough to characterize learning.
  2. Differentiate empirical risk and expected risk.
  3. Give an example of underfit and one of overfit.
  4. Interpret ε\varepsilon and δ\delta in a probabilistic warranty.
  5. Why does repeatedly evaluate in the test set compromise your function?
  6. In the example of spam, cite two possible causes for the difference between training and testing errors.

2.1 Error

Learning requires comparing predictions with observed results. This comparison is made by a loss function, which translates the quality of a prediction into a number. The lower the loss, the better the prediction according to the chosen criterion.

There is not a single notion of error appropriate for all problems. Mistake of a class is different from missing a continuous amount; in some applications, certain errors have far more serious consequences than others. The loss function is part of the formulation and should reflect the actual purpose of the system.

2.1.1 Per-example loss, risk, and metrics

The loss for example compares a y^\widehat{y} prediction with the yy target :

ℓ ⁣:Y^×Y→[0,∞). \ell\colon\widehat{Y}\times Y\to[0,\infty).

empirical risk aggregates the losses in the sample:

R^D(h)=1N∑i=1Nℓ(h(xi),yi). \widehat{R}_D(h) =\frac{1}{N}\sum_{i=1}^{N} \ell(h(x_i),y_i).

A evaluation metric summarizes some aspect of the model’s behavior, such as accuracy, accuracy, recall or mean absolute error. Some metrics can be used as a training objective; others are difficult to optimize directly and serve mainly for evaluation.

The algorithm can minimize an objective with empirical risk and regularization:

J(θ)=R^D(hθ)+λΩ(θ). J(\theta) =\widehat{R}_D(h_\theta)+\lambda\Omega(\theta).

We will use loss for an example, risk for a loss average and target for the quantity effectively optimized.

2.1.2 Classification: zero-one loss

In classification, the zero-one loss is 00 for a hit and 11 for an error:

ℓ0/1(y^,y)=1[y^≠y]. \ell_{0/1}(\widehat{y},y) =\mathbb{1}[\widehat{y}\neq y].

Its empirical risk is the rate of incorrect classifications:

R^0/1(h)=1N∑i=1N1[h(xi)≠yi]. \widehat{R}_{0/1}(h) =\frac{1}{N}\sum_{i=1}^{N} \mathbb{1}[h(x_i)\neq y_i].

If a classifier misses 1818 of 300300 examples, then R^0/1(h)=18/300=0,06\widehat{R}_{0/1}(h)=18/300=0{,}06 and its accuracy is 0,940{,}94.

The zero-one loss directly expresses the amount of errors, but is discontinuous. Therefore, many algorithms train with differentiable substitute losses.

2.1.3 Confusion matrix

In binary classification there are four results:

Target yyPrediction y^\widehat{y}Name
positivepositivetrue positive (VP)
negativenegativetrue negative (VN)
negativepositivefalse positive (FP)
positivenegativefalse negative (FN)

From these counts we calculate

precisa~o⁡=VPVP+FP,revocac\ca~o⁡=VPVP+FN \operatorname{precisão} =\frac{VP}{VP+FP}, \qquad \operatorname{revocação} =\frac{VP}{VP+FN}

e

especificidade⁡=VNVN+FP. \operatorname{especificidade} =\frac{VN}{VN+FP}.

Accuracy answers: among the positive predictions, how many were correct? Revocation answers: among the really positive cases, how many were detected?

When classes are very unbalanced, accuracy can be misleading. If only 1%1\% of transactions are fraudulent, predicting “no fraud” for all produces 99%99\% of accuracy and no ability to detect fraud.

2.1.4 Asymmetric costs

False positives and false negatives may have different costs:

ℓ(y^,y)={0,y^=y,cFP,y^=1 and y=0,cFN,y^=0 and y=1. \ell(\widehat{y},y) = \begin{cases} 0, & \widehat{y}=y,\\ c_{FP}, & \widehat{y}=1 \text{ and } y=0,\\ c_{FN}, & \widehat{y}=0 \text{ and } y=1. \end{cases}

The corresponding empirical risk is

R^D(h)=cFPFP+cFNFNN. \widehat{R}_D(h) =\frac{c_{FP}FP+c_{FN}FN}{N}.

In authentication, accepting an unauthorized person may be more serious than asking the authorized person to try again. In sorting, no longer signaling an urgent case may be more serious than forwarding a non-urgent case. Costs should represent consequences of the context.

2.1.5 Regression: residual

In regression, the residual example ii is

ri=h(xi)−yi. r_i=h(x_i)-y_i.

ri>0r_i>0 indicates overestimation and ri<0r_i<0 indicates underestimation. A loss turns this residual into a non-negative penalty.

Absolute loss grows linearly with the residual; quadratic growth grows faster; logistics decreases as the correct margin increases.

Figure 2.1. Absolute loss grows linearly with the residual; quadratic growth grows faster; logistics decreases as the correct margin increases.

2.1.6 Mean squared error

The squared loss is

ℓquad(y^,y)=(y^−y)2. \ell_{\text{quad}}(\widehat{y},y) =(\widehat{y}-y)^2.

The average squared error (* mean squared error*, MSE) is

MSE⁡(h)=1N∑i=1N(h(xi)−yi)2. \operatorname{MSE}(h) =\frac{1}{N}\sum_{i=1}^{N} \bigl(h(x_i)-y_i\bigr)^2.

Large errors receive disproportionate penalty. A 33 magnitude residual contributes 99, while three 11 magnitude residuals contribute 33 in total. This makes the MSE sensitive to extreme values.

The root of the MSE,

RMSE⁡(h)=MSE⁡(h), \operatorname{RMSE}(h) =\sqrt{\operatorname{MSE}(h)},

It has the same unit as the target.

2.1.7 Mean absolute error

The absolute loss is

ℓabs(y^,y)=∣y^−y∣. \ell_{\text{abs}}(\widehat{y},y) =|\widehat{y}-y|.

The mean absolute error (* mean absolute error*, MAE) is

MAE⁡(h)=1N∑i=1N∣h(xi)−yi∣. \operatorname{MAE}(h) =\frac{1}{N}\sum_{i=1}^{N} |h(x_i)-y_i|.

The EAM grows linearly and is less sensitive to extreme observations than the SEM. For waste (1,1,4)(1,1,4),

MAE⁡=2,MSE⁡=6. \operatorname{MAE}=2, \qquad \operatorname{MSE}=6.

The magnitude error 44 exerts a much greater influence on the MSE.

2.1.8 Huber Loss

The loss of Huber combines quadratic behavior close to zero and linear behavior for large waste:

ℓδ(r)={12r2,∣r∣≤δ,δ(∣r∣−12δ),∣r∣>δ. \ell_\delta(r) = \begin{cases} \frac{1}{2}r^2, & |r|\leq\delta,\\[4pt] \delta\left(|r|-\frac{1}{2}\delta\right), & |r|>\delta. \end{cases}

The δ\delta parameter determines the transition. This loss keeps smoothness close to the minimum and reduces the influence of very discrepant values.

2.1.9 Classes encoded by −1-1 and +1+1

If y,y^∈{−1,+1}y,\widehat{y}\in\{-1,+1\}, then

(y^−y)2={0,y^=y,4,y^≠y. (\widehat{y}-y)^2 = \begin{cases} 0, & \widehat{y}=y,\\ 4, & \widehat{y}\neq y. \end{cases}

Therefore, squared loss is four times zero-one loss in this specific case. It is not worth 11 when there is error. If the model produces a real score, squared loss also considers the distance from punctuation to label.

2.1.10 Probabilities and binary cross-entropy

Consider y∈{0,1}y\in\{0,1\} and a p=h(x)∈(0,1)p=h(x)\in(0,1) prediction. The binary cross-entropy is

ℓBCE(p,y)=−[ylog⁡p+(1−y)log⁡(1−p)]. \ell_{\text{BCE}}(p,y) =-\bigl[y\log p+(1-y)\log(1-p)\bigr].

If y=1y=1, the loss is −log⁡p-\log p; if y=0y=0, it is −log⁡(1−p)-\log(1-p). A confident and wrong prediction gets big loss:

−log⁡(0,9)≈0,105,−log⁡(0,01)≈4,605. -\log(0{,}9)\approx0{,}105, \qquad -\log(0{,}01)\approx4{,}605.

This loss assesses the probability attributed to the observed result, not just the final class.

2.1.11 Maximum likelihood

For i.i.d. examples and a Pθ(Y=y∣X=x)P_\theta(Y=y\mid X=x) model , likelihood is

L(θ)=∏i=1NPθ(Y=yi∣X=xi). L(\theta) =\prod_{i=1}^{N} P_\theta(Y=y_i\mid X=x_i).

Maximum likelihood chooses parameters that maximize L(θ)L(\theta). As logarithm is strictly increasing,

argmax⁡θ  L(θ)=argmax⁡θ  log⁡L(θ). \underset{\theta}{\operatorname{argmax}}\;L(\theta) = \underset{\theta}{\operatorname{argmax}}\;\log L(\theta).

To write the training as minimization, we use the mean negative log-likeness:

NLL⁡(θ)=−1N∑i=1Nlog⁡Pθ(Y=yi∣X=xi). \operatorname{NLL}(\theta) =-\frac{1}{N}\sum_{i=1}^{N} \log P_\theta(Y=y_i\mid X=x_i).

For a Bernoulli model, NLL coincides with binary cross-entropy.

Transformations and great points

A strictly growing transformation preserves minimum and maximum. A strictly decreasing transformation maximum exchange by minimum. Thus, log⁡\log preserves the maximum likelihood; −log⁡-\log converts this maximum to minimum.

2.1.12 Multiclass cross-entropy

For KK classes, the model produces p=(p1,…,pK)\mathbf{p}=(p_1,\ldots,p_K) with pk≥0p_k\geq0 and ∑kpk=1\sum_kp_k=1. If the correct class is yy, the loss is

ℓ(p,y)=−log⁡py. \ell(\mathbf{p},y)=-\log p_y.

With target * one-hot* y\mathbf{y},

ℓ(p,y)=−∑k=1Kyklog⁡pk. \ell(\mathbf{p},\mathbf{y}) =-\sum_{k=1}^{K}y_k\log p_k.

This is the usual loss for trained multiclass class classifiers with * softmax*.

2.1.13 Margin-based losses

In binary classification with y∈{−1,+1}y\in\{-1,+1\} and s(x)∈Rs(x)\in\mathbb{R} score, we set the margin

m=y s(x). m=y\,s(x).

Positive margin indicates correct classification; negative margin indicates error.

ℓlog(m)=log⁡(1+e−m). \ell_{\text{log}}(m)=\log(1+e^{-m}).

It decreases smoothly as the correct margin increases. We can optimize cross-entropy and evaluate accuracy, accuracy, recall and calibration.

2.1.14 Choosing a Loss

SituationCommon optionFeature
Regression with approximately symmetrical noiseMSEheavily penalizes big mistakes
Return with extreme valuesMAE or Hubergreater robustness
Binary probabilistic classificationbinary cross-entropyevaluates probabilities
Multiclass classificationcross-entropypenalizes low probability of correct class
Different costs between errorsweighted lossincorporates asymmetry

The choice should consider the type of output, the consequences of errors, extreme values, properties required for optimization and the metric of interest. No loss corrects inadequate data or replaces outside of the sample.

2.1.15 Computing example

def mse(predictions, targets):
    errors = [(p - y) ** 2 for p, y in zip(predictions, targets)]
    return sum(errors)/len(errors)


Def mae(predictions, targets):
    errors = [abs(p - y) for p, y in zip(previews, targets)]
    return sum(errors)/len(errors)


y = [10, 12, 14]
pred = [11, 13, 18]

print(mse(pred, y)) #6.0
print(mae(pred, y)) # 2.0

In production, we should also check lengths, missing values, numerical types and behavior when the sample is empty.

2.1.16 Practice exercises

  1. A classifier obtained VP=80VP=80, VN=900VN=900, FP=20FP=20 and FN=100FN=100. Calculate accuracy, accuracy and recall.
  2. For (2,−1,−3)(2,-1,-3) waste , calculate MAE, MSE and RMSE.
  3. Explain why squared loss is worth 44, not 11, when y=−1y=-1 and y^=+1\widehat{y}=+1.
  4. Calculate binary cross-entropy for y=1y=1 with p=0,8p=0{,}8 and with p=0,2p=0{,}2.
  5. Show why maximizing L(θ)L(\theta) is equivalent to minimizing −log⁡L(θ)-\log L(\theta).
  6. Give an example in which cFN>cFPc_{FN}>c_{FP} and another in which cFP>cFNc_{FP}>c_{FN}.
  7. When would you prefer MAE to MSE?
  8. Explain the difference between training loss and evaluation metric.

2.2 Probably Right.

The theory probably roughly correct, abbreviated by PAC (* probably approximately correct*), transforms the idea of generalization into a mathematical guarantee. It recognizes two inevitable limitations:

  • a finite sample does not perfectly determine the behavior of the entire population;
  • as the sample is random, some samples may be unrepresentative.

Instead of demanding certainty and perfection, we fixed a ε\varepsilon error tolerance and a δ\delta failure probability. We asked how many examples are needed for the algorithm to produce a good enough hypothesis with high probability.

In the PAC warranty, at least one fraction 1-\delta of the samples leads the algorithm to a hypothesis whose error is at most \varepsilon.

Figure 2.2. In the PAC warranty, at least one fraction 1−δ1-\delta of the samples leads the algorithm to a hypothesis whose error is at most ε\varepsilon.

2.2.1 Two sources of probability

Consider a PP distribution over X×YX\times Y and a hh hypothesis. Your risk is

RP(h)=E(X,Y)∼P[ℓ(h(X),Y)]. R_P(h) =\mathbb{E}_{(X,Y)\sim P} \bigl[\ell(h(X),Y)\bigr].

In the zero-one loss rating,

RP(h)=P(X,Y)∼P(h(X)≠Y). R_P(h) =P_{(X,Y)\sim P}\bigl(h(X)\neq Y\bigr).

This probability is about a new example drawn from PP. It measures the region of the population in which hh err.

The algorithm receives a random sample

D=((x1,y1),…,(xN,yN))∼PN D=((x_1,y_1),\ldots,(x_N,y_N)) \sim P^N

and returns A(D)A(D). As DD varies, the hypothesis also varies.

PD∼PN(RP(A(D))≤ε)≥1−δ P_{D\sim P^N} \bigl(R_P(A(D))\leq\varepsilon\bigr) \geq1-\delta

contains a second probability, now on the draw of the entire sample. It states that at most a fraction δ\delta of the samples leads to a hypothesis whose risk exceeds ε\varepsilon.

Do not confuse $\varepsilon$ and $\delta$

ε\varepsilon limits the error of hypothesis in the population. δ\delta limits the probability of the training procedure not achieving this guarantee. One acts within each hypothesis; the other acts on the possible samples.

2.2.2 Reading “probably approximately correct”

In inequality

PD(RP(A(D))≤ε)≥1−δ, P_D\bigl(R_P(A(D))\leq\varepsilon\bigr) \geq1-\delta,

each word has a role:

  • probably: the desired event occurs with probability of at least 1−δ1-\delta;
  • approximately: we admit error up to ε\varepsilon;
  • Correct**:** error is measured in relation to the distribution of interest, not only in the training sample.

If ε=0,05\varepsilon=0{,}05 and δ=0,01\delta=0{,}01, the guarantee says: with confidence of at least 99%99\% on the sample collected, the hypothesis produced will be at risk of maximum 5%5\%.

This does not mean that exactly 5%5\% of the predictions will be wrong or that the algorithm will fail exactly once in a hundred. It is a probabilistic bound valid under the theorem hypotheses.

2.2.3 Realizable setting

The simplest form of the theory assumes that there is a perfect hypothesis within the H\mathcal{H} class. This is the case feasible:

∃h∗∈Hsuch thatRP(h∗)=0. \exists h^*\in\mathcal{H} \quad\text{such that}\quad R_P(h^*)=0.

A AA algorithm is a PAC learner for H\mathcal{H} if there is a sample complexity function

mH ⁣:(0,1)2→N m_{\mathcal{H}}\colon(0,1)^2\to\mathbb{N}

such that, for any ε,δ∈(0,1)\varepsilon,\delta\in(0,1), any distribution of inputs and any target represented by H\mathcal{H}, any i.i.d. sample with

N≥mH(ε,δ) N\geq m_{\mathcal{H}}(\varepsilon,\delta)

satisfies

PD(RP(A(D))≤ε)≥1−δ. P_D\bigl(R_P(A(D))\leq\varepsilon\bigr) \geq1-\delta.

In the feasible case, a consistent algorithm seeks a hypothesis with zero empirical error. The theory needs to show when consistency in the sample implies small risk outside of it.

The hypothesis of achievement is strong. Data may contain noise, classes may overlap and the chosen family may not represent the real mechanism.

2.2.4 Agnostic setting

In the PAC agnostic learning, we do not assume that any hypothesis in H\mathcal{H} is perfect. We compare the algorithm’s result to the best hypothesis available in the class:

RP(A(D))≤inf⁡h∈HRP(h)+ε. R_P(A(D)) \leq \inf_{h\in\mathcal{H}}R_P(h)+\varepsilon.

Formally, we demand

PD(RP(A(D))≤inf⁡h∈HRP(h)+ε)≥1−δ. P_D\left( R_P(A(D)) \leq \inf_{h\in\mathcal{H}}R_P(h)+\varepsilon \right) \geq1-\delta.

ε\varepsilon is now a excess risk. The algorithm may not achieve small absolute error if every class hypothesis is inadequate; it should approximate the best possible performance within H\mathcal{H}.

This formulation separates two components:

RP(A(D))=inf⁡h∈HRP(h)⏟class limitation+excess risk⏟sample and algorithm limitations. R_P(A(D)) = \underbrace{\inf_{h\in\mathcal{H}}R_P(h)}_{\text{class limitation}} + \underbrace{\text{excess risk}}_{\text{sample and algorithm limitations}}.

Zooming in H\mathcal{H} can reduce representation limitation, but it makes statistical selection more difficult. This is an aspect of the balance between adjustment and complexity.

2.2.5 Sample complexity

The sample complexity mH(ε,δ)m_{\mathcal{H}}(\varepsilon,\delta) is the minimum number of examples sufficient for the desired warranty. It answers a statistical question: how much information is needed?

In general:

  • decrease ε\varepsilon requires more examples;
  • decrease δ\delta requires more examples;
  • increasing the complexity of H\mathcal{H} requires more examples.

For a finite class in the feasible case, a typical bound is

N≥1ε(log⁡∣H∣+log⁡1δ). N \geq \frac{1}{\varepsilon} \left( \log|\mathcal{H}| +\log\frac{1}{\delta} \right).

Constants and small variations depend on derivation, but the structure is important. Dependency is logarithmic in the number of hypotheses and in 1/δ1/\delta, and proportional to 1/ε1/\varepsilon.

In the agnostic case, a typical bound is

N=O(log⁡∣H∣+log⁡(1/δ)ε2). N = O\left( \frac{ \log|\mathcal{H}|+\log(1/\delta) }{ \varepsilon^2 } \right).

The 1/ε21/\varepsilon^2 dependency reflects the additional difficulty of comparing hypotheses when none is necessarily perfect.

2.2.6 Where does the bound for a finite class come from?

Consider the case feasible and a bad hypothesis hh with

RP(h)>ε. R_P(h)>\varepsilon.

The probability of hh hitting all NN independent examples is at most

(1−ε)N≤e−εN. (1-\varepsilon)^N \leq e^{-\varepsilon N}.

There are at most ∣H∣|\mathcal{H}| bad hypotheses. By the share of the union, the probability of some bad hypothesis remaining consistent is at most

∣H∣e−εN. |\mathcal{H}|e^{-\varepsilon N}.

We want this quantity to be maximum δ\delta:

∣H∣e−εN≤δ. |\mathcal{H}|e^{-\varepsilon N} \leq\delta.

Applying logarithms and isolating NN,

N≥1ε(log⁡∣H∣+log⁡1δ). N \geq \frac{1}{\varepsilon} \left( \log|\mathcal{H}| +\log\frac{1}{\delta} \right).

The derivation shows why we need to simultaneously control the chance of each bad hypothesis surviving and the amount of candidate hypotheses.

2.2.7 A numerical example

Suppose a finite class with

∣H∣=1 000,ε=0,05,δ=0,01. |\mathcal{H}|=1\,000, \qquad \varepsilon=0{,}05, \qquad \delta=0{,}01.

The reimburseable bound provides

N≥10,05(log⁡1 000+log⁡100). N \geq \frac{1}{0{,}05} \left( \log 1\,000+\log 100 \right).

Using natural logarithm,

N≥20(6,908+4,605)≈230,26. N \geq 20(6{,}908+4{,}605) \approx230{,}26.

Therefore, the bound asks for at least 231231 examples. This value is a guarantee of worse case, not an exact prediction of how many examples will be required in every application.

2.2.8 Infinite classes

Many important classes are infinite. There are infinite straight in the plane and infinite combinations of weights of a neural network. In this case, log⁡∣H∣\log|\mathcal{H}| cannot be used directly.

We need a more refined measure of class capacity. The Vapnik–Chervonenkis dimension, studied below, measures how many classification patterns a family can perform on finite sets. Other tools include coverage numbers, Rademacher complexity and parameters standards.

An infinite class can be PAC-learning if its effective capacity is controlled. Infinite in cardinality does not automatically mean impossible to learn.

2.2.9 Learnability and computational efficiency

Sample complexity and computational complexity are different.

  • Statistical Learning: is there an algorithm that achieves the warranty using a finite and controlled number of examples?
  • Computer efficiency: does this algorithm run in viable time and memory?

A class may admit good sample complexity, but require computationally intractable search. An efficient PAC apprentice usually requires polynomial time in the relevant parameters of representation, in 1/ε1/\varepsilon and in log⁡(1/δ)\log(1/\delta) or 1/δ1/\delta, according to the formal convention adopted. The central point is that obtaining sufficient information does not guarantee that we will be able to process it efficiently.

2.2.10 What the PAC guarantee does not say

A PAC guarantee depends on conditions.

  • i.i.d. data represent any future scenario;
  • the distribution will remain stable after implantation;
  • the labels are correct;
  • the chosen loss represents all relevant impacts;
  • the model is causal, fair or safe;
  • the bound is tight for a concrete application.

If training and use have different distributions, the derivative warranty for PP may not describe the actual operation. The theory provides a conditional statement: if the hypotheses are satisfied, then the bound is worth.

2.2.11 Finite example and inductive bias

Consider

X={1,2,…,8},Y={−1,+1}, X=\{1,2,\ldots,8\}, \qquad Y=\{-1,+1\},

and a sample that reveals the labels of five entries.

23=8 2^3=8

extensions compatible with the five observed values.

Only the sample does not allow logically to choose an extension. The algorithm needs an inductive bias: prefer simple functions, smooth patterns, linear boundaries or other structure. PAC does not eliminate this need; it analyzes when the class combination, algorithm and amount of data generalizes.

2.2.12 PAC and experimental validation

A theoretical bound and a set of tests answer different questions.

  • The PAC bound provides assurance under mathematical hypotheses and often goes in the worst case.
  • The test estimates the performance of a concrete hypothesis in an independent sample.

In practice, we use both when available: theory to understand dependencies and limits; experimental evaluation to measure the trained system.

2.2.13 Summary

A PAC method controls two levels of uncertainty:

PD(RP(A(D))≤ε)≥1−δ \boxed{ P_D\bigl( R_P(A(D)) \leq\varepsilon \bigr) \geq1-\delta }

in the case of achievable, or

PD(RP(A(D))≤inf⁡h∈HRP(h)+ε)≥1−δ \boxed{ P_D\left( R_P(A(D)) \leq \inf_{h\in\mathcal{H}}R_P(h)+\varepsilon \right) \geq1-\delta }

in the case of agnostic.

ε\varepsilon controls approximate quality, δ\delta controls confidence and mH(ε,δ)m_{\mathcal{H}}(\varepsilon,\delta) informs how many examples are sufficient.

2.2.14 Practice exercises

  1. Explain, in words, the two odds involved in a PAC guarantee.
  2. Interpret a warranty with ε=0,02\varepsilon=0{,}02 and δ=0,05\delta=0{,}05.
  3. Differentiate the agnostic case.
  4. For ∣H∣=100|\mathcal{H}|=100, ε=0,1\varepsilon=0{,}1 and δ=0,05\delta=0{,}05, calculate the achievable bound shown.
  5. Show the ∣H∣e−εN≤δ|\mathcal{H}|e^{-\varepsilon N}\leq\delta pass to the bound over NN.
  6. Why is an infinite class not automatically impossible to learn?
  7. Give an example in which i.i.d. hypothesis fails.
  8. Differentiate sample complexity of computational efficiency.
  9. Explain why a PAC guarantee does not replace a test set.

2.3 Training and Testing

A hypothesis is chosen because it adjusts to the available data. Evaluating it in the same examples used to choose it produces an optimistic estimate: the model has already had the opportunity to adapt to the particularities of this sample. To estimate generalization, we need data that have not participated in the choices.

The usual practice divides the observations into sets with distinct roles:

  • training: adjusts model parameters;
  • validation: chooses hyperparameters, features, architecture and thresholds;
  • test: estimates once the performance of the final configuration.

Training data adjust parameters, validation guides choices and the test remains isolated until the final evaluation.

Figure 2.3. Training data adjust parameters, validation guides choices and the test remains isolated until the final evaluation.

2.3.1 Parameters and hyperparameters

Parameters are learned directly by the training algorithm. In a linear function, are w\mathbf{w} weights and bb bias.

Hyperparameters control the method, but are not adjusted by the same minimization. Examples include learning rate, regularization intensity, number of layers, depth of a tree and number of neighbors.

Training in DtreinoD_{\text{treino}} produces

θ^λ∈argmin⁡θ  R^train(hθ,λ), \widehat{\theta}_\lambda \in \underset{\theta}{\operatorname{argmin}} \;\widehat{R}_{\text{train}}(h_{\theta,\lambda}),

where λ\lambda represents a hyperparameter configuration. Validation chooses

λ^∈argmin⁡λ∈Λ  R^val(hθ^λ,λ). \widehat{\lambda} \in \underset{\lambda\in\Lambda}{\operatorname{argmin}} \;\widehat{R}_{\text{val}}(h_{\widehat{\theta}_\lambda,\lambda}).

Only after fixing λ^\widehat{\lambda} did we evaluate the final configuration in the test.

2.3.2 Holdout

In the holdout protocol, we make a single division of data. An illustrative proportion is

70% train,15% validation,15% test. 70\%\text{ train},\qquad 15\%\text{ validation},\qquad 15\%\text{ test}.

There is no universal proportion. With millions of examples, a small fraction can form a precise test. With few data, booking a large part over-reduces training and makes validation unstable.

The division must be made before the exploitation guided by the labels. A registered pseudo-random seed allows to reproduce the partition, but testing many seeds and choosing the most favorable also constitutes a form of overfitting.

Test is not validation

If a decision changes after we observe the test result, then the test participated in the development. It should be considered validation, and a new independent set will be required for final evaluation.

2.3.3 Independence and representativeness

The validity of the holdout depends on training, validation and testing representing the use scenario without sharing undue information. In an i.i.d. random division, we expect the subsets to have similar distributions.

However, simple random division is not adequate in all cases:

  • in time series, the future cannot appear in the training of a prediction of the past;
  • in patient data, records of the same person should not stay in different subsets;
  • in images extracted from a video, neighboring frames are almost duplicated;
  • on recommendation, we may want to test users or items not yet observed;
  • in geographical implementation, it may be necessary to reserve whole regions.

The unit of independence must correspond to the use. If the prediction will be made for new people, the division must occur per person, not per record.

2.3.4 Stratified split

In unbalanced classification, a purely random division can produce few examples of the rare class. stratification preserves approximately the proportions of the classes in each subset.

If there are 1 0001\,000 examples, of which 100100 are positive, a stratified division of 80%/20%80\%/20\% places approximately 8080 positives in the training and 2020 in the test.

Stratifying does not create new information and does not solve an extremely rare class. Nor should it violate groups or time. When there are several restrictions, we use a strategy that first respects the causal structure of the dataset.

2.3.5 Data leakage

Leak occurs when information not available at the actual time of forecast influences training or evaluation. The result looks better than the system will be in production.

Examples:

  • normalize using average and deviation calculated on all data;
  • choose features observing correlation in the test set;
  • assign missing values before division;
  • include a variable registered after the expected event;
  • keep copies of the same example in training and testing.

All preprocessing that learns some amount should be adjusted only in training.

zj=xj−μjσj, z_j =\frac{x_j-\mu_j}{\sigma_j},

μj\mu_j and σj\sigma_j are calculated in DtreinoD_{\text{treino}} and then applied, without adjustment, to validation and testing.

A pipeline gathers preprocessing and model for each step to be adjusted within the correct protocol.

2.3.6 Cross validation kk-fold

When data is limited, a single validation can depend a lot on division. In cross-validation kk-fold, we separate development data into kk blocks approximately equal:

Ddev=F1∪F2∪⋯∪Fk. D_{\text{dev}} =F_1\cup F_2\cup\cdots\cup F_k.

For each jj, we train in all blocks except FjF_j and evaluate in FjF_j. The estimate is

R^CV=1k∑j=1kR^Fj(h(−j)), \widehat{R}_{CV} =\frac{1}{k}\sum_{j=1}^{k} \widehat{R}_{F_j}(h^{(-j)}),

where h(−j)h^{(-j)} was trained without the FjF_j block.

Each example participates in validation once and training k−1k-1 times. Common values are k=5k=5 or k=10k=10, but the choice depends on the computational cost and amount of data.

It is important that the final test remains out of cross-validation. We use folds to choose the configuration; then we train the configuration chosen in the development data and evaluate it in the isolated test.

2.3.7 Stratified and grouped cross-validation

Cross-validation also needs to respect the data structure.

  • Strategic**:** preserves class proportions in each fold.
  • By groups: keeps all examples of a group in the same fold.
  • Temporal: uses blocks that respect order, training in the past and validating in the future.

In time forecast, a progressive form is

{1,…,t1}→{t1+1,…,t2}, \{1,\ldots,t_1\}\to\{t_1+1,\ldots,t_2\},

followed by

{1,…,t2}→{t2+1,…,t3}. \{1,\ldots,t_2\}\to\{t_2+1,\ldots,t_3\}.

This mimics the way the system will accumulate history and make future predictions.

2.3.8 Repeated random sampling

The holdingout repeated, also called random subsampling, creates several random divisions training-validation . For each repetition rr, we train a new hypothesis hrh_r and calculate a MrM_r metric .

We report, for example,

M‾=1R∑r=1RMr \overline{M} =\frac{1}{R}\sum_{r=1}^{R}M_r

and variability between repetitions. Unlike kk-fold, one example can appear in validation several times and another not once.

This protocol measures the sensitivity of the procedure to data division. The values are not entirely independent because the partitions overlap; the dispersion should be interpreted as diagnosis, not automatically as a classic confidence interval.

2.3.9 Nested cross validation

If we use cross-validation both to choose hyperparameters and to estimate performance, we can achieve optimism. nested cross-validation uses two levels:

  1. internal folds choose hyperparameters;
  2. an external fold, which did not participate in the choice, evaluates the procedure.

The external cycle estimates the performance of the complete selection process. This method is useful when the set is small and many configurations are compared, although it is computationally more expensive.

2.3.10 Test confusion matrix

For KK classes, we set the matrix C∈NK×KC\in\mathbb{N}^{K\times K} by

Cij=#{(x,y)∈Dtest∣y=i,  h(x)=j}. C_{ij} =\#\{(x,y)\in D_{\text{test}} \mid y=i,\;h(x)=j\}.

In this convention, lines are true classes and columns are predicted classes. The diagonal contains correct answers; elements outside the diagonal show which classes have been confused.

One example is

target \\backslash forecastclass 1class 2class 3
class 1721
class 2181
class 3109

Accuracy is

7+8+930=0,8. \frac{7+8+9}{30}=0{,}8.

The matrix is more informative than the isolated accuracy because it reveals the direction of errors.

2.3.11 Uncertainty of the test estimate

The performance observed in the test is still a random estimate. For classification, if MM test examples are approximately independent and the observed error rate is p^\widehat{p}, an approximate standard error is

EP⁡(p^)≈p^(1−p^)M. \operatorname{EP}(\widehat{p}) \approx \sqrt{\frac{\widehat{p}(1-\widehat{p})}{M}}.

With p^=0,10\widehat{p}=0{,}10 and M=1 000M=1\,000,

EP⁡≈0,1⋅0,91 000≈0,0095. \operatorname{EP} \approx \sqrt{\frac{0{,}1\cdot0{,}9}{1\,000}} \approx0{,}0095.

A small test produces an unstable estimate. For proportions close to 00 or 11, small samples or dependency between examples, we should use appropriate interval methods instead of relying only on this approximation.

2.3.12 Choice of threshold

Probabilistic models often produce a p(x)p(x) score. Choosing a threshold based on the test leaks information. The correct procedure is:

  1. train the model in training;
  2. choose the threshold in the validation, considering the metric or the cost;
  3. freeze model and threshold;
  4. evaluate both in the test.

The same goes for selection of features, regularization, number of seasons and any performance-guided decision.

For a typical supervised project:

  1. set the division unit and reserve the test;
  2. build a pre-processing and model pipeline;
  3. use training and validation, or cross-validation, for choices;
  4. record the final configuration;
  5. if appropriate, adjust this configuration in more validation training;
  6. evaluate once in the test;
  7. report metrics, uncertainty, size of sets and division strategy;
  8. monitor distribution change after implantation.

Refit in training more validation is allowed after all choices are frozen. The test remains isolated. If the test result motivates a new change, another round of development starts and you will need to get an independent final evaluation.

2.3.14 Reproducibility

A reproducible assessment records:

  • version and origin of the data;
  • inclusion and exclusion criteria;
  • identifiers or indexes of each partition;
  • random seed;
  • pre-processing steps;
  • hyperparameters and selection criteria;
  • metrics and their definitions;
  • code version and dependencies.

Recording only the seed is not enough if the data or library changes.

2.3.15 Relationship with the theory

The PAC theory asks when the empirical risk approaches the expected risk under certain hypotheses. The training-validation-test protocol provides an operational evaluation for a concrete data set.

This book uses theoretical analyses to understand algorithms, but computational examples should keep separate evaluation whenever they affirm predictive performance. We should not rely only on training error.

Golden rule

Any data used to choose the model belongs to the development process. Only data that remained untouched can support an honest final evaluation.

2.3.16 Practice exercises

  1. Differentiate parameters, hyperparameters and metrics.
  2. Explain why normalizing before division causes leakage.
  3. Propose a suitable division for multiple queries from the same user.
  4. In what situation is a temporal division necessary?
  5. Describe the cross-validation procedure 55-fold.
  6. Differentiate repeated holdout and cross-validation.
  7. Why does nested cross-validation reduce selection bias?
  8. Calculate the accuracy of the presented confusion matrix and the recall of class 2.
  9. For p^=0,2\widehat{p}=0{,}2 and M=400M=400, calculate the approximate standard error.
  10. Explain what to do if the test result motivates a new choice of model.

2.4 Multiple choice exercises

Check the only correct alternative in each question. The comment is collected at the end of the section.

  1. The zero-one loss of a classifier is 11 when:

    1. the forecast is correct.
    2. the forecast differs from the true label.
    3. the predicted probability is exactly 11.
    4. the test set is empty.
  2. In a medical application in which no longer detecting a disease is very serious, What measure deserves special attention?

    1. Revocation of the positive class.
    2. Number of features.
    3. Rounding error.
    4. Cardinality of the exit space.
  3. Compared to the mean squared error, the mean absolute error is generally:

    1. more sensitive to atypical values.
    2. less sensitive to atypical values.
    3. always equals zero.
    4. applicable only to classification.
  4. In binary cross-entropy, assign close to zero probability to the event that actually occurred produces:

    1. loss close to zero.
    2. negative loss.
    3. very high loss.
    4. no change in loss.
  5. In the PAC language, the ϵ\epsilon parameter controls:

    1. the desired error or precision tolerance.
    2. the number of classes of the problem.
    3. the seed of the random generator.
    4. the cost of a matrix multiplication.
  6. In the context of the PAC, 1−δ1-\delta represents:

    1. the rate of learning.
    2. the level of confidence of the guarantee.
    3. the exact empirical error.
    4. the number of hypotheses.
  7. If we increase the complexity of the hypothesis class and keep the others factors, the amount of data required for the same warranty tends to:

    1. decrease to zero.
    2. always remain identical.
    3. increase.
    4. become independent of ϵ\epsilon.
  8. What practice characterizes data leakage?

    1. Adjust the normalizer only with training.
    2. Choose hyperparameters using validation.
    3. Calculate mean and deviation with the whole set before division.
    4. Evaluate once in the test at the end.
  9. When several observations belong to the same patient, the safest division is:

    1. draw each observation independently.
    2. keep all observations of each patient in the same subset.
    3. duplicate rare patients in the test.
    4. use training and testing with the same patients required.
  10. After the test set influenced a model choice, it should be treated as:

    1. part of the development process, and a new final evaluation requires Untouched data.
    2. a final test still perfectly independent.
    3. a set without any use.
    4. a training sample without labels.

Answer key with explanations

  1. b. Zero-one loss records error with 11 and hit with 00.
  2. a. The recall measures the fraction of the real positives that have been detected and, therefore, it shows false negatives.
  3. b. The square amplifies large residuals; the absolute value grows only linearly.
  4. c. Logarithm strongly penalizes reliable and incorrect predictions.
  5. a. ϵ\epsilon expresses how close to desired performance the result should to be.
  6. b. δ\delta limits the probability of failure; thus, 1−δ1-\delta is the trust.
  7. c. A richer class requires more evidence to control the selection between Your chances.
  8. c. Statistics would incorporate information from sets that should Stay independent.
  9. b. Group separation prevents patient specific information appear simultaneously in training and evaluation.
  10. a. All information used to decide is integrated into development; the final estimate requires new independent data.