Foundations to FrontierPart IX: The graduate coreBezhig

G04: Probability, information, and credible measurement

6 exercises, each with a complete solution. 1 figure. 1 code listing.

On this page
  1. Prerequisites and observable goals
  2. The central question: what population does this number describe?
  3. Conditional probability as a changed denominator
  4. Expectation, variance, and a concentration calculation
  5. A proportion interval that behaves near the endpoints
  6. Paired comparisons and bootstrap logic
  7. Information measures and their limits
  8. Independent practice
  9. Smallest useful hints
  10. Complete solutions: G04
  11. Readiness and next depth

Prerequisites and observable goals#

Before

foundation A03–A04, logarithms, counting, and basic summation.

After

Condition on the correct event, distinguish uncertainty sources, compute a proportion interval, and design a paired experiment whose sampling unit matches its claim.

The central question: what population does this number describe?#

A mean without a population and sampling procedure is incomplete. A model accuracy, server error rate, or benchmark speedup is computed from observations, but the desired claim usually concerns different future observations. Identify the unit first: requests, users, independent server restarts, entire workload traces, or machines. A thousand correlated requests from one session are not automatically a thousand independent trials.

Separate three sources of uncertainty. Sampling uncertainty comes from observing a subset of a target population. Measurement error comes from clocks, instrumentation, rounding, and collection mistakes. Modeling error comes from assumptions such as independent arrivals or a workload that fails to represent deployment. More repeated runs can reduce some sampling uncertainty without repairing an unrealistic workload.

Conditional probability as a changed denominator#

For events A,BA,B with P(B)>0P(B)>0, P(A∣B)=P(A∩B)/P(B)P(A\mid B)=P(A\cap B)/P(B). The condition restricts the sample space. Multiplication gives P(A∩B)=P(B∣A)P(A)P(A\cap B)=P(B\mid A)P(A), and partitioning by AA and its complement yields

P(A∣B)=P(B∣A)P(A)P(B∣A)P(A)+P(B∣Ac)P(Ac).P(A\mid B)=\frac{P(B\mid A)P(A)}{P(B\mid A)P(A)+P(B\mid A^c)P(A^c)}.

A detector’s sensitivity cannot be read as the reliability of a flag without prevalence. For a rare fault with prevalence .02, sensitivity .8, and false-positive probability .1, the joint true-positive probability is .016.016 and false-positive probability .098.098. Among flags, the true fraction is .016/.114=8/57≈.1404.016/.114=8/57\approx.1404. Replacing a probability tree with 10,000 cases often makes the denominator visible.

Independence means P(A∩B)=P(A)P(B)P(A\cap B)=P(A)P(B). Conditional independence given CC is a separate statement. Two measurements can be correlated because they share a hidden workload class, even if independent after conditioning on that class. Splitting data by row while duplicating that shared class across training and test can exploit a dependency rather than demonstrate generalization.

Expectation, variance, and a concentration calculation#

For independent identically distributed Bernoulli variables XiX_i with success probability pp, the sample proportion p^=n−1∑iXi\hat p=n^{-1}\sum_iX_i has expectation pp and variance p(1−p)/np(1-p)/n. Linearity of expectation does not require independence; removing covariance terms from the variance does. For dependent variables,

Var⁡ ⁣(1n∑iXi)=1n2(∑iVar⁡(Xi)+2∑i<jCov⁡(Xi,Xj)).\Var\!\left(\frac1n\sum_iX_i\right)=\frac1{n^2} \left(\sum_i\Var(X_i)+2\sum_{i<j}\operatorname{Cov}(X_i,X_j)\right).

Positive dependence can make the naive independent standard error too small.

For independent variables bounded in [0,1][0,1], Hoeffding’s inequality gives

P(∣μ^−μ∣≥ϵ)≤2e−2nϵ2.P(|\hat\mu-\mu|\ge\epsilon)\le2e^{-2n\epsilon^2}.

To make the upper bound at most δ\delta, solve 2e−2nϵ2≤δ2e^{-2n\epsilon^2}\le\delta: take logarithms, rearrange, and obtain

