Module contents
Lesson 5 of 20Core 100 min

PAC learning: realizable, agnostic and sample complexity

Introduce Valiant’s PAC model and its agnostic version as rigorous definitions of learning. Prove finite-class sample bounds of order log|H|/ε in the realizable case and log|H|/ε² in the agnostic case, explain the difference, and distinguish statistical from computational learnability through proper and improper learning.

After this lesson you can

  • State realizable and agnostic PAC learnability and sample complexity m_H(ε, δ).
  • Prove the finite-class realizable bound using bad hypotheses, without Hoeffding.
  • Derive agnostic learnability of finite classes from uniform convergence.
  • Explain why realizable and agnostic bounds scale as 1/ε and 1/ε².
  • Distinguish proper and improper learning and give an example where improper learning is computationally easier.
  • Apply discretization: a class with k parameters of b bits is finite with log|H| = kb log 2.

Before you start

What does learning for any distribution mean?

An algorithm with good error on one sample can still fail on another distribution. PAC theory states a stronger requirement: choose a sample size that guarantees accuracy and confidence without knowing the distribution. The goal is to bound the probability of obtaining a rule with too much error, rather than promise absolute success on every sample.

The order of the quantifiers matters: one learning rule and sample size are chosen to work for every allowed distribution, even though the distribution is unknown. The probability is over the sample, while RDR_D is the population risk of the resulting rule. A sample size sufficient in one experiment does not prove this uniform guarantee.

For example, with ϵ=0.05\epsilon=0.05 and δ=0.01\delta=0.01, the desired event is that the returned rule has risk at most 5%, and the procedure may fail that condition with probability at most 1%. It does not mean observed training error is 5%, or that the error at each individual point is independent once a sample is fixed. Realizability is an assumption about the joint distribution and the class: if the same input can receive two different labels with positive probability, a deterministic rule cannot have zero risk there.

Bad hypotheses in a finite class

Suppose ∣H∣<∞|\mathcal H|<\infty, a realizable distribution and an algorithm that returns a rule consistent with the nn labels. Call a hypothesis bad when R(h)>ϵR(h)>\epsilon. For an i.i.d. sample the probability that this particular rule makes no errors is

(1−R(h))n≤(1−ϵ)n≤e−ϵn.(1-R(h))^n\le(1-\epsilon)^n\le e^{-\epsilon n}.

A union bound over all hypotheses gives

P{∃h∈H: R(h)>ϵ, R^S(h)=0}≤∣H∣e−ϵn.\Pr\{\exists h\in\mathcal H:\ R(h)>\epsilon,\ \widehat R_S(h)=0\}\le |\mathcal H|e^{-\epsilon n}.

Therefore, n≥[log⁡∣H∣+log⁡(1/δ)]/ϵn\ge[\log|\mathcal H|+\log(1/\delta)]/\epsilon suffices for every consistent rule to have risk at most ϵ\epsilon with confidence 1−δ1-\delta. This is PAC learnability of finite classes using realizable ERM. We did not use Hoeffding: a bad rule must avoid its errors on every observation. Independence of examples allows the probability to be raised to nn. Existence of the target rule ensures at least one consistent hypothesis exists.

The bound protects all consistent hypotheses simultaneously: tie-breaking among them does not matter, provided the class was fixed before the sample. The factor ∣H∣|\mathcal H| appears before taking logarithms, when survival probabilities are added; sample size therefore depends only on its logarithm. The union bound can be loose: many hypotheses fail on overlapping regions and their survival events are dependent. A sufficient bound does not imply that many examples are necessary for every class or distribution.

The figure enumerates the 64 binary functions over six equally likely points, with an identically zero target. An example eliminates functions that disagree at that point; repeated points remove no additional information. A hypothesis is bad if it differs on more than a fraction ϵ\epsilon of points. The failure counter averages 500 independent samples with seed 2505; the bound is min⁡{1,64(1−ϵ)n}\min\{1,64(1-\epsilon)^n\}. Cells show a trajectory with a different seed, not all 500 at once.

InteractiveThe extinction of bad hypotheses

Red: bad and consistent; blue: good and consistent; gray: eliminated.

0 examples
0.30
Bad and still consistent57
Failure in 500 samples1.000
Union bound1.000
Replay the examples and change ε. Red cells are bad but still compatible; compare their survival over 500 samples with the union bound.

An infinite class: rectangles

