Module contents
Lesson 20 of 24Advanced 110 min

Sub-Gaussian and sub-exponential variables: Hoeffding and Bernstein

The modern language of concentration: sub-Gaussian and sub-exponential variables, their Orlicz norms and equivalent characterizations. These yield Hoeffding (range), Bernstein (variance plus range) and the maximal √(2 log n) inequality, three major tools for sizing evaluations and proving generalization bounds.

After this lesson you can

  • Prove equivalence of tail, moment and MGF characterizations of sub-Gaussianity.
  • Prove Hoeffding’s lemma and inequality.
  • Apply Bernstein and explain when it gives 1/n rather than 1/√n rates.
  • Bound the expected maximum of n sub-Gaussian variables.
  • Construct non-asymptotic intervals (Hoeffding, empirical Bernstein, Chernoff–KL) and compare their coverage with the CLT.

Before you start

Motivation: is a one-point difference real?

You have two models, A and B, and a test set. A achieves 81% accuracy and B 80%. Is A better, or is the difference sampling noise from the examples? And if the dataset has not yet been built, how many examples are needed for a one-point difference to mean something?

The textbook answer is the central limit theorem: the sample mean is approximately normal, with variance σ2/n\sigma^2/n, so at 95% confidence error is at most 1.96 σ/n1.96\,\sigma/\sqrt{n}. For accuracy near 0.50.5 (σ2=1/4\sigma^2 = 1/4) and error ±0.01\pm 0.01 this gives n=1.962⋅0.25/0.012≈9604n = 1.96^2 \cdot 0.25 / 0.01^2 \approx 9604 examples. But “approximately” is the important word. The CLT is a statement about limit n→∞n \to \infty; it does not say how wrong the approximation is at your particular nn, and it is very wrong exactly where it matters most: small error rates, asymmetric tails, few examples. The other familiar tool, Chebyshev’s inequality, is a guarantee but very expensive: P(∣Xˉn−μ∣≥ε)≤σ2/(nε2)\Pr(\abs{\bar X_n - \mu} \ge \eps) \le \sigma^2/(n\eps^2) requires n=0.25/(0.05⋅0.012)=50 000n = 0.25/(0.05 \cdot 0.01^2) = 50\,000, five times more. The culprit is factor 1/δ1/\delta: Chebyshev uses only two moments and cannot know a mean’s tail decays exponentially.

This lesson builds guarantees actually used in practice: non-asymptotic (valid for each nn, with explicit constants) and exponential in deviation, so confidence costs log⁡(1/δ)\log(1/\delta) rather than 1/δ1/\delta. There are three results, all from the previous lesson’s Chernoff method:

  • Hoeffding only requires each observation to lie in an interval [a,b][a, b]: half-width (b−a)log⁡(2/δ)/(2n)(b - a)\sqrt{\log(2/\delta)/(2n)}. For accuracy in [0,1][0, 1] with ±0.01\pm 0.01 at 95%, it requires 18 44518\,445 examples.
  • Bernstein also uses variance σ2\sigma^2 and deviation bound bb, ∣Xi−μ∣≤b\abs{X_i - \mu} \le b: half-width 2σ2log⁡(2/δ)/n+blog⁡(2/δ)/(3n)\sqrt{2\sigma^2\log(2/\delta)/n} + b\log(2/\delta)/(3n). When σ2\sigma^2 is small relative to the range, it wins by a lot.
  • The maximal inequality: the maximum of nn variables with Gaussian tails grows as 2log⁡n\sqrt{2\log n}, independent or not. This is the cost of comparing many models at once.

Return to the two models. The correct approach is pairing: for each example, Di=aciertoA−aciertoB∈{−1,0,1}D_i = \text{acierto}_A - \text{acierto}_B \in \{-1, 0, 1\}, and estimate E[D]\E[D]. Hoeffding with range 2 requires 73 77873\,778 examples for ±0.01\pm 0.01 at 95%. But if the models disagree on only 6% of examples, Var⁡(D)≤E[D2]=0.06\Var(D) \le \E[D^2] = 0.06, and Bernstein requires 49194919: fifteen times fewer. That difference between the cost of range and variance is the first figure.

InteractiveHoeffding versus Bernstein
Two-sided interval half-width ε\varepsilon versus nn (log-log)
n* slope −1/2
  • Hoeffding (range only)
  • Bernstein (variance and range)
  • Chernoff-KL (upper side)
  • CLT: asymptotic reference
Intervals p±εp \pm \varepsilon with n=1 000n = 1\,000
−0.0200.020.04impossible: < 0p = 0.01HoeffdingBernsteinChernoff-KLCLT (no guarantee)
The gray region is the part of the interval below 0: Hoeffding includes it because it does not know the variance is small.
0.01
1 000
Confidence 1−δ1 - \delta
σ2=p(1−p)\sigma^2 = p(1-p) versus squared range0.0099 versus 1
Hoeffding half-width0.0429
Bernstein half-width0.00976
Bernstein terms: 2σ2L/n\sqrt{2\sigma^2 L/n} and bL/(3n)bL/(3n)0.00855 and 0.00122
Hoeffding / Bernstein4.4×
Elbow n∗=b2L/(18σ2)n^* = b^2 L / (18\sigma^2)20
nn for error p/10p/10: Hoeffding versus Bernstein1.84·10⁶ versus 75500
Gaussian regime: 2σ2L/n\sqrt{2\sigma^2 L/n} dominates; Bernstein is Hoeffding with σ2\sigma^2 in place of 1/41/4.
Variables in [0,1][0, 1] with mean pp and maximum compatible variance p(1−p)p(1-p) (Bernoulli variance). Left: each two-sided interval’s half-width versus nn on log-log axes: Hoeffding has slope −1/2-1/2 and ignores pp; Bernstein and Chernoff–KL do not. Right: intervals for selected nn, with the impossible portion (below 0) faded. Lower pp to 0.0010.001: how much narrower is Bernstein? Find Bernstein’s elbow n∗n^*: to its left the slope is −1-1, the fast rate. Why is the gray CLT line narrower still, and why is that not good news?

The gray CLT line lies below all the others. It is an approximation, not a bound, and the last figure shows how badly it fails with small nn. The other three are guarantees: any nn, any distribution in [0,1][0, 1] with that mean.

From the Chernoff method to a class of variables

Recall the Chernoff method: for every λ≥0\lambda \ge 0, Markov’s inequality applied to eλXe^{\lambda X} gives

P(X≥t)≤e−λt EeλX=exp⁡(−(λt−ψX(λ))),ψX(λ)=log⁡EeλX,\Pr(X \ge t) \le e^{-\lambda t}\,\E e^{\lambda X} = \exp\big(-(\lambda t - \psi_X(\lambda))\big), \qquad \psi_X(\lambda) = \log \E e^{\lambda X},

where ψX\psi_X is the cumulant-generating function. Optimizing over λ\lambda converts any upper bound on ψX\psi_X into a tail bound. If X∼N(0,σ2)X \sim \Normal(0, \sigma^2), ψX(λ)=σ2λ2/2\psi_X(\lambda) = \sigma^2\lambda^2/2, the supremum of λt−σ2λ2/2\lambda t - \sigma^2\lambda^2/2 is attained at λ=t/σ2\lambda = t/\sigma^2 and equals t2/(2σ2)t^2/(2\sigma^2): Gaussian tail e−t2/(2σ2)e^{-t^2/(2\sigma^2)}.

The key observation is that the argument does not use XX being Gaussian: only ψX(λ)≤σ2λ2/2\psi_X(\lambda) \le \sigma^2\lambda^2/2. Any variable whose moment-generating function is dominated by a Gaussian’s inherits its tail. This defines a whole class of variables closed under independent sums; everything else in the lesson follows.

Proof

Write Y=X−μY = X - \mu. (1) Chernoff with λ=t/σ2\lambda = t/\sigma^2: P(Y≥t)≤e−λt+σ2λ2/2=e−t2/(2σ2)\Pr(Y \ge t) \le e^{-\lambda t + \sigma^2\lambda^2/2} = e^{-t^2/(2\sigma^2)}. The lower tail is the upper tail of −Y-Y, which satisfies the same assumption (replace λ\lambda by −λ-\lambda), and the two-sided tail is the union bound of both.