n≥ln⁡(2/δ)2ϵ2.n\ge\frac{\ln(2/\delta)}{2\epsilon^2}.

For ϵ=.1,δ=.05\epsilon=.1,\delta=.05, this requires n≥184.44…n\ge184.44\ldots, hence 185 observations. This is a distribution-free bound under independence and boundedness, not a claim that 185 arbitrary correlated records certify every prediction. The inequality is stated here; the calculation using it is derived. A deeper probability course should prove the exponential-moment bound underlying it.

A proportion interval that behaves near the endpoints#

The simple symmetric approximation p^±1.96p^(1−p^)/n\hat p\pm1.96\sqrt{\hat p(1-\hat p)/n} degenerates to zero width when all trials agree. The Wilson score interval instead inverts a standardized discrepancy using the hypothesized pp in its variance. With critical value zz, its center and half-width are

c=p^+z2/(2n)1+z2/n,h=zp^(1−p^)/n+z2/(4n2)1+z2/n.c=\frac{\hat p+z^2/(2n)}{1+z^2/n},\qquad h=\frac{z\sqrt{\hat p(1-\hat p)/n+z^2/(4n^2)}}{1+z^2/n}.

For 18 successes in 20 trials and z=1.96z=1.96, the interval is approximately [.6990,.9721][.6990,.9721]. The confidence level is a property of a repeated-sampling procedure under its model; it is not a frequentist probability that a fixed unknown parameter lies in the already computed interval. For clustered records, a binomial interval may not match the sampling design. Report the count and denominator with the interval, not only a rounded percentage.

Paired comparisons and bootstrap logic#

Suppose the same workload trace is run on old and new implementations. Define di=tnew,i−told,id_i=t_{{\rm new},i}-t_{{\rm old},i}. Negative values favor the new version. Pairing removes some variation caused by easy versus difficult traces. Resampling pairs means resampling the differences did_i, not independently resampling the two timing columns. The lab computes bootstrap means from samples of those differences and takes percentile endpoints.

This percentile bootstrap is an exploratory interval, not a universal guarantee. With very few pairs, severe dependence, time trends, or biased workload selection, it can mislead. A paired tt method or an appropriate hierarchical/block design may be preferable under its own assumptions. Establish the experimental unit before selecting a resampling scheme.

Worked example: old times (10,20,30)(10,20,30) and new times (8,18,28)(8,18,28) give differences (−2,−2,−2)(-2,-2,-2). Every resample has mean −2-2, so the bootstrap interval collapses to [−2,−2][-2,-2]. That does not establish that every future workload saves exactly two units. It shows that these three paired observations contain no observed variation in their differences; the uncertainty model has no information about unsampled behavior.

Information measures and their limits#

For a discrete probability vector pp, entropy in bits is H(p)=−∑ipilog⁡2piH(p)=-\sum_i p_i\log_2p_i, with the continuous extension 0log⁡0=00\log0=0. A certain event has entropy zero. Two equally likely outcomes have one bit; probabilities (1/2,1/4,1/4)(1/2,1/4,1/4) give 1/2+1/2+1/2=1.51/2+1/2+1/2=1.5 bits. This quantifies distributional uncertainty, not semantic importance or human intelligence.

The entropy of a coin. For two outcomes with probabilities pp and 1−p1-p, entropy is zero when the outcome is certain and largest, one bit, when the two are equally likely. A coin with p=0.1p=0.1 carries 0.4690.469 bits per toss: most tosses tell you little.

Cross-entropy under a proposed distribution qq is H(p,q)=−∑ipilog⁡qiH(p,q)=-\sum_i p_i\log q_i. With matching logarithm bases, H(p,q)=H(p)+DKL(p∥q)H(p,q)=H(p)+D_{\rm KL}(p\Vert q), where DKL=∑ipilog⁡(pi/qi)≥0D_{\rm KL}=\sum_i p_i\log(p_i/q_i)\ge0 when properly defined. If pi>0p_i>0 and qi=0q_i=0, the term is infinite. KL is not a symmetric distance. In binary classification, empirical cross-entropy rewards assigning probability to the observed class; it does not by itself prove calibration under distribution shift.

