AI Wiki中文/EN

PAC learning: accuracy, confidence and the algorithm that must deliver them

PAC 学习

Separate realizable and agnostic guarantees, properness and computational efficiency; audit an original threshold learner with exact probabilities.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A guarantee about repeating the learning experiment

Suppose a sorting device should flag items above an unknown threshold. You label a small random sample, fit a threshold and deploy it. A useful guarantee would specify both how much population error you can tolerate and how often the learning procedure is allowed to miss that target when the entire sample is drawn again.

Probably approximately correct learning, or PAC learning, separates those two allowances. The accuracy parameter ε bounds the predictor’s population error; the failure parameter δ bounds the probability that training returns a predictor exceeding that error. Neither is a confidence score for one item. They describe different random experiments: drawing a training set, then drawing a future item for the resulting predictor.

We use modern binary classification with labeled IID examples. Valiant’s 1984 paper established a computational framework for probabilistic learning, but its particular protocol supplies positive examples and may permit queries; it also uses a one-sided error requirement. Those details are not silently replaced by the modern protocol implemented here. Original paper, §§2–3, pp. 1136–1137.

Read the quantifiers before reading the sample count

Let H be a class of binary predictors, P a distribution over input-label pairs, and A a learning algorithm. Its output after sample S is A(S); a randomized learner may also use an independent random seed U. Population risk uses a fresh pair from P:

RP(h)=Pr⁡(X,Y)∼P[h(X)≠Y].R_P(h)=\Pr_{(X,Y)\sim P}[h(X)\ne Y].

In the realizable setting, some member of H has zero risk under P. Labels need only agree with that member with probability one; irrelevant zero-probability inputs do not affect risk. The modern distribution-free requirement is that one algorithm and a sample bound work for every permitted P:

∀ε,δ∈(0,1), ∀P realizable by H, ∀m≥mH(ε,δ):Pr⁡S∼Pm,U ⁣[RP(A(S,U))>ε]≤δ.\forall\varepsilon,\delta\in(0,1),\ \forall P\text{ realizable by }H,\ \forall m\ge m_H(\varepsilon,\delta):\qquad\Pr_{S\sim P^m,U}\!\left[R_P(A(S,U))>\varepsilon\right]\le\delta.

The algorithm is chosen before the unknown P, not separately after being told which distribution will appear. The outer probability is over the sample and any learner randomness. Within that event, R already averages over future items. The same distribution supplies training and evaluation; correlated records or distribution shifts need a different analysis. The textbook’s Definition 3.1 spells out these quantifiers. Understanding Machine Learning, §3.1.

A sample bound is sufficient for this guarantee. It need not be the smallest possible bound, and “sample complexity” should state whether it means a particular upper bound or an optimal requirement over algorithms. A successful run on one dataset establishes neither the universal quantifiers nor the failure probability.

Realizable, agnostic, proper and improper are different choices

The agnostic setting allows arbitrary joint input-label distributions, including irreducible label noise. It compares the output with the best risk available in H, rather than demanding nearly zero error:

RP∗(H)=inf⁡h∈HRP(h),Pr⁡S∼Pm,U ⁣[RP(A(S,U))>RP∗(H)+ε]≤δ.R_P^*(H)=\inf_{h\in H}R_P(h),\qquad\Pr_{S\sim P^m,U}\!\left[R_P(A(S,U))>R_P^*(H)+\varepsilon\right]\le\delta.

For our finite threshold class, the infimum is a minimum. If the best class member has risk 0.3, ε=0.05 allows risk up to 0.35 on successful runs; it does not promise 0.05 total error. Realizability is the special case where an allowed predictor achieves zero risk. The empirical-risk chapter derives a finite-class agnostic guarantee; this chapter does not repeat its uniform-convergence proof.

A proper learner returns a member of H. An improper learner may return a predictor outside H while still meeting the comparison with H. This concerns the output representation, not whether the method is legitimate or its guarantee is weaker. A decision tree learned against a threshold benchmark could be improper if it represents a non-threshold function. The distinction is independent of whether the data are realizable. Textbook, Definition 3.4 and Remark 3.2.