(2) The MGF of YY is finite for all R\R, so it is analytic near 0 and EeλY=1+λE[Y]+λ22E[Y2]+o(λ2)=1+λ22Var⁡(X)+o(λ2)\E e^{\lambda Y} = 1 + \lambda\E[Y] + \tfrac{\lambda^2}{2}\E[Y^2] + o(\lambda^2) = 1 + \tfrac{\lambda^2}{2}\Var(X) + o(\lambda^2). On the other hand eσ2λ2/2=1+λ22σ2+o(λ2)e^{\sigma^2\lambda^2/2} = 1 + \tfrac{\lambda^2}{2}\sigma^2 + o(\lambda^2). Subtract, divide by λ2/2\lambda^2/2, and take λ→0\lambda \to 0: Var⁡(X)≤σ2\Var(X) \le \sigma^2.

(3) By independence the sum’s MGF is the product: Eeλ∑iaiYi=∏iEe(λai)Yi≤∏ieσi2ai2λ2/2\E e^{\lambda\sum_i a_i Y_i} = \prod_i \E e^{(\lambda a_i)Y_i} \le \prod_i e^{\sigma_i^2a_i^2\lambda^2/2}. For the mean, ai=1/na_i = 1/n, and apply (1).

∎

Property (3) is why the definition uses the MGF: it is the only characterization below that multiplies cleanly when independent variables are summed. And (2) contains the lesson’s first trap: the variance proxy bounds variance, but can be much larger.

The last example motivates Bernstein. For rare events, even the best sub-Gaussian proxy does not reflect actual variance, and a bound using only σopt2\sigma^2_{\text{opt}} is conservative by factor 10\sqrt{10} with p=0.01p = 0.01 and 72\sqrt{72} with p=0.001p = 0.001.

Four faces of the same property

The MGF definition is convenient for sums, but not what is checked in practice. Often you know something about tails, moments, or EeX2/t2\E e^{X^2/t^2}. This section’s central theorem says all four are the same property, with parameters differing only by universal constants.

Three useful values: EeZ2/t2=(1−2/t2)−1/2\E e^{Z^2/t^2} = (1 - 2/t^2)^{-1/2} for Z∼N(0,1)Z \sim \Normal(0, 1), equal to 2 at t2=8/3t^2 = 8/3, so ∥Z∥ψ2=8/3≈1.633\norm{Z}_{\psi_2} = \sqrt{8/3} \approx 1.633. For a Rademacher, e1/t2=2e^{1/t^2} = 2 gives ∥ε∥ψ2=1/log⁡2≈1.201\norm{\varepsilon}_{\psi_2} = 1/\sqrt{\log 2} \approx 1.201. And if ∣X∣≤M\abs{X} \le M, then ∥X∥ψ2≤M/log⁡2\norm{X}_{\psi_2} \le M/\sqrt{\log 2}.

Proof

(a) ⇒ (b). This is property (1) above.

(b) ⇒ (c). For a nonnegative variable, E∣X∣p=∫0∞p tp−1P(∣X∣≥t) ⁣dt\E\abs{X}^p = \int_0^\infty p\,t^{p-1}\Pr(\abs{X} \ge t)\dd t (by Tonelli applied to ∣X∣p=∫0∣X∣p tp−1 ⁣dt\abs{X}^p = \int_0^{\abs{X}} p\,t^{p-1}\dd t). With the tail bound and substitution u=t2/(2s2)u = t^2/(2s^2),

E∣X∣p≤2p∫0∞tp−1e−t2/(2s2) ⁣dt=p (2s2)p/2 Γ(p/2).\E\abs{X}^p \le 2p\int_0^\infty t^{p-1}e^{-t^2/(2s^2)}\dd t = p\,(2s^2)^{p/2}\,\Gamma(p/2).

For x≥1x \ge 1, Γ(x)≤xx\Gamma(x) \le x^x, so with p≥2p \ge 2 we obtain E∣X∣p≤p (2s2)p/2(p/2)p/2=p (s2p)p/2\E\abs{X}^p \le p\,(2s^2)^{p/2}(p/2)^{p/2} = p\,(s^2p)^{p/2} and ∥X∥p≤p1/p sp\norm{X}_p \le p^{1/p}\,s\sqrt{p}. Factor p1/pp^{1/p} is at most e1/e≈1.445e^{1/e} \approx 1.445.

(c) ⇒ (d). Expand the exponential and use monotone convergence to exchange sum and expectation:

EeX2/t2=1+∑k≥1EX2kk! t2k≤1+∑k≥1(K2k)2kk! t2k≤1+∑k≥1(2eK2t2)k,\E e^{X^2/t^2} = 1 + \sum_{k \ge 1}\frac{\E X^{2k}}{k!\,t^{2k}} \le 1 + \sum_{k \ge 1}\frac{(K\sqrt{2k})^{2k}}{k!\,t^{2k}} \le 1 + \sum_{k \ge 1}\Big(\frac{2eK^2}{t^2}\Big)^k,

where the last step uses k!≥(k/e)kk! \ge (k/e)^k. With t2=4eK2t^2 = 4eK^2 the series is ∑k2−k=1\sum_k 2^{-k} = 1 and the total 2. Therefore ∥X∥ψ2≤2e K\norm{X}_{\psi_2} \le 2\sqrt{e}\,K.

(d) ⇒ (a). Let K=∥X∥ψ2K = \norm{X}_{\psi_2}, so EeX2/K2≤2\E e^{X^2/K^2} \le 2 (the infimum is attained, again by monotone convergence). Use elementary inequality ex≤x+ex2e^x \le x + e^{x^2} for every x∈Rx \in \R. (If x≥1x \ge 1, ex2≥exe^{x^2} \ge e^x; if x≤−1x \le -1, ex−x≤e−1+∣x∣≤1+x2≤ex2e^x - x \le e^{-1} + \abs{x} \le 1 + x^2 \le e^{x^2}; if ∣x∣<1\abs{x} < 1, ex−x=1+∑k≥2xk/k!≤1+(e−2)x2≤ex2e^x - x = 1 + \sum_{k \ge 2}x^k/k! \le 1 + (e - 2)x^2 \le e^{x^2}.) Taking expectations with x=λXx = \lambda X and using EX=0\E X = 0,

EeλX≤Eeλ2X2.\E e^{\lambda X} \le \E e^{\lambda^2X^2}.

If ∣λ∣K≤1\abs{\lambda}K \le 1, function y↦yλ2K2y \mapsto y^{\lambda^2K^2} is concave and Jensen’s inequality gives Eeλ2X2=E[(eX2/K2)λ2K2]≤2λ2K2=e(log⁡2)λ2K2\E e^{\lambda^2X^2} = \E\big[(e^{X^2/K^2})^{\lambda^2K^2}\big] \le 2^{\lambda^2K^2} = e^{(\log 2)\lambda^2K^2}. If ∣λ∣K>1\abs{\lambda}K > 1, use λX≤λ2K2/2+X2/(2K2)\lambda X \le \lambda^2K^2/2 + X^2/(2K^2) instead and Jensen with exponent 1/21/2: EeλX≤eλ2K2/22≤eλ2K2(1+log⁡2)/2\E e^{\lambda X} \le e^{\lambda^2K^2/2}\sqrt{2} \le e^{\lambda^2K^2(1 + \log 2)/2}, because λ2K2>1\lambda^2K^2 > 1. In both cases the exponent is at most 0.85 λ2K20.85\,\lambda^2K^2, that is, σ2=1.7K2\sigma^2 = 1.7K^2.

∎

Two comments. First, centering is needed only for (a): a bounded uncentered variable satisfies (b), (c), and (d), but EeλX=eλμ(1+O(λ2))\E e^{\lambda X} = e^{\lambda\mu}(1 + O(\lambda^2)) cannot stay below ecλ2e^{c\lambda^2} near 0 if μ≠0\mu \neq 0. Second, the constants are poor (going around the cycle multiplies the parameter by about 6) and do not matter: the theorem says there is one scale, ∥X∥ψ2\norm{X}_{\psi_2}, measured by all characterizations. When good constants are needed, work directly with the MGF.

The next figure places the three observable characterizations side by side for six laws, all centered with variance 1 for fair comparison.

InteractiveIs it sub-Gaussian?
MGF: log⁡EeλX\log \E e^{\lambda X} versus parabolas
∞ for λ ≥ 1
Tails: P(∣X∣>t)\Pr(|X| > t) on a logarithmic scale
Moments: ∥X∥p/p\|X\|_p / \sqrt{p}
  • Exponential − 1
  • variance parabola λ2/2\lambda^2/2
  • reference Gaussian