Independent practice#

F foundation C standard course work T transfer S optional stretch L runnable lab or project. Attempt the complete set before opening its solutions.

G04.01FSolution

For the fault detector with prevalence .02, sensitivity .8, and false-positive probability .1, compute P(fault∣flag)P(\text{fault}\mid\text{flag}) using 10,000 cases. Explain why .8 is not the answer.

G04.02CSolution

Using the stated Hoeffding bound, find an integer sample count sufficient for absolute error .05 with failure bound .05. State the assumptions and explain why repeated readings of one unchanged cached result do not satisfy them as independent trials.

G04.03CSolution

For zero failures in 20 independent trials, find the Wilson upper bound using z=1.96z=1.96. Interpret it without saying the true failure probability is certainly zero.

G04.04TSolution

Old timings are (10,100,20,200)(10,100,20,200) and new timings (9,99,19,199)(9,99,19,199). Compare the paired differences with the spread of each timing column. Explain what is lost by unpaired resampling and what remains unestablished even with identical differences.

G04.05CSolution

Compute entropy in bits for (.5,.25,.25)(.5,.25,.25) and cross-entropy against the uniform distribution on three outcomes. Find their difference and explain its meaning.

G04.06LSolution

Implement wilson, entropy, quantile, and paired_bootstrap in starters/evidence.py. Validate counts, finite inputs, a probability sum of one, pairing, and a local random seed. Reproduce the known examples, then explain why a deterministic seeded result is not proof of statistical validity.

Smallest useful hints#

For .02, round upward only after solving the logarithmic inequality. For .03, set p^=0\hat p=0 in both center and half-width. For .04, inspect the distribution of differences, not merely the two marginal distributions.

Complete solutions: G04#

Compare the first step where your work differs. A corrected answer is not yet an independent success.

G04.01Show solution

Flags define the denominator

Expect 200 faults and 9,800 nonfaults. Flag 160 faults and 980 nonfaults, totaling 1,140 flags. The fraction is 160/1140=8/57≈.14035160/1140=8/57\approx.14035. Sensitivity .8 conditions on being a fault; the requested probability conditions on being flagged. This arithmetic assumes the supplied rates describe the target population and do not vary in an unmodeled way.

Back to G04.01
G04.02Show solution

A sufficient bound, not a magic sample size

Compute ln⁡40/[2(.05)2]≈737.7759\ln40/[2(.05)^2]\approx737.7759, so 738 independent bounded observations suffice for the stated bound. It is conservative and not necessarily the minimum for a specific distribution. Repeatedly reading an unchanged cache value is strongly dependent and may represent no new random outcome at all. Increasing the row count does not make the independence premise true.

Back to G04.02
G04.03Show solution

No observed failures does not mean no possible failures

At p^=0\hat p=0, c=h=z2/[2(n+z2)]c=h=z^2/[2(n+z^2)]. The upper endpoint is z2/(n+z2)=3.8416/23.8416≈.16113z^2/(n+z^2)=3.8416/23.8416\approx.16113; the lower is zero. Under the binomial model and score-interval procedure, the finite sample remains compatible with nonzero failure probabilities. This two-sided score interval is not the same as a one-sided exact binomial bound; state which procedure was used.

Back to G04.03
G04.04Show solution

Pairing preserves the comparison unit

The four differences are all −1-1, while the marginal times range over nearly two hundred units. Unpaired resampling can compare the new timing of a difficult trace with the old timing of an easy one, adding workload variation irrelevant to the within-trace comparison. A collapsed paired interval still says little about unseen traces, thermal drift, or different hardware. Pairing is a design feature, not a substitute for representative sampling.

Back to G04.04
G04.05Show solution

The cost of a mismatched distribution