Statistical PAC learnability also does not by itself promise a fast implementation. Here we separate a sample guarantee from computational efficiency. A claim of efficient learning must specify runtime in accuracy, confidence and input/representation size, rather than treating exhaustive search as free. Valiant’s original definition explicitly includes polynomial runtime; the textbook discusses this convention in §3.4. The finite audit below is not the learner and has a different cost.

A threshold learner with a distribution-free bound

Take inputs 0 through N−1 and thresholds t=0 through N. Define hₜ(x)=1 when x≥t. Threshold 0 labels everything positive; threshold N labels everything negative. Labels in this example are generated by a true threshold t*. The learner chooses one plus the largest observed negative input, or zero if there are none:

ht(x)=1[x≥t],t^=max⁡ ⁣({0}∪{xi+1:yi=0}),RP(ht^)=∑x=t^t∗−1px.h_t(x)=\mathbf1[x\ge t],\qquad\widehat t=\max\!\left(\{0\}\cup\{x_i+1:y_i=0\}\right),\qquad R_P(h_{\widehat t})=\sum_{x=\widehat t}^{t^*-1}p_x.

Every negative sample lies below t*, so the selected threshold cannot exceed t*. Every positive sample lies at or above t* and is labeled correctly by the selected threshold. Thus the learner is consistent on realizable samples, even if it mislabels unseen negatives as positive. It is proper because the returned threshold belongs to 0,…,N.

Here is a proof that works for any probability masses pₓ on the finite ordered domain. Among thresholds from 0 through t*, call t bad when its risk exceeds ε. Their risks decrease as t increases. If there are no bad thresholds, failure is impossible. Otherwise let b be the largest bad threshold and let q be the probability mass of the negative interval b,…,t*−1. By construction q>ε.

The learner returns a bad threshold exactly when none of the m samples falls in that interval. One such negative observation would move its threshold above b; all observations outside the interval leave it at or below b. Independence therefore gives:

Pr⁡ ⁣[RP(ht^)>ε]=(1−q)m≤e−mε,m≥⌈log⁡(1/δ)ε⌉ ⟹ Pr⁡(failure)≤δ.\Pr\!\left[R_P(h_{\widehat t})>\varepsilon\right]=(1-q)^m\le e^{-m\varepsilon},\qquad m\ge\left\lceil\frac{\log(1/\delta)}{\varepsilon}\right\rceil\ \Longrightarrow\ \Pr(\text{failure})\le\delta.

The equality applies when a bad interval exists; otherwise the probability is zero. It includes m=0 with the usual empty-sample interpretation. The sufficient bound is uniform over the domain size, target threshold and distribution in this family. The proof, rather than a finite list of simulations, establishes that scope. It exploits ordered, realizable thresholds; it is not an agnostic bound for arbitrary classifiers.

As a concrete distribution, use masses (1,2,1,3,2,1)/10 on six inputs and t*=4. With ε=1/5, the largest bad threshold is 3: it has risk 3/10, and observing input 3 is enough to eliminate every bad threshold. Therefore the exact failure probability is (7/10)ᵐ. For δ=1/20, nine observations suffice for this particular distribution, whereas the distribution-free sufficient bound above gives fifteen. Fifteen is not claimed to be an optimal universal sample requirement.

Keep the learner separate from the omniscient audit

learn receives only N and labeled examples. It tracks the largest negative input and the smallest positive input, returning the smallest consistent threshold. Contradictory labels or a positive observation below a negative one cause ValueError. This checks sample consistency, not whether a future labeling process truly satisfies realizability. An empty sample returns threshold zero. Repeated examples retain their ordinary meaning.

audit receives extra information unavailable to that learner: nonnegative integer population weights, the true threshold, sample size m and an exact Fraction ε strictly between zero and one. It computes the entire distribution of the learned threshold over weighted ordered samples. It does not fit a new predictor using the known population.