Let the target be a closed axis-aligned rectangle R∗R^* in R2\mathbb R^2. Return the smallest rectangle containing observed positives; if there are no positives, return the empty classifier. Under realizability, the learned rectangle lies inside R∗R^* and introduces no false positives. Its error is the positive mass left outside.

Consider four fixed strips at the edges of R∗R^*, each with mass at least ϵ/4\epsilon/4 when sufficient positive mass exists. If the sample contains a positive in every strip, each learned edge reaches that strip and the mass lost on that side is at most ϵ/4\epsilon/4. A union over the four lost regions gives error at most ϵ\epsilon. If total positive mass is below ϵ/4\epsilon/4, even the empty classifier has error below ϵ\epsilon.

For distributions with atoms, do not assume a strip can be cut to have exactly mass ϵ/4\epsilon/4. Use positive-mass quantiles: the closed strip through the first quantile has at least that mass, while the strictly preceding part has at most that mass. A point in the strip leaves side error inside the strict part. The same argument applies to all four sides; overlap only makes the union bound more conservative.

Each strip is missed with probability at most (1−ϵ/4)n≤e−ϵn/4(1-\epsilon/4)^n\le e^{-\epsilon n/4}. By the union bound,

P{R(R^)>ϵ}≤4e−ϵn/4,n≥4ϵlog⁡4δ.\Pr\{R(\hat R)>\epsilon\}\le4e^{-\epsilon n/4},\qquad n\ge\frac4\epsilon\log\frac4\delta.

This works for arbitrary distributions, not only uniform ones, and proves PAC learnability of an infinite class. The figure uses two specific product distributions: uniform and one with Beta(2,2)\mathrm{Beta}(2,2) marginals, with cumulative distribution function F(t)=3t2−2t3F(t)=3t^2-2t^3. Their masses are calculated from the CDF, not by counting points. The four displayed strips do not overlap: left and right span the full height; top and bottom span only the learned width. They are observed error regions, distinct from the fixed strips of mass ϵ/4\epsilon/4 used in the proof.

InteractiveLearning a rectangle blindly
Orange: target region outside the fit; blue: learned rectangle. Nonoverlapping masses: left 0.015, right 0.038, bottom 0.006, top 0.002.
Distribution
0.50
0.45
80
0.15
Observed positives22
Exact error mass0.0603
Error greater than ε?no
Failure bound 4 exp(−εn/4)0.199
Drag the target and change size, distribution and n. Error is the orange mass; the bound shown is a failure probability over samples, not the error of this sample.
[ ]Rectangles and failure probabilityBrowser
import numpy as np

rng = np.random.default_rng(1305)
target = (.2,.8,.25,.75)
def cdf(x, kind):
    return x if kind == 'uniforme' else 3*x*x-2*x*x*x
def tightest_rectangle(X_pos):
    if len(X_pos)==0: return None
    return (X_pos[:,0].min(), X_pos[:,0].max(), X_pos[:,1].min(), X_pos[:,1].max())
example=np.array([[.3,.4],[.7,.6]])
assert np.allclose(tightest_rectangle(example),(.3,.7,.4,.6))
def mass(rect,kind):
    if rect is None: return 0.
    l,r,b,t=rect
    return (cdf(r,kind)-cdf(l,kind))*(cdf(t,kind)-cdf(b,kind))
def experiment(n,eps,kind,trials=10000):
    # La misma operación de extremos se vectoriza por fila para 10000 muestras.
    X = rng.uniform(size=(trials,n,2)) if kind=='uniforme' else rng.beta(2,2,size=(trials,n,2))
    l,r,b,t=target
    positive=(X[:,:,0]>=l)&(X[:,:,0]<=r)&(X[:,:,1]>=b)&(X[:,:,1]<=t)
    left=np.where(positive,X[:,:,0],np.inf).min(axis=1)
    right=np.where(positive,X[:,:,0],-np.inf).max(axis=1)
    bottom=np.where(positive,X[:,:,1],np.inf).min(axis=1)
    top=np.where(positive,X[:,:,1],-np.inf).max(axis=1)
    valid=positive.any(axis=1)
    fit=np.zeros(trials)
    fit[valid]=(cdf(right[valid],kind)-cdf(left[valid],kind))*(cdf(top[valid],kind)-cdf(bottom[valid],kind))
    error=mass(target,kind)-fit
    return np.mean(error>eps)