Entropy is −(.5)(−1)−2(.25)(−2)=1.5-(.5)(-1)-2(.25)(-2)=1.5 bits. Uniform qi=1/3q_i=1/3 gives cross-entropy −∑ipilog⁡2(1/3)=log⁡23≈1.58496-\sum_i p_i\log_2(1/3)=\log_23\approx1.58496 bits. The difference is about .08496 bits, equal to DKL(p∥q)D_{\rm KL}(p\Vert q). It is excess expected log loss for using this qq rather than pp, not a symmetric geometric distance or a measure of the importance of an outcome.

Back to G04.05
G04.06Show solution

Complete reference and reproducible randomness

The quantile implementation interpolates between sorted sample values at index q(n−1)q(n-1); other quantile conventions can differ in small samples. The bootstrap uses a local pseudorandom generator so another module’s random draws do not change this sequence. Validate the statistical design separately from that engineering reproducibility.

graduate_code/solutions/evidence.pyPython
"""G04: explicit statistical procedures; validity still needs a sampling model."""
import math
import random


def wilson(successes, trials, z=1.96):
    if type(trials) is not int or type(successes) is not int or not 0 <= successes <= trials or trials < 1:
        raise ValueError("integer counts with 0 <= successes <= trials required")
    if not math.isfinite(z) or z <= 0:
        raise ValueError("finite positive critical value required")
    p = successes / trials
    denominator = 1 + z*z/trials
    center = (p + z*z/(2*trials)) / denominator
    half = z*math.sqrt(p*(1-p)/trials + z*z/(4*trials*trials)) / denominator
    return max(0., center-half), min(1., center+half)


def entropy(probabilities):
    p = list(probabilities)
    if not p or any(not math.isfinite(x) or x < 0 or x > 1 for x in p):
        raise ValueError("nonempty finite probability vector required")
    if not math.isclose(math.fsum(p), 1., rel_tol=0., abs_tol=1e-12):
        raise ValueError("probabilities must sum to one")
    return -math.fsum(x*math.log2(x) for x in p if x > 0)


def quantile(values, probability):
    values = sorted(values)
    if not values or not math.isfinite(probability) or not 0 <= probability <= 1:
        raise ValueError("nonempty data and probability in [0,1] required")
    if any(not math.isfinite(x) for x in values):
        raise ValueError("finite observations required")
    position = (len(values)-1)*probability
    lo = math.floor(position)
    hi = min(lo+1, len(values)-1)
    fraction = position-lo
    return (1-fraction)*values[lo]+fraction*values[hi]


def paired_bootstrap(old, new, repeats=2000, seed=21, confidence=.95):
    if len(old) != len(new) or not 2 <= len(old) <= 10000:
        raise ValueError("2..10000 matched pairs required")
    if type(repeats) is not int or not 100 <= repeats <= 10000:
        raise ValueError("100..10000 resamples required")
    if not math.isfinite(confidence) or not 0 < confidence < 1:
        raise ValueError("confidence must lie in (0,1)")
    if any(not math.isfinite(v) for v in [*old, *new]):
        raise ValueError("finite measurements required")
    differences = [b-a for a,b in zip(old,new)]
    if any(not math.isfinite(d) for d in differences):
        raise ValueError("difference overflow")
    rng = random.Random(seed)
    n = len(differences)
    means = [math.fsum(rng.choice(differences) for _ in range(n))/n
             for _ in range(repeats)]
    tail = (1-confidence)/2
    return {"mean_difference": math.fsum(differences)/n,
            "interval": (quantile(means,tail),quantile(means,1-tail)),
            "seed":seed,"pairs":n,"resamples":repeats}


if __name__ == "__main__":
    print("Wilson:",wilson(18,20))
    print("Entropy:",entropy([.5,.25,.25]))
    print(paired_bootstrap([10,20,30],[8,18,28]))
Back to G04.06

Readiness and next depth#

You should be able to name the sampling unit and write the conditional denominator before calculating. Review foundation A03–A04 when those choices are unclear. Continue with concentration proofs, stochastic processes, hierarchical models, and experimental design; do not claim the elementary bootstrap lab covers those areas. Connect the interval exercise to G16’s research review and G15’s group-aware splitting.