The audit begins with threshold zero and, for each new draw, adds its integer mass to the updated threshold state. A sampled negative input x updates the state to max(t,x+1); a positive input leaves it unchanged. After m steps, dividing by the total weight raised to m gives exact probabilities. Zero-weight inputs are allowed, all-zero weights and an empty domain are rejected. Booleans and floating-point probability inputs are rejected. The failure event uses strict risk > epsilon, so equality meets the accuracy requirement.

Write the state update as T(t,x), with total weight W. The integer recurrence is:

c0(t)=1[t=0],cs+1(v)=∑t,x:T(t,x)=vcs(t)wx,Pr⁡(t^=v)=cm(v)Wm.c_0(t)=\mathbf1[t=0],\qquad c_{s+1}(v)=\sum_{t,x:T(t,x)=v}c_s(t)w_x,\qquad\Pr(\widehat t=v)=\frac{c_m(v)}{W^m}.
from fractions import Fraction
from math import ceil, log


def integer(value, minimum=0):
    if type(value) is not int or value < minimum:
        raise ValueError('integer outside allowed range; Booleans are not integers here')
    return value


def sequence(value):
    if type(value) not in (list, tuple):
        raise ValueError('expected list or tuple')
    return value


def learn(n, sample):
    """Return the smallest threshold consistent with the labeled sample."""
    n = integer(n, 1)
    lower, upper = 0, n
    for row in sequence(sample):
        row = sequence(row)
        if len(row) != 2:
            raise ValueError('each example needs x and y')
        x, y = integer(row[0]), integer(row[1])
        if x >= n or y > 1:
            raise ValueError('example outside domain or label set')
        if y == 0:
            lower = max(lower, x + 1)
        else:
            upper = min(upper, x)
    if lower > upper:
        raise ValueError('sample is inconsistent with increasing thresholds')
    return lower


def audit(weights, target, m, epsilon):
    """Exact sampling distribution for this learner under a known realizable model."""
    weights = tuple(integer(w) for w in sequence(weights))
    if not weights or sum(weights) == 0:
        raise ValueError('nonempty nonnegative weights with positive sum required')
    n, total = len(weights), sum(weights)
    target, m = integer(target), integer(m)
    if target > n:
        raise ValueError('target threshold outside 0..n')
    if type(epsilon) not in (int, Fraction) or not 0 < epsilon < 1:
        raise ValueError('epsilon must be exact and strictly between zero and one')
    # Integer masses count weighted ordered sample histories, not fitted models.
    counts = [0] * (target + 1)
    counts[0] = 1
    for _ in range(m):
        updated = [0] * len(counts)
        for threshold, mass in enumerate(counts):
            for x, weight in enumerate(weights):
                new = max(threshold, x + 1) if x < target else threshold
                updated[new] += mass * weight
        counts = updated
    denominator = total ** m
    distribution = tuple(Fraction(c, denominator) for c in counts)
    suffix = [0] * (target + 1)
    for k in range(target - 1, -1, -1):
        suffix[k] = suffix[k + 1] + weights[k]
    risks = tuple(Fraction(w, total) for w in suffix)
    failure = sum((p for p, r in zip(distribution, risks) if r > epsilon), Fraction())
    expected_risk = sum((p * r for p, r in zip(distribution, risks)), Fraction())
    return {'threshold_mass': distribution, 'risks': risks,
            'failure': failure, 'expected_risk': expected_risk}


if __name__ == '__main__':
    weights, target = (1, 2, 1, 3, 2, 1), 4
    epsilon, delta = Fraction(1, 5), Fraction(1, 20)
    sample = ((0, 0), (2, 0), (4, 1))
    threshold = learn(len(weights), sample)
    print('sample threshold:', threshold)
    print('sample risk:', audit(weights, target, 0, epsilon)['risks'][threshold])
    print('m | exact failure | expected risk')
    for m in (0, 1, 4, 8, 9, 15):
        result = audit(weights, target, m, epsilon)
        print(m, str(result['failure']), round(float(result['expected_risk']), 6))
    first = next(m for m in range(16) if audit(weights, target, m, epsilon)['failure'] <= delta)
    print('first sufficient for this distribution:', first)
    print('distribution-free sufficient bound:', ceil(log(1 / float(delta)) / float(epsilon)))