Moments divided by
Var⁡(X)\Var(X)1
Optimal proxy σopt2=sup⁡λ2log⁡EeλX/λ2\sigma^2_{\text{opt}} = \sup_\lambda 2\log\E e^{\lambda X}/\lambda^2∞
∥X∥ψ2\|X\|_{\psi_2}∞
∥X∥ψ1\|X\|_{\psi_1}1.531
Sub-exponential but not sub-Gaussian: the MGF exists only for λ<1\lambda < 1, the tail is linear on a logarithmic scale, and ∥X∥p\|X\|_p grows like pp, not p\sqrt{p}.
Three tests of the same property. Left: log⁡EeλX\log\E e^{\lambda X} versus the variance parabola λ2/2\lambda^2/2 and the optimal-proxy parabola. Center: tail P(∣X∣>t)\Pr(\abs{X} > t) on log scale, where a Gaussian tail is a downward parabola and an exponential a line. Right: ∥X∥p/p\norm{X}_p/\sqrt{p}, bounded if and only if the law is sub-Gaussian. Start with exponential: its MGF explodes at λ=1\lambda = 1 and no parabola covers it; divide moments by pp instead of p\sqrt{p} and the curve flattens. Switch to Bernoulli and lower qq: what happens to σopt2\sigma^2_{\text{opt}} with variance fixed at 1? Finish with Student’s t.

For the exponential all three tests fail together and in the same way: its MGF is finite only for λ<1\lambda < 1, the tail is a straight line on log scale (e−1−te^{-1-t}), and ∥X∥p\norm{X}_p grows as pp, not p\sqrt{p}. It is not sub-Gaussian, but almost: it is the prototype of the next class. Student’s t with 5 degrees passes none: MGF is infinite for every λ≠0\lambda \neq 0, its tail is polynomial, and moments of order 5 or more do not exist.

Hoeffding’s lemma

Bounded variables are the case most common in machine learning: losses in [0,1][0, 1], successes, indicators. Hoeffding’s lemma says they are sub-Gaussian with a proxy depending only on range.

Proof

Since XX is bounded, ψ(λ)=log⁡EeλX\psi(\lambda) = \log\E e^{\lambda X} is finite and infinitely differentiable, with ψ(0)=0\psi(0) = 0 and ψ′(0)=EX=0\psi'(0) = \E X = 0. For the second derivative, define the tilted law QλQ_\lambda by  ⁣dQλ ⁣dP=eλX/EeλX\frac{\dd Q_\lambda}{\dd\Pr} = e^{\lambda X}/\E e^{\lambda X} (a change of measure with positive density). Differentiating under the integral,

ψ′(λ)=E[XeλX]EeλX=EQλ[X],ψ′′(λ)=E[X2eλX]EeλX−(E[XeλX]EeλX)2=Var⁡Qλ(X).\psi'(\lambda) = \frac{\E[Xe^{\lambda X}]}{\E e^{\lambda X}} = \E_{Q_\lambda}[X], \qquad \psi''(\lambda) = \frac{\E[X^2e^{\lambda X}]}{\E e^{\lambda X}} - \Big(\frac{\E[Xe^{\lambda X}]}{\E e^{\lambda X}}\Big)^2 = \Var_{Q_\lambda}(X).

Under QλQ_\lambda, XX remains in [a,b][a, b], and variance of any variable in [a,b][a, b] is at most (b−a)2/4(b-a)^2/4: Var⁡(X)≤E(X−a+b2)2≤(b−a2)2\Var(X) \le \E\big(X - \tfrac{a+b}{2}\big)^2 \le \big(\tfrac{b-a}{2}\big)^2. By Taylor’s theorem with Lagrange remainder, for some ξ\xi between 0 and λ\lambda,

ψ(λ)=ψ(0)+ψ′(0)λ+12ψ′′(ξ)λ2≤(b−a)24⋅λ22.\psi(\lambda) = \psi(0) + \psi'(0)\lambda + \tfrac{1}{2}\psi''(\xi)\lambda^2 \le \frac{(b-a)^2}{4}\cdot\frac{\lambda^2}{2}.∎

The proof shows where the constant comes from: 1/8=12⋅141/8 = \tfrac12 \cdot \tfrac14, half the maximum variance on an interval of length 1. The constant cannot be improved: with a Rademacher scaled to ±(b−a)/2\pm(b-a)/2, ψ(λ)=log⁡cosh⁡(λ(b−a)/2)=λ2(b−a)2/8+O(λ4)\psi(\lambda) = \log\cosh\big(\lambda(b-a)/2\big) = \lambda^2(b-a)^2/8 + O(\lambda^4). Exercises ask you to prove the lemma another way, using only convexity.

Hoeffding’s inequality

Proof

Xi−EXiX_i - \E X_i is centered and lies in an interval of length bi−aib_i - a_i, so by the lemma it is SG⁡((bi−ai)2/4)\operatorname{SG}\big((b_i-a_i)^2/4\big). By the sum property, S∈SG⁡(v)S \in \operatorname{SG}(v) with v=∑i(bi−ai)2/4v = \sum_i(b_i-a_i)^2/4, and its tail is at most e−t2/(2v)=e−2t2/∑i(bi−ai)2e^{-t^2/(2v)} = e^{-2t^2/\sum_i(b_i-a_i)^2}.

∎

Equating the two-sided bound to δ\delta gives the two everyday forms:

∣Xˉn−μ∣≤(b−a)log⁡(2/δ)2n  con probabilidad≥1−δ,n≥(b−a)2log⁡(2/δ)2ε2  basta para error≤ε.\abs{\bar X_n - \mu} \le (b - a)\sqrt{\frac{\log(2/\delta)}{2n}} \ \text{ con probabilidad} \ge 1 - \delta, \qquad n \ge \frac{(b-a)^2\log(2/\delta)}{2\eps^2} \ \text{ basta para error} \le \eps.

Compare the dependence on δ\delta with Chebyshev’s. For δ=10−6\delta = 10^{-6}, Hoeffding multiplies sample size by log⁡(2⋅106)/2≈7.3\log(2\cdot 10^6)/2 \approx 7.3 and Chebyshev, with maximum variance 1/41/4, by 1/(4δ)=250 0001/(4\delta) = 250\,000. That logarithm allows union bounds over thousands or millions of events (hypotheses, questions, bandit arms) paying only log⁡\log of their number: with ∣H∣\abs{\Hyp} hypotheses, sup⁡h∈H∣R^(h)−R(h)∣≤log⁡(2∣H∣/δ)/(2n)\sup_{h \in \Hyp}\abs{\hat R(h) - R(h)} \le \sqrt{\log(2\abs{\Hyp}/\delta)/(2n)} for losses in [0,1][0, 1], the finite-class uniform bound. The confidence radius of UCB1, 2log⁡t/na\sqrt{2\log t/n_a}, is exactly a Hoeffding interval with decreasing δ\delta.

The relative-entropy version

Hoeffding’s paper also contains a tighter bound for variables in [0,1][0, 1]. By convexity, eλx≤1−x+xeλe^{\lambda x} \le 1 - x + xe^\lambda on [0,1][0, 1], so EeλXi≤1−μi+μieλ\E e^{\lambda X_i} \le 1 - \mu_i + \mu_i e^\lambda: among all laws in [0,1][0, 1] with a given mean, Bernoulli has the largest MGF. By logarithm concavity, ∏i(1−μi+μieλ)≤(1−μ+μeλ)n\prod_i(1 - \mu_i + \mu_ie^\lambda) \le (1 - \mu + \mu e^\lambda)^n, which is a binomial MGF, and the previous lesson’s binomial Chernoff calculation gives

P(Xˉn≥μ+t)≤exp⁡(−n kl⁡(μ+t ∥ μ)),kl⁡(q ∥ p)=qlog⁡qp+(1−q)log⁡1−q1−p,\Pr(\bar X_n \ge \mu + t) \le \exp\big(-n\,\operatorname{kl}(\mu + t \,\|\, \mu)\big), \qquad \operatorname{kl}(q \,\|\, p) = q\log\frac{q}{p} + (1-q)\log\frac{1-q}{1-p},