eps=.15
for kind in ['uniforme','centro']:
    for n in [80,160]:
        observed=experiment(n,eps,kind)
        print(kind,'n',n,'fallo',round(observed,4),'cota',round(min(1,4*np.exp(-eps*n/4)),4))

The 10000 repetitions check two distributions and two sample sizes. The proof covers any distribution under its assumptions; simulation does not replace it. In this example the target is known only to calculate error, not to fit the rectangle.

Agnostic PAC

Agnostic PAC learning does not require any hypothesis to have zero risk. The goal is to compete with the best rule in the class:

PS ⁣(RD(A(S))≤inf⁡h∈HRD(h)+ϵ)≥1−δ\Pr_S\!\left(R_D(A(S))\le\inf_{h\in\mathcal H}R_D(h)+\epsilon\right)\ge1-\delta

for every joint distribution of (X,Y)(X,Y). If H\mathcal H is finite, the previous lesson’s two-sided uniform bound controls every discrepancy by log⁡(2∣H∣/δ)/(2n)\sqrt{\log(2|\mathcal H|/\delta)/(2n)}. For exact ERM, excess is at most twice that quantity. Therefore it suffices that

n≥2log⁡(2∣H∣/δ)ϵ2.n\ge\frac{2\log(2|\mathcal H|/\delta)}{\epsilon^2}.

In the realizable argument, a hypothesis with error ϵ\epsilon must get every label right, at cost approximately e−nϵe^{-n\epsilon}. In the agnostic case, two rules can have nearby risks around 1/2; distinguishing differences of size ϵ\epsilon with fluctuations of order n−1/2n^{-1/2} leads to the scale 1/ϵ21/\epsilon^2. These are general sufficient bounds. Structure in a particular distribution, a positive gap between hypotheses or low-noise conditions can yield faster convergence. Adding noise invalidates the consistency proof, but does not force every problem to have exactly slope −1/2-1/2.

To make the difference tangible, imagine two constant predictors and Bernoulli labels with mean 1/2+γ1/2+\gamma. Their errors differ by 2γ2\gamma, but the standard deviation of an empirical proportion near 1/2 is approximately 1/(2n)1/(2\sqrt n). When γ\gamma is small, observations on the order of 1/γ21/\gamma^2 are needed to distinguish signal from fluctuation with constant confidence. In a realizable task, by contrast, a hypothesis that fails on a region of mass ϵ\epsilon is discarded as soon as one example from that region appears, on scale 1/ϵ1/\epsilon. This example explains the different mechanisms; proving general lower bounds needs an additional formal argument.

The agnostic reference is the best hypothesis within H\mathcal H, not necessarily the global Bayes rule. If the class is too small, it can be PAC learnable and still have large approximation error. The sample-complexity bound says how many examples suffice to approach the best member, not whether that member is useful in an application.

The next figure evaluates ERM among 64 angular separators in the plane, with X∼N(0,I2)X\sim\Normal(0,I_2) and clean label given by the sign of X1X_1. Each label is flipped with a selectable probability. The clean target belongs to the class; with noise its best risk is the flip probability. An angular separator’s disagreement probability is its minimum angle divided by π\pi, so excess is exactly known. Results average 200 training runs per size, with uniform tie-breaking among empirical minima and seed 1305. The 1/n1/n and 1/n1/\sqrt n lines are references normalized to the first point, not fits or slope guarantees for this distribution. If none of the 200 replicates shows excess, it is drawn at the floor 10−510^{-5} without claiming exact zero risk.

InteractiveRealizable and agnostic: comparing rates
  • measured excess
  • 1/n reference
  • 1/√n reference
0.00
Noise0.00
Mean excess with n=20480.00000
Change noise and compare the observed curve with two references. A finite class with a fixed gap can converge faster than the worst-case agnostic bound.
[ ]Learning curves for a finite classBrowser
import numpy as np
import matplotlib.pyplot as plt