Actual output:

sample threshold: 3
sample risk: 3/10
m | exact failure | expected risk
0 1 0.7
1 7/10 0.38
4 2401/10000 0.09092
8 5764801/100000000 0.019112
9 40353607/1000000000 0.013168
15 4747561509943/1000000000000000 0.001472
first sufficient for this distribution: 9
distribution-free sufficient bound: 15

The handpicked sample contains negatives at 0 and 2 and a positive at 4. It returns threshold 3, which fits all three labels but has population risk 3/10. That particular output fails the chosen ε=1/5 target. This does not refute a statement allowing some failed training samples. Conversely, the small expected risk at m=9 is not the definition of PAC success; the separately reported failure probability is the relevant quantity.

The first-sufficient search in the demonstration checks m=0,…,15 for this known distribution using exact comparisons. It is not a generic sample-complexity optimizer. The displayed universal bound uses floating logarithms only for this fixed calculation; the guarantee above is a mathematical statement. The returned threshold distribution and risks remain exact fractions throughout.

For a supplied sample of length m, learn uses O(m+1) comparisons and O(1) additional index slots, apart from the input and integer encoding costs. The audit retains at most N+1 threshold states and loops over every state and domain value on each draw. Its transition work is O(mN(N+1)) big-integer multiply-adds, with O(N) further probability/risk conversions and summation, plus the denominator power. Including validation and zero samples gives O((m+1)N(N+1)) arithmetic work when each integer/rational operation is counted as one. That is not a bit-operation bound.

If W is the positive total integer weight and ℓ is the bit length of W, state masses have O((m+1)ℓ) bits. A coarse retained-space bound is O((N+1)(m+1)ℓ) bits; fraction reduction and arithmetic depend on those bit lengths. The audit avoids enumerating Nᵐ ordered samples, but increasing m still enlarges its integers. There is no partial-result or runtime-budget status.

What the guarantee leaves open

PAC is a property of a learner under a specified data-access model. It does not assert that any training method, sufficiently large dataset or expressive model will work. In particular, checking that one sample admits a threshold does not establish that the population is threshold-realizable. On noisy data, the consistency-only learner may reject; it is not an agnostic optimizer.

Zero population risk is not necessarily exact parameter recovery. If an interval has zero probability mass, several thresholds can make different predictions there while sharing zero risk. With target threshold zero, this learner already has zero risk before observing anything. Such easy instances do not remove the worst-case quantifiers in a distribution-free guarantee.

The confidence statement is not a posterior probability about the correctness of a specific fitted model. It bounds the rate of bad outputs across hypothetical repeated IID samples under each permitted distribution. It also does not give a correctness probability of 1−δ to each training point or a conditional correctness guarantee at every fixed input. For a successful output, the error on a fresh IID draw from P, averaged over that distribution, is at most ε.

The agnostic criterion allows unavoidable risk and compares against H. An output outside H can even outperform its best member; this does not violate an improper-learning guarantee. Conversely, enlarging H changes the benchmark and may alter the amount of data or computation required. A sample bound must identify its class, learning protocol, loss, properness convention and realizability assumption.

Real experiments still need suitable sampling, a separate evaluation design and knowledge of how labels were produced. The known-distribution audit is useful because those assumptions are explicit and its answers are checkable; real applications generally cannot supply the true threshold and exact probability weights.