the Kullback–Leibler divergence between two Bernoullis. Since kl⁡(q ∥ p)≥2(q−p)2\operatorname{kl}(q \,\|\, p) \ge 2(q - p)^2 (Pinsker’s inequality), this bound implies Hoeffding. But near boundaries it is much better: kl⁡(p+t ∥ p)≈t2/(2p(1−p))\operatorname{kl}(p + t \,\|\, p) \approx t^2/(2p(1-p)), so it behaves like a bound using true variance. Inverting it gives the Chernoff–KL interval, {q:nkl⁡(p^ ∥ q)≤log⁡(2/δ)}\{q : n\operatorname{kl}(\hat p \,\|\, q) \le \log(2/\delta)\}, the aqua curve in the first figure and basis of KL-UCB.

Sub-exponential variables

Many important quantities are not sub-Gaussian. If Z∼N(0,1)Z \sim \Normal(0, 1), EeλZ2=(1−2λ)−1/2\E e^{\lambda Z^2} = (1 - 2\lambda)^{-1/2} is infinite for λ≥1/2\lambda \ge 1/2, so Z2−1Z^2 - 1 has no finite MGF for all R\R. Its tail is P(Z2>t)=P(∣Z∣>t)≈e−t/2\Pr(Z^2 > t) = \Pr(\abs{Z} > \sqrt{t}) \approx e^{-t/2}: exponential, not Gaussian. The same holds for exponential and gamma waiting times, products XiYiX_iY_i appearing in covariance estimation, and squared norms ∥x∥2=∑ixi2\norm{\vb{x}}^2 = \sum_i x_i^2 of random vectors. Their MGFs are finite and parabola-like only near λ=0\lambda = 0.

As in the sub-Gaussian case, for a centered variable the following are equivalent up to universal constants: (a) the MGF condition in a neighborhood of 0; (b) tails P(∣X∣≥t)≤2e−t/K\Pr(\abs{X} \ge t) \le 2e^{-t/K}; (c) moments ∥X∥p≤Kp\norm{X}_p \le Kp; (d) ∥X∥ψ1<∞\norm{X}_{\psi_1} < \infty. The proof repeats the earlier one replacing t2t^2 by tt and p\sqrt{p} by pp; it is in chapter 2 of Vershynin’s book. Every sub-Gaussian is sub-exponential (with arbitrary α\alpha), but not conversely.

Proof

The first is the definition: EeX2/t≤2\E e^{X^2/t} \le 2 is the same as EeX2/(t)2≤2\E e^{X^2/(\sqrt t)^2} \le 2. For the second, normalize K=∥X∥ψ2K = \norm{X}_{\psi_2} and L=∥Y∥ψ2L = \norm{Y}_{\psi_2}. By ∣ab∣≤(a2+b2)/2\abs{ab} \le (a^2 + b^2)/2 and e(u+v)/2=euev≤(eu+ev)/2e^{(u + v)/2} = \sqrt{e^ue^v} \le (e^u + e^v)/2,

Ee∣XY∣/(KL)≤Ee12(X2/K2+Y2/L2)≤12(EeX2/K2+EeY2/L2)≤2.\E e^{\abs{XY}/(KL)} \le \E e^{\frac12\big(X^2/K^2 + Y^2/L^2\big)} \le \tfrac12\big(\E e^{X^2/K^2} + \E e^{Y^2/L^2}\big) \le 2.∎

This theorem explains where sub-exponentials arise in practice: the product of two sub-Gaussian coordinates (an entry of X⊤X/n\mat{X}\T\mat{X}/n) and the square of one (each summand of ∥x∥2\norm{\vb{x}}^2) are sub-exponential. As in the sub-Gaussian case, independent sums combine: if Xi∈SE⁡(νi2,αi)X_i \in \operatorname{SE}(\nu_i^2, \alpha_i) are independent, ∑iXi∈SE⁡(∑iνi2,max⁡iαi)\sum_i X_i \in \operatorname{SE}\big(\sum_i\nu_i^2, \max_i\alpha_i\big), multiplying MGFs on the common interval ∣λ∣<1/max⁡iαi\abs{\lambda} < 1/\max_i\alpha_i.

Bernstein’s inequality

Now apply Chernoff to a sub-exponential sum. The only difference from the sub-Gaussian case is that λ\lambda cannot exceed 1/α1/\alpha, producing two regimes.

Proof

By Chernoff and the sum’s MGF, log⁡P(∑iXi≥t)≤−λt+ν2λ2/2\log\Pr(\sum_iX_i \ge t) \le -\lambda t + \nu^2\lambda^2/2 for every 0≤λ<1/α0 \le \lambda < 1/\alpha (and by continuity also at λ=1/α\lambda = 1/\alpha as a limit). The unconstrained minimum is at λ=t/ν2\lambda = t/\nu^2. If t≤ν2/αt \le \nu^2/\alpha, that λ\lambda is admissible and gives −t2/(2ν2)-t^2/(2\nu^2). Otherwise take λ=1/α\lambda = 1/\alpha: the exponent is −t/α+ν2/(2α2)≤−t/α+t/(2α)=−t/(2α)-t/\alpha + \nu^2/(2\alpha^2) \le -t/\alpha + t/(2\alpha) = -t/(2\alpha) because ν2/α<t\nu^2/\alpha < t.

∎

For small deviations the sum behaves like a Gaussian with variance ν2\nu^2; for large deviations, like one exponential with scale α\alpha: the tail is dominated by large summands, not accumulation of many small ones. Applied to χn2∈SE⁡(4n,4)\chi^2_n \in \operatorname{SE}(4n, 4) with t=nεt = n\eps and ε∈(0,1)\eps \in (0, 1) (always in the Gaussian regime because nε≤4n/4n\eps \le 4n/4):

P(∣χn2n−1∣≥ε)≤2e−nε2/8.\Pr\Big(\Big|\frac{\chi^2_n}{n} - 1\Big| \ge \eps\Big) \le 2e^{-n\eps^2/8}.

This is central to the Johnson–Lindenstrauss lemma: the squared norm of a Gaussian projection concentrates around its mean with relative deviation O(1/n)\bigO(1/\sqrt{n}).

The bounded-variable version

Bernstein’s most-used form does not mention sub-exponential parameters, but what is usually known: upper bound bb and variance.

Proof

(1) Let ϕ(u)=(eu−1−u)/u2\phi(u) = (e^u - 1 - u)/u^2, continuously extended with ϕ(0)=1/2\phi(0) = 1/2. By Taylor’s formula with integral remainder, ϕ(u)=∫01(1−s)esu ⁣ds\phi(u) = \int_0^1(1 - s)e^{su}\dd s, increasing in uu. For λ≥0\lambda \ge 0 and Xi≤bX_i \le b, λXi≤λb\lambda X_i \le \lambda b, so

eλXi=1+λXi+λ2Xi2 ϕ(λXi)≤1+λXi+λ2Xi2 ϕ(λb).e^{\lambda X_i} = 1 + \lambda X_i + \lambda^2X_i^2\,\phi(\lambda X_i) \le 1 + \lambda X_i + \lambda^2X_i^2\,\phi(\lambda b).

Taking expectations, EeλXi≤1+λ2EXi2 ϕ(λb)≤exp⁡(λ2EXi2 ϕ(λb))\E e^{\lambda X_i} \le 1 + \lambda^2\E X_i^2\,\phi(\lambda b) \le \exp\big(\lambda^2\E X_i^2\,\phi(\lambda b)\big). Also, since k!≥2⋅3k−2k! \ge 2\cdot 3^{k-2} for k≥2k \ge 2, for 0≤u<30 \le u < 3 we have ϕ(u)=∑k≥2uk−2/k!≤12∑j≥0(u/3)j=12(1−u/3)\phi(u) = \sum_{k \ge 2}u^{k-2}/k! \le \tfrac12\sum_{j \ge 0}(u/3)^j = \frac{1}{2(1 - u/3)}. Multiply over ii by independence.

(2) Chernoff with (1): log⁡P(S≥t)≤−λt+vλ22(1−bλ/3)\log\Pr(S \ge t) \le -\lambda t + \frac{v\lambda^2}{2(1 - b\lambda/3)}. With λ=t/(v+bt/3)\lambda = t/(v + bt/3), which is less than 3/b3/b, we have 1−bλ/3=v/(v+bt/3)1 - b\lambda/3 = v/(v + bt/3) and the second term equals λt/2\lambda t/2. The exponent becomes −λt/2=−t2/(2(v+bt/3))-\lambda t/2 = -t^2/(2(v + bt/3)).

