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 is the population risk of the resulting rule. A sample size sufficient in one experiment does not prove this uniform guarantee.
For example, with and , 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 , a realizable distribution and an algorithm that returns a rule consistent with the labels. Call a hypothesis bad when . For an i.i.d. sample the probability that this particular rule makes no errors is
A union bound over all hypotheses gives
Therefore, suffices for every consistent rule to have risk at most with confidence . 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 . 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 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 of points. The failure counter averages 500 independent samples with seed 2505; the bound is . Cells show a trajectory with a different seed, not all 500 at once.
An infinite class: rectangles
Let the target be a closed axis-aligned rectangle in . Return the smallest rectangle containing observed positives; if there are no positives, return the empty classifier. Under realizability, the learned rectangle lies inside and introduces no false positives. Its error is the positive mass left outside.
Consider four fixed strips at the edges of , each with mass at least 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 . A union over the four lost regions gives error at most . If total positive mass is below , even the empty classifier has error below .
For distributions with atoms, do not assume a strip can be cut to have exactly mass . 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 . By the union bound,
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 marginals, with cumulative distribution function . 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 used in the proof.
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:
for every joint distribution of . If is finite, the previous lesson’s two-sided uniform bound controls every discrepancy by . For exact ERM, excess is at most twice that quantity. Therefore it suffices that
In the realizable argument, a hypothesis with error must get every label right, at cost approximately . In the agnostic case, two rules can have nearby risks around 1/2; distinguishing differences of size with fluctuations of order leads to the scale . 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 .
To make the difference tangible, imagine two constant predictors and Bernoulli labels with mean . Their errors differ by , but the standard deviation of an empirical proportion near 1/2 is approximately . When is small, observations on the order of 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 is discarded as soon as one example from that region appears, on scale . This example explains the different mechanisms; proving general lower bounds needs an additional formal argument.
The agnostic reference is the best hypothesis within , 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 and clean label given by the sign of . 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 , so excess is exactly known. Results average 200 training runs per size, with uniform tie-breaking among empirical minima and seed 1305. The and 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 without claiming exact zero risk.
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 parameters have at most bits each, there are at most configurations and . Different configurations may represent the same function, making this an upper bound. With real numbers and no discretization, cannot be replaced directly by . 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 , 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 variables, there are literals and at most on the order of 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 is large.
Exercises
Step 1 of 2. If each strip has mass at least ε/4, what is the probability of observing no point in one strip?
Step 1 of 2. With what probability can a bad hypothesis remain consistent?
def tightest_rectangle(X_pos):
pass
def estimate_failure_prob(eps, n, sampler, trials):
pass