Identify which probability is being bounded

  1. For ε=0.2 and δ=0.05, what does a successful realizable PAC guarantee say? Does it assign 95% confidence to each item’s predicted label?

    Answer: At least 95% of training runs, over the permitted sampling and learner randomness, produce a predictor with population error at most 20%. It does not assign a posterior confidence to each label. Up to 5% of runs may produce worse predictors.

  2. In the six-input example, why do eight samples fail the requested confidence while nine suffice? Why is the printed bound fifteen?

    Answer: Exact failure is (7/10)ᵐ: at m=8 it is 5764801/100000000, greater than 1/20; at m=9 it is 40353607/1000000000, less than 1/20. Fifteen comes from the looser distribution-free bound ceil(log(20)/0.2), not from the smallest passing count for this distribution.

  3. For weights (1,0,1), target threshold 2 and an observed negative at input 0, which threshold does the learner return? Can it have zero risk without recovering the target? What if risk is exactly ε?

    Answer: It returns threshold 1. Thresholds 1 and 2 disagree only at the zero-mass input 1, so the learned predictor has zero risk despite a different parameter. Risk exactly ε is successful here; only strictly larger risk contributes to failure.

  4. If the best risk in H is 0.3 and ε=0.05, what does an agnostic guarantee permit? If the learner returns a non-threshold tree while H contains only thresholds, is it proper? Does a fast audit prove efficient learning?

    Answer: Successful runs may have risk up to 0.35. A non-threshold output is improper relative to that H, even if it meets the guarantee. Audit cost and learning cost are different: an audit may know the population, and a learning-efficiency claim needs a runtime bound for the actual learner under its stated information access.

The protocol is part of the theory

The 1984 journal version of Valiant’s paper appears in Communications of the ACM 27(11), pp. 1134–1142; its first page identifies an earlier conference version. In §§2–3 the journal paper specifies positive-example access, an oracle option, polynomial computation and one-sided errors. It uses one adjustable parameter in two probabilistic bounds and explicitly remarks that separate parameters would be more precise. This is historical context, not a claim that our threshold routine implements that protocol. University-hosted original scan.

Shalev-Shwartz and Ben-David’s 2014 textbook provides the modern statistical definition, agnostic general-loss extension, proper/improper distinction and separation of statistical from computational learning. The online copy has different pagination from print. Relevant definitions and remarks were read from the official PDF’s search-extracted text after direct opening failed; no entire-book or visual-page review is claimed. The original threshold example and its interval proof above do not depend on copying a textbook exercise.

The tests independently enumerate short ordered samples and select the smallest consistent threshold by checking every hypothesis, rather than reusing the audit’s state transitions. They also use the critical-interval formula to check larger sample counts. These finite checks validate the program; the explicit interval argument supplies the uniform guarantee beyond those fixtures. Continue with empirical risk for finite-class agnostic bounds and the planned VC dimension topic for another way to characterize class complexity.

Make a prediction, then check

With epsilon=0.2 and delta=0.05, what does a realizable PAC guarantee bound?

Choose one answer

Learning objectives

  • Read the PAC quantifiers and distinguish accuracy from the probability of a bad training outcome.
  • Separate realizable and agnostic learning, properness and computational efficiency.
  • Audit a threshold learner exactly and compare a distribution-specific sample count with a uniform sufficient bound.

Prerequisites & connections

Explore related knowledge →