(3) Write c=b/3c = b/3, s=2L/vs = \sqrt{2L/v} and choose λ=s/(1+cs)<1/c\lambda = s/(1 + cs) < 1/c. Then 1−cλ=1/(1+cs)1 - c\lambda = 1/(1 + cs) and vλ22(1−cλ)=vs22(1+cs)=L1+cs\frac{v\lambda^2}{2(1 - c\lambda)} = \frac{vs^2}{2(1 + cs)} = \frac{L}{1 + cs}. With u=2vL+cLu = \sqrt{2vL} + cL and s2vL=2Ls\sqrt{2vL} = 2L, λu=2L+csL1+cs\lambda u = \frac{2L + csL}{1 + cs}. The Chernoff exponent is −λu+L1+cs=−L+csL1+cs=−L-\lambda u + \frac{L}{1 + cs} = -\frac{L + csL}{1 + cs} = -L.

∎

Form (3) suits intervals and is slightly tighter than inverting (2): solving for tt in t2=2L(v+bt/3)t^2 = 2L(v + bt/3) gives t=bL/3+(bL/3)2+2vLt = bL/3 + \sqrt{(bL/3)^2 + 2vL}, which with x+y≤x+y\sqrt{x + y} \le \sqrt{x} + \sqrt{y} is often simplified to 2vL+2bL/3\sqrt{2vL} + 2bL/3, twice the range term. For the mean of nn independent identically distributed variables with variance σ2\sigma^2 and ∣Xi−μ∣≤b\abs{X_i - \mu} \le b, applied to each tail with L=log⁡(2/δ)L = \log(2/\delta):

∣Xˉn−μ∣≤2σ2log⁡(2/δ)n⏟reˊgimen gaussiano+blog⁡(2/δ)3n⏟reˊgimen exponencialcon probabilidad≥1−δ.\abs{\bar X_n - \mu} \le \underbrace{\sqrt{\frac{2\sigma^2\log(2/\delta)}{n}}}_{\text{régimen gaussiano}} + \underbrace{\frac{b\log(2/\delta)}{3n}}_{\text{régimen exponencial}} \qquad \text{con probabilidad} \ge 1 - \delta.

The first term is the CLT term, σ/n\sigma/\sqrt{n}, multiplied by 2log⁡(2/δ)\sqrt{2\log(2/\delta)} rather than quantile z1−δ/2z_{1-\delta/2}; the second is the price of non-Gaussianity. Compared with Hoeffding, the dominant term replaces (b−a)2/4(b-a)^2/4, worst-case variance, with true variance. Both terms are equal at n∗=b2log⁡(2/δ)/(18σ2)n^* = b^2\log(2/\delta)/(18\sigma^2): below it the range term dominates and width falls as 1/n1/n; above it, as 1/n1/\sqrt{n}. This is the elbow sought in the first figure.

Fast rates

For a variable in [0,1][0, 1], X2≤XX^2 \le X, so σ2≤EX2≤μ\sigma^2 \le \E X^2 \le \mu. Bernstein then gives, with L=log⁡(2/δ)L = \log(2/\delta),

∣Xˉn−μ∣≤2μLn+L3n.\abs{\bar X_n - \mu} \le \sqrt{\frac{2\mu L}{n}} + \frac{L}{3n}.

If the mean is of order L/nL/n (nearly zero error rate), both terms are O(L/n)\bigO(L/n): the fast rate 1/n1/n versus Hoeffding’s 1/n1/\sqrt{n}. In learning theory this is the difference between the realizable case, where minimum empirical risk is zero and n∼log⁡(∣H∣/δ)/εn \sim \log(\abs{\Hyp}/\delta)/\eps suffices, and the agnostic case requiring n∼log⁡(∣H∣/δ)/ε2n \sim \log(\abs{\Hyp}/\delta)/\eps^2. This is what happens with the motivation’s two models: paired difference DD has Var⁡(D)=P(D≠0)−(ED)2≤0.06\Var(D) = \Pr(D \neq 0) - (\E D)^2 \le 0.06, ∣D−ED∣≤2\abs{D - \E D} \le 2, and the size n≥(2σ2+2bε/3)log⁡(2/δ)/ε2n \ge (2\sigma^2 + 2b\eps/3)\log(2/\delta)/\eps^2 guaranteed by form (2) falls from 73 77873\,778 (Hoeffding) to 49194919.

Empirical Bernstein: variance without knowing it

In practice σ2\sigma^2 is unknown. The temptation is to substitute sample variance Vn=1n−1∑i(Xi−Xˉn)2V_n = \frac{1}{n-1}\sum_i(X_i - \bar X_n)^2 and proceed unchanged. This is an error, and not a subtle one.

Maurer and Pontil’s solution is to pay explicitly for uncertainty in VnV_n.

Proof

Let L=log⁡(2/δ)L = \log(2/\delta). Combine two events each with probability at most δ/2\delta/2. The first is Bernstein’s tail, form (3), with Xi→μ−Xi≤1X_i \to \mu - X_i \le 1: outside it, μ−Xˉn≤2σ2L/n+L/(3n)\mu - \bar X_n \le \sqrt{2\sigma^2L/n} + L/(3n). The second is true standard deviation exceeding sample standard deviation by more than 2L/(n−1)\sqrt{2L/(n-1)}: Maurer and Pontil prove (their theorem 10, a consequence of concentration of self-bounding functions) P(σ>Vn+2L/(n−1))≤e−L\Pr\big(\sigma > \sqrt{V_n} + \sqrt{2L/(n-1)}\big) \le e^{-L}. Outside both,

2σ2Ln≤2VnLn+2Ln2Ln−1≤2VnLn+2Ln−1,\sqrt{\frac{2\sigma^2L}{n}} \le \sqrt{\frac{2V_nL}{n}} + \sqrt{\frac{2L}{n}}\sqrt{\frac{2L}{n-1}} \le \sqrt{\frac{2V_nL}{n}} + \frac{2L}{n-1},

and 2Ln−1+L3n≤7L3(n−1)\frac{2L}{n-1} + \frac{L}{3n} \le \frac{7L}{3(n-1)}. The union probability of the two bad events is at most δ\delta.

∎

The cost is in the constant: 7/37/3 instead of 1/31/3 and log⁡(4/δ)\log(4/\delta) instead of log⁡(2/δ)\log(2/\delta) in the two-sided version. With small nn, empirical Bernstein is wider than Hoeffding; it wins when nn is large and variance small. For means of variables in [0,1][0, 1] there is a third option needing no estimation: the earlier Chernoff–KL interval. Its coverage follows from Hoeffding’s relative-entropy bound applied to each side, because μ\mu is outside the interval exactly when Xˉn\bar X_n deviates from μ\mu beyond point qq with nkl⁡(q ∥ μ)=log⁡(2/δ)n\operatorname{kl}(q \,\|\, \mu) = \log(2/\delta).

The next figure tests all five options using an asymmetric law and small nn, repeating the experiment thousands of times.

InteractiveActual interval coverage
The first 60 intervals of CLT: 13 do not contain μ\mu
  • contains μ
  • does not contain μ
  • sample mean
  • true mean μ
Failure rate across 2000 experiments versus δ=0.05\delta = 0.05
0 %5 %10 %15 %20 %25 %CLT: width 0.11721.1 %Hoeffding: width 0.2980.0 %Empirical Bernstein: width 0.5050.0 %Chernoff-KL: width 0.2160.4 %Plug-in Bernstein: width 0.18520.8 %δ
Law of each observation
0.05
30
δ\delta nominal
μ\mu and σ2\sigma^2 for each observation0.05 and 0.0475
Experiments with p^=0\hat p = 020.8 %
Failures of CLT (of 2000)21.1 %
Mean width of CLT0.117
CLT and plug-in Bernstein fail more often than the promised δ=0.05\delta = 0.05 level. The three guaranteed intervals meet it.
Each experiment takes nn observations and constructs five two-sided intervals at level 1−δ1 - \delta. Left: the first 60 intervals for the selected method, red when they miss μ\mu. Right: fraction of 2000 experiments where each method fails, versus the δ\delta line, with mean width (clipped to [0,1][0, 1]). With p=0.05p = 0.05 and n=30n = 30, which methods keep their promise? Raise nn to 1000 and lower pp to 0.010.01: when does empirical Bernstein overtake Hoeffding? Try continuous law UkU^k with large kk: more asymmetry, worse CLT.