rng=np.random.default_rng(1305)
angles=np.arange(64)*2*np.pi/64
W=np.stack((np.cos(angles),np.sin(angles)))
distance=np.minimum(angles,2*np.pi-angles)/np.pi
sizes=np.array([32,64,128,256,512]); B=120
for noise in [0.,.1,.3,.49]:
    means=[]
    for n in sizes:
        excess=[]
        for _ in range(B):
            X=rng.normal(size=(n,2)); clean=X[:,0]>=0
            y=np.logical_xor(clean,rng.random(n)<noise)
            errors=np.mean((X@W>=0)!=y[:,None],axis=0)
            ties=np.flatnonzero(errors==errors.min())
            chosen=int(ties[rng.integers(len(ties))])
            excess.append((1-2*noise)*distance[chosen])
        means.append(np.mean(excess))
    positive=np.array(means)>0
    slope=np.polyfit(np.log(sizes[positive]),np.log(np.array(means)[positive]),1)[0] if positive.sum()>1 else np.nan
    print('ruido',noise,'excesos',np.round(means,5),'pendiente descriptiva',round(slope,3))
    plt.loglog(sizes,np.maximum(means,1e-5),marker='o',label=f'ruido={noise}')
plt.xlabel('n');plt.ylabel('exceso medio (suelo 1e-5)');plt.legend();plt.show()

Bits, output and time

If kk parameters have at most bb bits each, there are at most 2kb2^{kb} configurations and log⁡∣H∣≤kblog⁡2\log|\mathcal H|\le kb\log2. Different configurations may represent the same function, making this an upper bound. With real numbers and no discretization, ∣H∣|\mathcal H| cannot be replaced directly by 2k2^k. Counting bits gives a statistical guarantee, but with millions of parameters it may be too loose to explain observed results.

Efficient learnability adds a requirement of polynomial time in representation size and accuracy and confidence parameters. A proper learner returns a rule from the target class; an improper learner may return a rule from another class and still approximate the target. Sample size and search time are distinct resources.

Chapter 8 of Shalev-Shwartz and Ben-David offers an example. A 3-term DNF is a disjunction of three potentially long conjunctions. Under the usual assumption RP≠NP\mathrm{RP}\ne\mathrm{NP}, there is no polynomial-time proper PAC learner for the problem family as dimension grows. However, distributing the three conjunctions makes the target equivalent to a 3-CNF: a conjunction of clauses of at most three literals. There are only polynomially many possible clauses. Start with all of them and remove those contradicted by a positive example; by realizability, the target clauses survive, so the resulting conjunction also rejects negatives. The output need not be a 3-term DNF: this is an efficient improper learner in the realizable case. Proper hardness does not imply every way to learn the concept is impossible or resolve the agnostic case.

If there are dd variables, there are 2d2d literals and at most on the order of (2d)3(2d)^3 three-literal clauses. Representing the learned conjunction and scanning those clauses for each example costs polynomial time. The enlarged class of conjunctions of those clauses is finite: its logarithmic cardinality is at most proportional to the number of clauses, yielding a polynomial sample bound. This proves existence under realizability; it does not suggest enumerating every clause is practical when dd is large.

Exercises

Proof
Prove: Prove the bound 4 exp(-εn/4) for the rectangle fitted to positives.
0
Choose four fixed strips using positive-mass quantiles; handle the case of small positive mass.

Step 1 of 2. If each strip has mass at least ε/4, what is the probability of observing no point in one strip?

Proof
Prove: Prove the realizable bound for a finite class.
0
Every bad hypothesis has risk greater than ε and examples are i.i.d.

Step 1 of 2. With what probability can a bad hypothesis remain consistent?

Numeric
For |H|=2²⁰, ε=0.01 and δ=0.05, what is the smallest integer satisfying this lesson’s realizable sufficient bound?
Numeric
With the same |H|, ε and δ, what is the smallest integer satisfying n ≥ 2 ln(2|H|/δ)/ε²?
Quiz
What distinguishes improper learning of 3-term DNF using 3-CNF in the realizable case?
CodeRectangle and failure
Implement tightest_rectangle(X_pos), returning (xmin,xmax,ymin,ymax), or None when there are no positives. Implement estimate_failure_prob(eps,n,sampler,trials): each sampler(n) returns X of shape (n,2), labels y and an error(rect) function calculating population risk of that rectangle. Count the fraction of trials whose error is strictly greater than eps.
def tightest_rectangle(X_pos):
  pass
def estimate_failure_prob(eps, n, sampler, trials):
  pass
Shift+Enter to run

Summary

Key idea
In the realizable case, eliminating bad hypotheses gives a sufficient bound proportional to 1/ε; in the agnostic case, uniform convergence gives a general bound proportional to 1/ε². These statistical guarantees alone do not determine whether the algorithm is efficient or whether its output must belong to the original class.