References

  1. A Theory of the Learnable
    Leslie G. Valiant · 1984
  2. Understanding Machine Learning: From Theory to Algorithms — author online copy
    Shai Shalev-Shwartz; Shai Ben-David · 2014

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.

  • Independent AI reviewer requested clarification of the confidence statement: successful outputs have fresh-draw average error at most epsilon, without a conditional guarantee at each fixed input. Both languages now state this explicitly; code unchanged.
  • Nine tests passed. A separate exhaustive-hypothesis oracle checks 70 audit distributions through 1,154 weighted ordered samples, and 259 arbitrary short labeled samples including contradictions. The oracle does not reuse the state-transition DP.
  • Checked 96 critical-interval cases, zero samples, extreme thresholds, zero-mass parameter ambiguity, strict risk>epsilon, scaling integer weights, repetitions, input preservation and invalid values. Exact (7/10)^m failure gives first passing count 9; a 60-digit Decimal calculation independently checks sufficient count 15. All eleven stdout lines match the article.
  • Original bilingual prose, six matching display equations, six anchors, identical Python/output and four answered exercises. Strict MDX/KaTeX and actual React HTML passed. Humanizer prose reread; AI author checks only, review written pending independent review. No library, whole-site build, empirical population study or agnostic solver claim.
  • Read complete bilingual articles, code, nine author tests and final metadata. All nine author tests passed. Learner information is limited to domain size and labeled sample; consistency checks, extreme thresholds, empty sample, strict risk>epsilon and exact rational audit outputs match the stated contract.
  • Independent order-statistic CDF uses P(learned threshold <= k) = (1-risk(k))^m, then takes consecutive differences for every threshold mass. It uses neither threshold DP nor ordered sample/all-hypothesis enumeration. Eighty-eight audits cover 248 threshold-mass comparisons plus exact risks, expected risk and failure probability; six learner edges include empty and contradictory samples. All pass.
  • Separately checked the critical-interval proof for arbitrary finite-domain masses, including no bad threshold, zero masses, equality at epsilon and m=0. The interval mass strictly exceeds epsilon, and missing it is exactly failure for this minimum-consistent-threshold learner. Realizable/agnostic, properness, sufficient versus optimal count, sample guarantee versus runtime, and bit-cost limits are accurately separated.
  • Author accepted a wording clarification: successful outputs have error at most epsilon averaged over a fresh IID draw from P, without a per-fixed-input conditional correctness guarantee. Reread the final matching paragraph and recorded AI correction. Final five hashes match; strict MDX/KaTeX and actual React HTML pass with six displays, six anchors and four answers per locale. No code, author file or repository edit by reviewer.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points existing topics to their complete articles, retaining pending directory entries. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

  • A Theory of the Learnable · Actually opened the nine-page university-hosted journal PDF through web. Printed 1134 (PDF index 0) identifies CACM November 1984, 27(11), and the earlier STOC version; read introduction lines 51–83. Printed 1136–1137 (indices 2–3), §§2–3, lines 201–269 specify distributions over positive examples, EXAMPLES and ORACLE, polynomial time, one-sided correctness, and the remark that two separate probability parameters are more precise. These are source text readings, not a visual scan audit or an implementation of its original protocol.
  • Understanding Machine Learning: From Theory to Algorithms — author online copy · Direct opening of https://www.cs.huji.ac.il/~shais/UnderstandingMachineLearning/understanding-machine-learning-theory-algorithms.pdf returned Internal Error. Actually read search-extracted content from that same official PDF: online page 43, Definition 3.1, gives the realizable distribution-free quantifiers; page 49, Definition 3.4 and Remark 3.2, gives general-loss agnostic comparison and proper versus representation-independent outputs; page 50, §3.4, distinguishes the book’s statistical convention from Valiant’s computational requirements. No full PDF download, full chapter review, copied asset or visual-page verification claimed.
  • A Theory of the Learnable · Independently opened the nine-page original university-hosted journal scan through web. Read p1134 publication/prior-STOC note, introduction pp1134–1135, and §§2–3 pp1136–1137, extracted lines 201–269: distribution over positive examples, EXAMPLES and optional ORACLE resources, polynomial runtime, no false-positive outputs under the one-sided requirement, and one adjustable parameter in both probability bounds with a two-parameter refinement noted. The modern labeled-IID threshold learner is accurately distinguished. No visual scan audit, later theorem reproduction or historical runtime claim inferred from modern code.
  • Understanding Machine Learning: From Theory to Algorithms — author online copy · Independently read full targeted-search extracts from the same official author-hosted PDF: online p43 Definition 3.1 for distribution-free realizable quantifiers; p49 Definition 3.4 and Remark 3.2 for agnostic loss comparison and proper/representation-independent outputs; p50 §3.4 for the authors’ statistical versus Valiant computational conventions. Direct PDF access had failed in prior peer work; no full-book or visual-page audit claimed.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.