Three lessons from the figure. The CLT severely undercovers when nμn\mu is small: with p=0.05p = 0.05 and n=30n = 30 it fails about 21% rather than 5% of the time, almost always because p^=0\hat p = 0 (probability 0.9530≈21.5 %0.95^{30} \approx 21.5\,\%) and its interval shrinks to a point. Bernstein with plug-in variance fails on those same experiments, and its extra width barely saves it from others. The three guaranteed intervals (Hoeffding, empirical Bernstein, Chernoff–KL) fail far less than allowed: they are conservative and the guarantee costs width. Of the three, Chernoff–KL is narrowest for means in [0,1][0, 1], while empirical Bernstein has the advantage of applying to any bounded variable, not only Bernoulli averages, and extending to loss functions and sample-variance penalties.

The maximal inequality

Final piece. You evaluate 100 model variants (seeds, prompts, checkpoints) and keep the best. Even if all have the same true accuracy, the best measured one exceeds the mean: it is the maximum of 100 noisy variables. By how much?

You will prove the expectation bound in the exercises; the idea is to apply Jensen to eλmax⁡iXie^{\lambda\max_iX_i} and bound the maximum of exponentials by their sum. The bound for ∣Xi∣\abs{X_i} follows by applying the first to 2n2n variables ±Xi\pm X_i. The tail bound is the union bound: with u=σ2log⁡n+tu = \sigma\sqrt{2\log n} + t,

P(max⁡iXi≥u)≤n e−u2/(2σ2)=exp⁡(log⁡n−2σ2log⁡n+2tσ2log⁡n+t22σ2)≤e−t2/(2σ2).\Pr\Big(\max_i X_i \ge u\Big) \le n\,e^{-u^2/(2\sigma^2)} = \exp\Big(\log n - \frac{2\sigma^2\log n + 2t\sigma\sqrt{2\log n} + t^2}{2\sigma^2}\Big) \le e^{-t^2/(2\sigma^2)}.

Thus the maximum not only has mean ≲σ2log⁡n\lesssim \sigma\sqrt{2\log n}: it concentrates below that value with fluctuations of size σ\sigma. For independent Gaussians the bound is first-order exact, Emax⁡iZi=2log⁡n (1−o(1))\E\max_iZ_i = \sqrt{2\log n}\,(1 - o(1)), although convergence is slow: with n=100n = 100 the exact value is 2.512.51 and the bound 3.033.03; with n=104n = 10^4, 3.853.85 versus 4.294.29.

InteractiveThe maximum of n Gaussians
Maximum of X1,…,XnX_1, \dots, X_n, each N(0,1)\Normal(0, 1)
√(2 log n) simulating 10⁷ normal variables…
  • simulated mean maximum
  • 10–90% band
  • bound 2log⁡n\sqrt{2\log n} (without independence)
  • exact for independent variables
Distribution of the maximum with n=1 000n = 1\,000 (100 replicas)
bound
1 000
Dependence
Mean maximum (100 replicas)simulating…
Bound 2log⁡n\sqrt{2\log n}3.717
Exact E[max⁡]\E[\max] if independent3.241
Mean / bound…
Standard deviation of maximum…
Effective nn (approx.: independent variables with same mean)…
One hundred replicates of nn variables N(0,1)\Normal(0, 1), with nn from 1 to 10510^5. Left: mean maximum and 10–90% band versus bound 2log⁡n\sqrt{2\log n} and the exact independent value; right: maximum histogram for selected nn, narrowing as nn grows. Next introduce dependence. With equicorrelation ρ\rho, each Xi=ρZ0+1−ρZiX_i = \sqrt{\rho}Z_0 + \sqrt{1-\rho}Z_i: what happens to mean and spread? With moving averages of window ww, neighbors almost coincide: compare “effective nn” with n/wn/w.

The bound uses only marginals, so it always holds regardless of dependence. Positive correlation helps: the maximum of highly correlated variables resembles that of fewer variables. Negative correlation can worsen matters relative to independent variables (with X2=−X1X_2 = -X_1, Emax⁡(X1,X2)=E∣X1∣≈0.80\E\max(X_1, X_2) = \E\abs{X_1} \approx 0.80, versus 0.560.56 if independent), but never above the bound. With equicorrelation the calculation is exact: max⁡iXi=ρZ0+1−ρmax⁡iZi\max_iX_i = \sqrt{\rho}Z_0 + \sqrt{1 - \rho}\max_iZ_i and the mean is multiplied by 1−ρ\sqrt{1 - \rho}. With moving averages of window ww, the maximum behaves like that of about n/wn/w independent variables. Quantifying this reduction from geometry, distance ∥Xi−Xj∥L2\norm{X_i - X_j}_{L^2} between variables, is the object of chaining techniques (Dudley, Talagrand) and Rademacher complexity.

Return to the 100 variants. If all have true accuracy 0.800.80 and each is evaluated with n=1000n = 1000 examples, each measured accuracy has standard deviation σ=0.8⋅0.2/1000≈0.0126\sigma = \sqrt{0.8\cdot 0.2/1000} \approx 0.0126, and the best of 100 appears on average about σ Emax⁡i≤100Zi≈2.51 σ≈3.2\sigma\,\E\max_{i \le 100}Z_i \approx 2.51\,\sigma \approx 3.2 points higher than its value. With the same Gaussian approximation, maximal bound σ2log⁡100≈3.8\sigma\sqrt{2\log 100} \approx 3.8 points bounds this without knowing dependence between variants. Without approximation, each measured accuracy averages 10001000 variables in [0,1][0, 1], which by Hoeffding’s lemma is SG⁡(1/(4⋅1000))\operatorname{SG}\big(1/(4\cdot 1000)\big), and the rigorous bound is 1/4000 2log⁡100≈4.8\sqrt{1/4000}\,\sqrt{2\log 100} \approx 4.8 points. This is why hyperparameter-search results are reported on a separate test set and why error bars for comparing many models cannot be those of one.

Implementation from scratch

First, the motivation’s sample sizes. The four functions are the lesson’s formulas and nothing more.

[ ]How many test examples are neededBrowser
import numpy as np
from scipy.special import ndtri

def n_chebyshev(eps, delta, var):        # P(|X̄ - μ| ≥ ε) ≤ var / (n ε²)
    return var / (delta * eps**2)

def n_hoeffding(eps, delta, rango):      # 2 exp(-2 n ε² / rango²) ≤ δ
    return rango**2 * np.log(2 / delta) / (2 * eps**2)

def n_bernstein(eps, delta, var, b):     # 2 exp(-n ε² / (2 var + 2 b ε / 3)) ≤ δ
    return (2 * var + 2 * b * eps / 3) * np.log(2 / delta) / eps**2

def n_tcl(eps, delta, var):              # aproximación asintótica, sin garantía
    return ndtri(1 - delta / 2)**2 * var / eps**2

entero = lambda x: int(np.ceil(x - 1e-9))   # el menor n que cumple la desigualdad

eps, delta = 0.01, 0.05
print("Exactitud de UN modelo, ±1 punto al 95 % (variables en [0, 1], varianza ≤ 1/4):")
print(f"  Chebyshev {entero(n_chebyshev(eps, delta, 0.25)):8d}   Hoeffding {entero(n_hoeffding(eps, delta, 1)):8d}"
      f"   TCL (p = 0.5) {entero(n_tcl(eps, delta, 0.25)):6d}")

print("\nDiferencia emparejada D = acierto_A - acierto_B ∈ {-1, 0, 1}; los modelos discrepan en un 6 %:")
var_D = 0.06                             # Var(D) ≤ E[D²] = P(discrepan)
print(f"  Hoeffding (rango 2)            {entero(n_hoeffding(eps, delta, 2)):8d}")
print(f"  Bernstein (σ² ≤ 0.06, b = 2)   {entero(n_bernstein(eps, delta, var_D, 2)):8d}")
print(f"  TCL (σ² = 0.06)                {entero(n_tcl(eps, delta, var_D)):8d}")

The ordering is expected: Chebyshev pays 1/δ1/\delta, Hoeffding pays for range, Bernstein pays for variance plus a small range term, and the CLT pays nothing because it guarantees nothing. In the paired comparison, Bernstein is within a factor of two of the CLT and a factor of fifteen from Hoeffding.

Now check Hoeffding’s lemma and variance proxies numerically. The first part samples a thousand random discrete laws on [0,1][0, 1] and calculates the ratio of centered log-MGF to the lemma’s bound; the second calculates the Bernoulli optimal proxy on a grid of λ\lambda and compares it with closed form and variance.

[ ]Hoeffding’s lemma y el proxy de varianza de la BernoulliBrowser
import numpy as np

rng = np.random.default_rng(0)
lam = np.linspace(-40, 40, 2001)
lam = lam[lam != 0]

def log_mgf_centrada(x, w, lam):
    """log E exp(λ (X - EX)) de una ley discreta con valores x y pesos w (forma estable)."""
    xc = x - w @ x
    a = np.log(w)[None, :] + lam[:, None] * xc[None, :]
    m = a.max(axis=1, keepdims=True)
    return (m + np.log(np.exp(a - m).sum(axis=1, keepdims=True)))[:, 0]

peor = 0.0
for _ in range(1000):
    k = rng.integers(2, 8)
    x = rng.uniform(0, 1, k)
    w = rng.dirichlet(np.ones(k) * rng.uniform(0.1, 3))
    a, b = x.min(), x.max()
    cociente = log_mgf_centrada(x, w, lam) / (lam**2 * (b - a)**2 / 8)
    peor = max(peor, cociente.max())
print(f"máximo de log E e^(λX) / (λ²(b-a)²/8) en 1000 leyes al azar: {peor:.4f}  (el lema dice ≤ 1)")

print("\nBernoulli(p) centrada: varianza frente al proxy óptimo (Hoeffding usa 1/4)")
for p in [0.5, 0.3, 0.1, 0.01, 0.001]:
    psi = log_mgf_centrada(np.array([0.0, 1.0]), np.array([1 - p, p]), lam)
    s2_rejilla = (2 * psi / lam**2).max()
    s2_cerrada = 0.25 if p == 0.5 else (1 - 2 * p) / (2 * np.log((1 - p) / p))
    print(f"  p = {p:<6} Var = {p*(1-p):.4f}   σ²_opt = {s2_rejilla:.4f} (fórmula {s2_cerrada:.4f})"
          f"   σ²_opt / Var = {s2_cerrada / (p*(1-p)):6.2f}")

The ratio reaches 1 without exceeding it: the lemma is exact in limit λ→0\lambda \to 0 for symmetric two-point laws. The Bernoulli table quantifies the proxy trap: with p=0.001p = 0.001 the best sub-Gaussian proxy is 72 times variance, and Hoeffding’s is 250 times.

The main lab: five intervals for means of variables in [0,1][0, 1], vectorized over thousands of experiments, and their coverage measured by simulation.

[ ]Non-asymptotic intervals and their coverage, from scratchBrowser
import numpy as np
from scipy.special import ndtri

def ic_tcl(x, delta):
    n = x.shape[-1]; m = x.mean(-1); s = x.std(-1, ddof=1)
    h = ndtri(1 - delta / 2) * s / np.sqrt(n)
    return m - h, m + h

def ic_hoeffding(x, delta):
    n = x.shape[-1]; m = x.mean(-1)
    h = np.sqrt(np.log(2 / delta) / (2 * n))
    return m - h, m + h

def ic_bernstein_empirico(x, delta):
    """Maurer y Pontil (2009), teorema 4, con δ/2 en cada cola."""
    n = x.shape[-1]; m = x.mean(-1); v = x.var(-1, ddof=1)
    L = np.log(4 / delta)
    h = np.sqrt(2 * v * L / n) + 7 * L / (3 * (n - 1))
    return m - h, m + h

def ic_bernstein_enchufado(x, delta):
    """INCORRECTO: Bernstein con la varianza muestral como si fuera la verdadera."""
    n = x.shape[-1]; m = x.mean(-1); v = x.var(-1, ddof=1)
    L = np.log(2 / delta)
    h = np.sqrt(2 * v * L / n) + L / (3 * n)
    return m - h, m + h

def kl_bern(p, q):
    p = np.clip(p, 1e-12, 1 - 1e-12); q = np.clip(q, 1e-12, 1 - 1e-12)
    return p * np.log(p / q) + (1 - p) * np.log((1 - p) / (1 - q))

def ic_kl(x, delta, iters=50):
    """{q : n kl(p̂ ‖ q) ≤ log(2/δ)}, invertido por bisección a cada lado de p̂."""
    n = x.shape[-1]; m = x.mean(-1); c = np.log(2 / delta) / n
    a, b = m.copy(), np.ones_like(m)            # extremo superior en [p̂, 1]
    for _ in range(iters):
        q = (a + b) / 2; ok = kl_bern(m, q) <= c
        a, b = np.where(ok, q, a), np.where(ok, b, q)
    hi = a
    a, b = np.zeros_like(m), m.copy()           # extremo inferior en [0, p̂]
    for _ in range(iters):
        q = (a + b) / 2; ok = kl_bern(m, q) <= c
        a, b = np.where(ok, a, q), np.where(ok, q, b)
    return b, hi

METODOS = [("TCL", ic_tcl), ("Hoeffding", ic_hoeffding), ("Bernstein emp.", ic_bernstein_empirico),
           ("Chernoff-KL", ic_kl), ("B. enchufado", ic_bernstein_enchufado)]

def evaluar(muestreo, mu, n, delta=0.05, M=4000, seed=0):
    x = muestreo(np.random.default_rng(seed), (M, n))
    for nombre, f in METODOS:
        lo, hi = f(x, delta)
        fallo = np.mean((mu < lo) | (mu > hi))
        anchura = np.mean(np.minimum(hi, 1) - np.maximum(lo, 0))
        print(f"    {nombre:15s} fallo {100*fallo:5.1f} %   anchura media {anchura:.4f}")

casos = [("Bernoulli(0.05), n = 30", lambda g, s: (g.random(s) < 0.05) * 1.0, 0.05, 30),
         ("Bernoulli(0.01), n = 1000", lambda g, s: (g.random(s) < 0.01) * 1.0, 0.01, 1000),
         ("U^8, n = 30", lambda g, s: g.random(s)**8, 1 / 9, 30)]
for titulo, f, mu, n in casos:
    print(f"{titulo}  (δ = 0.05)")
    evaluar(f, mu, n)

The numbers tell the same story as the coverage figure, now with your own code. With Bernoulli(0.05) and n=30n = 30, CLT and plug-in Bernstein fail around 21%, Chernoff–KL 0.3%, and Hoeffding and empirical Bernstein never, with empirical Bernstein almost twice as wide as Hoeffding. With Bernoulli(0.01) and n=1000n = 1000 width ordering reverses: empirical Bernstein (0.0290.029) is already much narrower than Hoeffding (0.0530.053), and Chernoff–KL (0.0170.017) remains the best guaranteed one. The CLT still fails 7.5%.

Finally, the Gaussian maximum versus its bound, and selection bias in the 100-variant example, simulated with binomials.

[ ]The maximal inequality y el sesgo de quedarse con el mejorBrowser
import numpy as np
from scipy import integrate
from scipy.stats import norm

def emax_exacto(n):
    """E[max de n N(0,1) independientes] = ∫ x n φ(x) Φ(x)^(n-1) dx."""
    f = lambda x: x * n * norm.pdf(x) * norm.cdf(x)**(n - 1)
    return integrate.quad(f, -10, 12, limit=200)[0]

rng = np.random.default_rng(1)
print("     n   E[max] simulado   exacto   cota √(2 log n)")
for n in [10, 100, 1000, 10000]:
    sim = rng.standard_normal((400, n)).max(axis=1).mean()
    print(f"{n:6d}   {sim:8.3f}       {emax_exacto(n):6.3f}      {np.sqrt(2*np.log(n)):6.3f}")

# 100 variantes con la MISMA exactitud real, cada una evaluada con 1000 ejemplos
k, n, p = 100, 1000, 0.80
mejores = rng.binomial(n, p, size=(2000, k)).max(axis=1) / n
sigma = np.sqrt(p * (1 - p) / n)
print(f"\nmejor de {k} variantes iguales: exactitud aparente media {mejores.mean():.4f} (real {p})")
print(f"ganancia espuria {100*(mejores.mean() - p):.2f} puntos;  σ·E[max de 100 N(0,1)] = "
      f"{100*sigma*emax_exacto(k):.2f};  cota σ√(2 log k) = {100*sigma*np.sqrt(2*np.log(k)):.2f}")

Simulated spurious gain (about 3.1 points) matches the Gaussian prediction (3.2) and stays below the maximal bound (3.8), which assumes nothing about dependence between variants.

Using libraries

There is no standard SciPy function for Hoeffding or empirical Bernstein: they take three lines and are usually written directly, as above. There is an exact binomial-proportion interval (Clopper–Pearson), a reference for comparing Chernoff–KL in the Bernoulli case, and Wilson’s interval, asymptotic but much better than the CLT’s Wald interval. The second part compares the exact tail of χn2\chi^2_n with the sub-exponential bound.

[ ]Clopper–Pearson, Wilson, and the chi-square tail (SciPy)Browser
import numpy as np
from scipy import stats

k, n, delta = 3, 100, 0.05
x = np.r_[np.ones(k), np.zeros(n - k)][None, :]
cp = stats.binomtest(k, n).proportion_ci(confidence_level=1 - delta, method="exact")
wi = stats.binomtest(k, n).proportion_ci(confidence_level=1 - delta, method="wilson")
lo_kl, hi_kl = ic_kl(x, delta)
lo_h, hi_h = ic_hoeffding(x, delta)
print(f"{k} errores en {n}:")
print(f"  Clopper-Pearson (exacto)  [{cp.low:.4f}, {cp.high:.4f}]")
print(f"  Wilson (asintótico)       [{wi.low:.4f}, {wi.high:.4f}]")
print(f"  Chernoff-KL               [{lo_kl[0]:.4f}, {hi_kl[0]:.4f}]")
print(f"  Hoeffding                 [{max(lo_h[0], 0):.4f}, {hi_h[0]:.4f}]")

print("\nχ²_n: P(|χ²/n - 1| ≥ ε) exacta frente a la cota subexponencial 2 exp(-n ε²/8)")
for m, eps in [(10, 0.5), (100, 0.3), (1000, 0.1), (1000, 0.2)]:
    exacta = stats.chi2.sf(m * (1 + eps), m) + stats.chi2.cdf(m * (1 - eps), m)
    print(f"  n = {m:5d}, ε = {eps}:  exacta {exacta:.3e}   cota {2*np.exp(-m*eps**2/8):.3e}")

With 3 errors in 100, Chernoff–KL gives [0.004,0.100][0.004, 0.100], close to exact Clopper–Pearson [0.006,0.085][0.006, 0.085], while Hoeffding gives [0,0.166][0, 0.166]. The chi-square bound has the correct exponent in nε2n\eps^2 but a poor constant (1/81/8 versus 1/41/4 given by the CLT for χn2\chi^2_n, with variance 2n2n): for serious sizing, use the exact tail when available and bounds when not.

Common mistakes

Exercises

NumericHoeffding sample size
You want to estimate the mean of a variable in [0,1][0, 1] with error at most 0.010.01 and 99% two-sided confidence. How many independent samples does Hoeffding guarantee suffice (smallest integer)?
QuizWhich are sub-Gaussian?
Which of these variables are sub-Gaussian?

More than one answer may be correct.

QuizVariance and proxy of a rare Bernoulli
Let X∼Bern⁡(0.01)X \sim \Bern(0.01) and Y=X−0.01Y = X - 0.01. Which statements are true?

More than one answer may be correct.

NumericThe Gaussian ψ₂ norm
Calculate ∥Z∥ψ2\norm{Z}_{\psi_2} for Z∼N(0,1)Z \sim \Normal(0, 1).
NumericThe cost of choosing the best
You evaluate 50 classifier variants, all with true accuracy 0.700.70, on 2000 examples each. Using a Gaussian approximation for each measured accuracy and the maximal inequality, what is the upper bound, in percentage points, on expected spurious gain of the best variant?
QuizQuestions from the same document
A benchmark has 2000 questions generated from 200 documents (10 per document), and model errors within a document are highly correlated. Which interval for mean accuracy is valid?
ProofHoeffding’s lemma by convexity
Prove: If X∈[a,b]X \in [a, b] almost surely and EX=0\E X = 0, then EeλX≤eλ2(b−a)2/8\E e^{\lambda X} \le e^{\lambda^2(b-a)^2/8} for every λ∈R\lambda \in \R.
0
Assume a<0<ba < 0 < b (if a=0a = 0 or b=0b = 0, then X=0X = 0 almost surely and nothing remains to prove). Fix λ\lambda.

Step 1 of 4. How do you bound eλxe^{\lambda x} for x∈[a,b]x \in [a, b]?

ProofExpected maximum of n sub-Gaussians
Prove: If X1,…,XnX_1, \dots, X_n are centered and each is SG⁡(σ2)\operatorname{SG}(\sigma^2), without assuming independence, then Emax⁡iXi≤σ2log⁡n\E\max_i X_i \le \sigma\sqrt{2\log n}.
0
Fix λ>0\lambda > 0, to be chosen at the end, and write M=max⁡iXiM = \max_i X_i.

Step 1 of 4. How do you begin?

CodeBernstein: bound and sample size
Implement two functions for the mean Xˉn\bar X_n of nn independent variables with variance σ2\sigma^2 and ∣Xi−μ∣≤b|X_i - \mu| \le b. bernstein_cola(eps, n, sigma2, b) returns Bernstein’s one-sided bound exp⁡(−nε2/(2σ2+2bε/3))\exp\big(-n\varepsilon^2/(2\sigma^2 + 2b\varepsilon/3)\big) for P(Xˉn−μ≥ε)\Pr(\bar X_n - \mu \ge \varepsilon). n_min_bernstein(eps, delta, sigma2, b) returns the smallest integer n≥1n \ge 1 for which the two-sided bound, twice the preceding one, is at most δ\delta. Use only math or NumPy.
import math

def bernstein_cola(eps, n, sigma2, b):
  """Cota de Bernstein para P(media - mu >= eps)."""
  # tu código
  return 1.0

def n_min_bernstein(eps, delta, sigma2, b):
  """Menor n con 2 * bernstein_cola(eps, n, sigma2, b) <= delta."""
  # tu código
  return 1
Shift+Enter to run

Summary

Key idea
A variable is sub-Gaussian when its MGF is bounded by a Gaussian’s; it then inherits tails e−t2/(2σ2)e^{-t^2/(2\sigma^2)}, and because MGFs multiply, means of nn independent variables concentrate at scale σ/n\sigma/\sqrt{n} with only logarithmic confidence cost. Hoeffding is the bounded case (proxy (b−a)2/4(b-a)^2/4), Bernstein replaces range with variance at the cost of term 1/n1/n, and the maximum of nn sub-Gaussians costs σ2log⁡n\sigma\sqrt{2\log n}.
  • MGF, tail, moment (∥X∥p≲p\norm{X}_p \lesssim \sqrt{p}), and ψ2\psi_2 norm characterizations are equivalent up to universal constants. The MGF handles sums; the others are checked.
  • Variance proxy bounds variance but can be much larger: centered Bernoulli(0.01) has variance 0.00990.0099 and optimal proxy 0.1070.107.
  • Hoeffding’s lemma: [a,b]⇒SG⁡((b−a)2/4)[a, b] \Rightarrow \operatorname{SG}((b-a)^2/4). Hoeffding’s inequality: ∣Xˉn−μ∣≤(b−a)log⁡(2/δ)/(2n)\abs{\bar X_n - \mu} \le (b-a)\sqrt{\log(2/\delta)/(2n)}. It requires independence and does not see variance.
  • Sub-exponentials (squares and products of sub-Gaussians, exponentials, χ2\chi^2) have quadratic MGFs only near 0; Bernstein gives Gaussian behavior for small deviations and exponential for large ones.
  • Bounded Bernstein: ∣Xˉn−μ∣≤2σ2log⁡(2/δ)/n+blog⁡(2/δ)/(3n)\abs{\bar X_n - \mu} \le \sqrt{2\sigma^2\log(2/\delta)/n} + b\log(2/\delta)/(3n). With small variance the rate changes from 1/n1/\sqrt{n} to 1/n1/n.
  • Unknown variance is not simply plugged in: empirical Bernstein (Maurer and Pontil) replaces it with VnV_n, paying 7log⁡(2/δ)/(3(n−1))7\log(2/\delta)/(3(n-1)). For proportions, Chernoff–KL is narrower and also guaranteed.
  • Emax⁡i≤nXi≤σ2log⁡n\E\max_{i \le n}X_i \le \sigma\sqrt{2\log n} without independence: the bias from choosing the best of nn and the basis of finite-class uniform bounds.