LeetLLM
My PlanLearnGlossaryTracksPracticeBlog
LeetLLM

Your go-to resource for mastering AI & LLM systems.

Product

  • Learn
  • Glossary
  • Tracks
  • Practice
  • Blog
  • RSS

Legal

  • Terms of Service
  • Privacy Policy

© 2026 LeetLLM. All rights reserved.

All Topics
Your Progress
0%

0 of 196 articles completed

🛠️Computing Foundations0/9
Git, Shell, Linux for AIDocker for Reproducible AIPython for AI EngineeringNumPy and Tensor ShapesCUDA for ML TrainingMPS & Metal for ML on MacData Structures for AISQL and Data ModelingAlgorithms for ML Engineers
📊Math & Statistics0/9
Gradients and BackpropVectors, Matrices & TensorsLinear Algebra for MLAdam, Momentum, SchedulersProbability for Machine LearningBayesian Inference from EvidenceStatistics and UncertaintyDistributions and SamplingHypothesis Tests, Intervals, and pass@k
📚Preparation & Prerequisites0/13
Neural Networks from ScratchCNNs from ScratchTraining & BackpropagationSoftmax, Cross-Entropy & OptimizationRNNs, LSTMs, GRUs, and Sequence ModelingAutoencoders and VAEsThe Transformer Architecture End-to-EndLanguage Modeling & Next TokensFrom GPT to Modern LLMsPrompt Engineering FundamentalsCalling LLM APIs in ProductionFirst AI App End-to-EndThe LLM Lifecycle
🧮ML Algorithms & Evaluation0/15
Linear Regression from ScratchLogistic Regression and MetricsDecision Trees, Forests, and BoostingReinforcement Learning BasicsValidation and LeakageStatistical Learning and GeneralizationConformal Prediction and UncertaintyClustering and PCAProbabilistic Generative ModelsCore Retrieval AlgorithmsDecoding AlgorithmsExperiment Design and A/B TestingCausal Inference and CounterfactualsPyTorch Training LoopsDataset Pipelines and Data Quality
📦Production ML Systems0/6
Feature Engineering for Production MLBatch and Streaming Feature PipelinesGradient Boosted Trees in ProductionRanking and Recommendation SystemsForecasting and Anomaly DetectionMonitoring Predictive Models
🧪Core LLM Foundations0/8
The Bitter Lesson & ComputeBPE, WordPiece, and SentencePieceStatic to Contextual EmbeddingsPerplexity & Model EvaluationFile Ingestion for AIChunking StrategiesLLM Benchmarks & LimitationsInstruction Tuning & Chat Templates
🧰Applied LLM Engineering0/25
Dimensionality Reduction for EmbeddingsCoT, ToT & Self-Consistency PromptingFunction Calling & Tool UseMCP & Tool Protocol StandardsContext EngineeringPrompt Injection DefenseResponsible AI GovernancePrivacy-Preserving Machine LearningData Labeling and Human FeedbackEvaluating AI AgentsProduction RAG PipelinesHybrid Search: Dense + SparseReranking and Cross-Encoders for RAGRAG Evaluation for Reliable AnswersLLM-as-a-Judge EvaluationBias & Fairness in LLMsHallucination Detection & MitigationLLM Observability & MonitoringExperiment Tracking with MLflow and W&BPrompt Optimization with DSPyModel Versioning & DeploymentSemantic Caching & Cost OptimizationLLM Cost Engineering & Token EconomicsModel Gateways, Routing, and FallbacksDesign an Automated Support Agent
🎓Portfolio Capstones0/9
Capstone: Delivery ETA PredictionCapstone: Product RankingCapstone: Demand ForecastingCapstone: Image Damage ClassifierCapstone: Production ML PipelineCapstone: Document QACapstone: Eval DashboardCapstone: Fine-Tuned ClassifierCapstone: Reproducible ML Study
🧠Transformer Deep Dives0/8
Sentence Embeddings & Contrastive LossEmbedding Similarity & QuantizationScaled Dot-Product AttentionVision Transformers and Image EncodersPositional Encoding: RoPE & ALiBiLayer Normalization: Pre-LN vs Post-LNMechanistic InterpretabilityDecoding Strategies: Greedy to Nucleus
🧬Advanced Training & Adaptation0/17
Scaling Laws & Compute-Optimal TrainingPre-training Data at ScaleBuild GPT from Scratch LabJAX for PyTorch ResearchersContinued Pretraining for Domain ShiftSynthetic Data PipelinesSupervised Fine-Tuning PipelineMixed Precision TrainingDistributed Training: FSDP & ZeROLoRA & Parameter-Efficient TuningTraining Run OperationsReward Modeling from Preference DataRLHF & DPO AlignmentConstitutional AI & Red TeamingRLVR & Verifiable RewardsKnowledge Distillation for LLMsModel Merging and Weight Interpolation
🤖Advanced Agents & Retrieval0/16
Vector DB Internals: HNSW & IVFAdvanced RAG: HyDE & Self-RAGGraphRAG & Knowledge GraphsRAG Security & Access ControlStructured Output GenerationReAct & Plan-and-ExecuteGuardrails & Safety FiltersCode Generation & SandboxingComputer-Use / GUI / Browser AgentsHuman-in-the-Loop Agent ArchitectureAI Coding Workflow with AgentsAgent Memory & PersistenceAgent Failure & RecoveryRecursive Language Models (RLM)Multi-Agent OrchestrationCapstone: Production Agent
⚡Inference & Production Scale0/31
Inference: TTFT, TPS & KV CacheMulti-Query & Grouped-Query AttentionKV Cache & PagedAttentionPrefix Caching and Prompt CachingFlashAttention & Memory EfficiencyContinuous Batching & SchedulingScaling LLM InferenceModel Parallelism for LLM InferenceAccelerator Architecture Field GuideCorrect GPU Profiling and BenchmarkingGPU Kernel Performance Engineering LabGPU Parallel Primitives LabGPU Compilers and Kernel LanguagesGEMM From Naive CUDA to Tensor CoresLow-Precision GPU ProgrammingGPU Runtime Execution LabAI-Generated Kernel EngineeringModel Quantization: GPTQ, AWQ & GGUFLocal LLM DeploymentSLM Specialization & Edge DeploymentSpeculative DecodingLong Context Window ManagementMixture of Experts ArchitectureMamba & State Space ModelsReasoning & Test-Time ComputeAdvanced MLOps & DevOps for AIGPU Serving & AutoscalingGPU Failure OperationsDistributed Inference Data PlaneServing Benchmark EngineeringA/B Testing for LLMs
🏗️System Design Capstones0/9
Content Moderation SystemCode Completion SystemMulti-Tenant LLM PlatformLLM-Powered Search EngineVision-Language Models & CLIPMultimodal LLM ArchitectureDiffusion Models: Images & TextReal-Time Voice AI AgentReasoning Agent System Design
🎤AI Lab Interviewing0/4
AI Lab Coding Interview: Python SystemsAI Lab System Design InterviewAI Lab Behavioral InterviewAI Lab Technical Presentation
🔬Project Deep Dives0/17
Deep Dive - vLLMDeep Dive - SkyRLDeep Dive - FlashAttentionDeep Dive - FlashInferDeep Dive - DeepGEMMDeep Dive - NCCLDeep Dive - MegatronDeep Dive - DeepSpeedDeep Dive - RayDeep Dive - MLflowDeep Dive - PyTorchDeep Dive - TransformersDeep Dive - SGLangDeep Dive - slimeDeep Dive - DeepEPDeep Dive - TinkerDeep Dive - Light-PEFT
Back to Topics
LearnMath & StatisticsBayesian Inference from Evidence
📊EasyEvaluation & Benchmarks

Bayesian Inference from Evidence

Update a coding agent's unknown success rate with beta-binomial evidence, compare priors, measure uncertainty, and expose sampling failures.

13 min read
Learning path
Step 15 of 196 in the full curriculum
Probability for Machine LearningStatistics and Uncertainty

Personalize this lesson

Adapt explanations and teaching visuals to your background and preferred voice.

A coding agent passes eight of ten held-out tasks. Is its success rate above 70%? The observed rate is 80%, but ten tasks leave room for luck. We need to distinguish a promising estimate from strong evidence that the agent clears the threshold.

Probability for Machine Learning introduced base rates and conditioning. Bayesian inference applies the same reasoning to an unknown model parameter: state which values were plausible before the evaluation, then update those beliefs using the results. The answer is a distribution of plausible success rates, not just one adjusted score.[1]Reference 1Machine Learning: A Probabilistic Perspective.https://probml.github.io/pml-book/book0.html

We'll use those same eight passes and two failures throughout. Start with a mild preference for middle success rates, then change that preference to see how much the conclusion depends on it.

Formulating the unknown success parameter

Let ppp mean the probability that this agent passes a randomly drawn task from the intended deployment population. Pin the agent's model, prompt, tools, retry budget, and pass criterion. One observation is one task evaluated under that fixed policy.

Our simple model treats the outcomes as independent conditional on ppp, with the same success probability for each draw. That means: if we knew ppp, knowing one result wouldn't change the probability of another. Tasks can differ in difficulty, but their sampling process must stay the same. Ten handpicked easy tasks won't support a claim about a different production mix.

QuantityQuestion it answersWorked value
PriorWhich rates were plausible before this eval?A broad distribution centered at 0.5
ObservationsWhat actually happened?8 passes, 2 failures
LikelihoodHow probable are the observed results at a candidate rate?Compare eight passes out of ten at p=0.5p=0.5p=0.5 and p=0.8p=0.8p=0.8
PosteriorWhich rates are plausible after the update?More weight near high success rates, with uncertainty remaining

The direction of conditioning matters. A likelihood asks about the data given a proposed rate. A posterior asks about the rate given the data. Bayes' rule connects them; they aren't interchangeable.

Binomial likelihood scores candidate success rates

At a candidate rate of 0.8, each pass contributes a factor of 0.8 and each failure contributes 0.2. One particular sequence of eight passes and two failures has probability 0.88×0.220.8^8 \times 0.2^20.88×0.22. There are 45 possible positions for the two failures, so the probability of exactly eight passes, regardless of order, is 45 times that value.

Python's comb(10, 8) counts the 45 unique arrangements of eight passes across ten trials. Evaluating this binomial formula across candidate rates reveals how sharply the observed run separates hypotheses:

compare-candidate-success-rates.py
1from math import comb 2 3for rate in (0.2, 0.5, 0.8): 4 likelihood = comb(10, 8) * rate**8 * (1 - rate)**2 5 print(f"rate={rate:.1f}: P(exactly 8 passes)={likelihood:.6f}")
Output
1rate=0.2: P(exactly 8 passes)=0.000074 2rate=0.5: P(exactly 8 passes)=0.043945 3rate=0.8: P(exactly 8 passes)=0.301990

The eight-pass result is about 6.9 times as likely at rate 0.8 as at rate 0.5. That favors 0.8 relative to 0.5, but it doesn't mean there's a 30.2% posterior probability that the rate is 0.8. We haven't combined the evidence with a prior.

For a general candidate rate, the likelihood is 45p8(1−p)245p^8(1-p)^245p8(1−p)2. The factor 45 is the same for every candidate, so it cancels when we normalize the posterior. We can therefore work with a likelihood proportional to p8(1−p)2p^8(1-p)^2p8(1−p)2. The symbol ∝\propto∝ means "equal up to a constant factor."

Beta distributions quantify prior beliefs

A beta distribution describes uncertainty about a probability between 0 and 1. Its two positive shape parameters, α\alphaα and β\betaβ, control where that uncertainty sits. We'll choose Beta(2, 2): it favors middle rates over near-zero or near-one rates, without ruling out a broad range.

This is an explicit modeling choice, not a claim that we observed two historical passes and two failures. A uniform Beta(1, 1) prior would give equal density to all rates. Increasing both parameters equally concentrates the distribution around 0.5. These alternatives make it possible to test how much the prior matters.

For a continuous rate, probability belongs to a range of values, represented by area under a density curve. The height at one point isn't a probability and can exceed 1. Beta(2, 2) has density 6p(1−p)6p(1-p)6p(1−p); the constant 6 makes the total area from 0 to 1 equal to 1.[2]Reference 2scipy.stats.betahttps://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.beta.html

Bayes' rule multiplies that prior shape by the likelihood, then rescales the result so its total area is 1:

posterior density∝prior density×likelihood\text{posterior density} \propto \text{prior density} \times \text{likelihood}posterior density∝prior density×likelihood

For our run, multiplying p(1−p)p(1-p)p(1−p) by p8(1−p)2p^8(1-p)^2p8(1−p)2 gives p9(1−p)3p^9(1-p)^3p9(1−p)3. A beta density has the shape pα−1(1−p)β−1p^{\alpha-1}(1-p)^{\beta-1}pα−1(1−p)β−1, so the new exponents identify Beta(10, 4). The prior's exponents and the data's exponents add; the observations don't replace the prior.[3]Reference 3Gittins Index for Bayesian Bandits: Beta-Binomial Conjugacyhttps://www.stat.berkeley.edu/~bartlett/courses/2014fall-cs294stat260/lectures/gittins-notes.pdf

The Bayesian update cycle: Prior Beta(2,2) combines with binomial evidence (8 passes, 2 failures) to produce Beta(10,4). Density curves show the prior centered at 0.50, the normalized likelihood peaked at 0.80, and the posterior resolving to a compromise curve centered at mean 0.714.
The Bayesian update cycle in action. The Beta(2, 2) prior (blue) pulls toward 0.50, the binomial likelihood (amber) peaks at the observed 0.80 rate, and the resulting Beta(10, 4) posterior (purple) balances both. Each density curve has total area 1.

Beta-binomial conjugacy produces an exact posterior

Now the arithmetic has a reason behind it: 2+8=102+8=102+8=10 and 2+2=42+2=42+2=4. A beta prior combined with a binomial count likelihood stays in the beta family. This makes beta a conjugate prior for that likelihood. For any observed data DDD containing sss passes and fff failures:

p∣D∼Beta⁡(α+s,  β+f)p \mid D \sim \operatorname{Beta}(\alpha+s,\;\beta+f)p∣D∼Beta(α+s,β+f)

Here α\alphaα and β\betaβ are the prior parameters, sss counts observed passes, and fff counts observed failures. Substitute the actual numbers:

Beta⁡(2+8,  2+2)=Beta⁡(10,4)\operatorname{Beta}(2+8,\;2+2)=\operatorname{Beta}(10,4)Beta(2+8,2+2)=Beta(10,4)

Posterior expectation is given by:

E[p∣D]=α+sα+β+s+f=1014≈0.714E[p\mid D]=\frac{\alpha+s}{\alpha+\beta+s+f}=\frac{10}{14}\approx0.714E[p∣D]=α+β+s+fα+s​=1410​≈0.714

Observed alone, the empirical pass fraction is 8/10=0.8008/10=0.8008/10=0.800. Before seeing any runs, the prior mean was 2/4=0.5002/4=0.5002/4=0.500. After the update, the posterior mean resolves to an exact weighted average of those two quantities:

414×0.5+1014×0.8=1014\frac{4}{14}\times0.5 + \frac{10}{14}\times0.8 = \frac{10}{14}144​×0.5+1410​×0.8=1410​

Here the prior holds weight 4 while the empirical runs contribute weight 10. These weights explain the gravitational pull toward 0.5; they don't mean anyone actually ran four historical benchmark tasks.

The next cell repeats that arithmetic and checks the parameter totals before printing the updated rate.

update-agent-success-posterior.py
1prior_success = 2 2prior_failure = 2 3observed_pass = 8 4observed_fail = 2 5 6posterior_success = prior_success + observed_pass 7posterior_failure = prior_failure + observed_fail 8posterior_mean = posterior_success / (posterior_success + posterior_failure) 9 10assert (posterior_success, posterior_failure) == (10, 4) 11print(f"observed rate: {observed_pass / (observed_pass + observed_fail):.3f}") 12print(f"posterior: Beta({posterior_success}, {posterior_failure})") 13print(f"next-task pass probability: {posterior_mean:.3f}")
Output
1observed rate: 0.800 2posterior: Beta(10, 4) 3next-task pass probability: 0.714

Forecasting the next run with the posterior predictive

If the next task is comparable, the posterior predictive probability gives a forecast before it runs. To forecast the outcome of the eleventh task, average each candidate success rate weighted by its posterior credibility. At rate 0.6, the next task has pass probability 0.6; at rate 0.8, it has probability 0.8. Integrating over the entire Beta(10, 4) distribution yields an expected future pass probability equal to the posterior mean, 10/14≈0.71410/14\approx0.71410/14≈0.714.[3]Reference 3Gittins Index for Bayesian Bandits: Beta-Binomial Conjugacyhttps://www.stat.berkeley.edu/~bartlett/courses/2014fall-cs294stat260/lectures/gittins-notes.pdf

This reflects uncertainty about a future outcome, not a claim that ppp is exactly 0.714. If the next task passes, the posterior becomes Beta(11, 4), and the following task's forecast rises to 11/15≈0.73311/15\approx0.73311/15≈0.733. Sequential updates and one combined update give the same parameters when they use the same observations and model.

Why does the posterior mean equal 10/14 instead of the observed pass rate 8/10?

Answer

The Beta(2,2) prior contributes parameter weights of 2 and 2. Combining them with eight passes and two failures yields Beta(10,4), whose mean is 10 divided by 14. Those prior weights are assumptions, not extra observed tasks.

Prior sensitivity: when assumptions outweigh small samples

Two engineers can see the same ten outcomes and reach different posterior means because they chose different priors. Hold the observations fixed and vary only the starting assumption.

The next cell reuses the pass and failure counts and compares a weak Beta(1, 1) prior, a moderate Beta(2, 2) prior, and a strong Beta(20, 20) prior. Predict what should happen before reading the numbers: the strong prior should stay closer to 0.5.

compare-agent-prior-strengths.py
1for success_count, failure_count in [(1, 1), (2, 2), (20, 20)]: 2 updated_success = success_count + observed_pass 3 updated_total = success_count + failure_count + observed_pass + observed_fail 4 print( 5 f"Beta({success_count:>2}, {failure_count:>2}) -> " 6 f"posterior mean {updated_success / updated_total:.3f}" 7 )
Output
1Beta( 1, 1) -> posterior mean 0.750 2Beta( 2, 2) -> posterior mean 0.714 3Beta(20, 20) -> posterior mean 0.560

Beta(20, 20) gives its starting mean a weight of 40, compared with 10 for the new data. The updated mean is therefore 0.8×0.5+0.2×0.8=0.560.8\times0.5+0.2\times0.8=0.560.8×0.5+0.2×0.8=0.56. That strength needs justification, such as substantial evidence that genuinely applies to this agent and task population.

Relative to a uniform Beta(1, 1) baseline, reaching Beta(20, 20) would require 19 historical passes and 19 historical failures, not 40 observed tasks. Parameter weights function as bookkeeping; they aren't provenance records. Keep those two facts separate.

PriorPrior parameter weightPosterior meanInterpretation
Beta(1, 1)20.750Weak symmetric starting assumption
Beta(2, 2)40.714Mild pull toward 0.5
Beta(20, 20)400.560Strong prior dominates ten tasks

Report several defensible priors when the sample is small. If the deployment decision flips between them, collect more representative evidence instead of quietly choosing the prior that makes the preferred outcome win.

An engineer claims Beta(20,20) proves that 40 comparable historical tasks were observed. What information is missing?

Answer

The prior has total parameter weight 40, but that weight isn't automatically 40 observed tasks. Relative to a uniform Beta(1,1) baseline, the same prior could result from 19 historical passes and 19 historical failures. The earlier baseline and the historical evidence's provenance must both be disclosed.

Credible intervals and tail probabilities versus point averages

A mean of 0.714 leaves our original question unanswered: how much evidence says the rate exceeds 0.7? Beta(10, 4) assigns probability both below and above that threshold.

A 90% equal-tailed credible interval leaves 5% of the posterior area below its lower endpoint and 5% above its upper endpoint. The remaining 90% lies between them. These endpoints are the 5th and 95th quantiles, or percentile cutoffs, of the posterior.

SciPy's beta.ppf returns those cutoffs. Its beta.sf(0.7, a, b) returns the area above 0.7, which directly answers our threshold question.[2]Reference 2scipy.stats.betahttps://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.beta.html Use the same Beta(10, 4) posterior for both calculations:

credible-interval-and-threshold.py
1from scipy.stats import beta 2 3a, b = 10, 4 4lower, upper = beta.ppf([0.05, 0.95], a, b) 5prob_above_threshold = beta.sf(0.7, a, b) 6 7print(f"90% credible interval: [{lower:.3f}, {upper:.3f}]") 8print(f"P(rate > 0.7 | data): {prob_above_threshold:.3f}") 9assert abs((beta.cdf(upper, a, b) - beta.cdf(lower, a, b)) - 0.9) < 1e-10
Output
190% credible interval: [0.505, 0.887] 2P(rate > 0.7 | data): 0.579

Calculating the quantiles yields an interval of [0.505, 0.887], while the posterior probability above 0.7 is only 0.579. Having an expected value of 0.714 doesn't mean you're confident the agent clears 0.70; in fact, there's a 42.1% chance its true rate falls below your release bar!

Crucially, this interval reflects parameter uncertainty under the chosen prior and binomial model. Tasks themselves don't yield fractional outputs: each run either succeeds or fails. Frequentist procedures interpret intervals differently, evaluating long-run coverage under repeated sampling. Subsequent lessons explore those distinctions in detail.

Another summary is the posterior standard deviation, which measures spread around the mean. Its square, the variance, has a closed form for Beta(a,ba,ba,b):

Var⁡(p∣D)=ab(a+b)2(a+b+1)\operatorname{Var}(p\mid D)=\frac{ab}{(a+b)^2(a+b+1)}Var(p∣D)=(a+b)2(a+b+1)ab​

At Beta(10, 4), the variance is 40/(196⋅15)≈0.013640/(196\cdot15)\approx0.013640/(196⋅15)≈0.0136, and its square root is about 0.117. Use beta quantiles for the interval above; a shortcut such as mean plus or minus two standard deviations needn't give the intended probability, especially near 0 or 1.

The posterior mean exceeds 0.7. Does the posterior assign at least 90% probability to rates above 0.7?

Answer

No. The mean is 0.714, but the posterior area above 0.7 is only about 0.579. The average and the probability of clearing a threshold answer different questions.

Sample size scaling: comparing 8/10 against 80/100

Hold the Beta(2, 2) prior fixed and compare two alternative sample sizes: eight passes out of ten and eighty passes out of one hundred. Both observed rates are 0.8. The larger run yields Beta(82, 22), not Beta(90, 24): we're replacing the ten-task example with a hundred-task example, not adding the runs together.

The next independent cell computes both means, standard deviations, and equal-tailed intervals. Predict which interval will be narrower before running it:

compare-posterior-uncertainty.py
1from math import sqrt 2from scipy.stats import beta 3 4for observed_pass, observed_fail in [(8, 2), (80, 20)]: 5 a, b = 2 + observed_pass, 2 + observed_fail 6 total = a + b 7 mean = a / total 8 variance = a * b / (total**2 * (total + 1)) 9 lower, upper = beta.ppf([0.05, 0.95], a, b) 10 print(f"Beta({a}, {b}): mean={mean:.3f}, sd={sqrt(variance):.3f}") 11 print(f"90% interval: [{lower:.3f}, {upper:.3f}]") 12 print(f"P(rate > 0.7 | data): {beta.sf(0.7, a, b):.3f}")
Output
1Beta(10, 4): mean=0.714, sd=0.117 290% interval: [0.505, 0.887] 3P(rate > 0.7 | data): 0.579 4Beta(82, 22): mean=0.788, sd=0.040 590% interval: [0.720, 0.851] 6P(rate > 0.7 | data): 0.981

With one hundred tasks, the posterior mean moves to 0.788, the spread tightens dramatically, and the 90% credible interval contracts to [0.720, 0.851]. Posterior tail probability above 0.7 jumps from 57.9% to 98.1%. That contrast shows why sample size transforms raw fractions into actionable decisions: identical 80% empirical rates deliver completely opposite degrees of certainty.

Two 90% equal-tailed posterior intervals compared against a 0.70 deployment threshold. Eight passes out of ten gives an interval of 0.505 to 0.887 with mean 0.714 and only 57.9% posterior probability above threshold (Reject). Eighty passes out of one hundred gives a narrow interval of 0.720 to 0.851 with mean 0.788 and 98.1% posterior probability above threshold (Promote).
Credible intervals versus the 0.70 deployment threshold. Both runs observed an 80% pass rate from a Beta(2, 2) prior, but only the 100-task evaluation provides sufficient statistical power to clear the 95% posterior confidence rule.

More data doesn't remove randomness from individual future tasks. Even if we learned that ppp was exactly 0.8, a new task could still fail. It also doesn't remove uncertainty caused by a wrong model or an unrepresentative sample.

Posterior dispersion versus empirical calibration

Posterior spread and calibration answer different questions. The posterior describes uncertainty about a success rate under a chosen model. Calibration asks whether forecasts line up with later outcomes: among many comparable tasks assigned a pass probability near 0.7, do about 70% pass?

A frozen 0.714 forecast can't establish calibration from the same ten tasks that produced it. Save forecasts before later outcomes arrive. Across enough predictions, group similar probabilities and compare each group's average forecast with its observed pass fraction.[4]Reference 4On Calibration of Modern Neural Networkshttps://arxiv.org/abs/1706.04599 With only one frozen forecast, this amounts to comparing that forecast with the pass fraction on a fresh batch.

Small batches fluctuate, so one mismatch isn't proof of a bad model. Persistent discrepancies deserve investigation: did the task mix shift, were retries counted as new tasks, or did the agent's policy change? More data can narrow a wrong model's posterior without making its predictions reliable.

Sampling failure modes that corrupt the posterior

The arithmetic can be correct while the inference is wrong.

FailureVisible symptomRepair
Repeated retries of one taskTen rows claim to represent ten independent tasksGroup retries by underlying task and sample distinct tasks
Easy benchmark slicePosterior looks strong while hard production tasks failStratify by task family and compare deployment traffic
Historical prior from another agentStrong prior hides a real regressionRecord prior provenance and run sensitivity checks
Hidden prompt changesOutcomes combine incompatible policiesPin model, prompt, tools, and task definitions
Selective release reportingOnly a favorable stopping point or chosen agent is disclosedRecord every evaluated agent, stopping rule, and release decision

Keep the collection and reporting process visible. Omitted runs, selected agents, or an undisclosed change of target population can make the reported analysis answer a different question from the one a reader assumes. Updating can't turn duplicated or biased rows into representative observations.

A model passes eight out of ten tasks, but all ten rows are retries of the same prompt. Why is Beta(10,4) misleading?

Answer

The intended parameter describes new tasks from the deployment population. Ten retries of one prompt mainly describe that prompt. Even if retry randomness is independent, the prompt wasn't sampled ten times independently from that population. A beta update might model that prompt's retry success rate, but it doesn't establish the broader task success rate.

Production release gates with posterior decision rules

For this exercise, choose the rule before seeing results: increase traffic only if the posterior probability that p>0.7p>0.7p>0.7 is at least 95%. This is an illustrative evidence threshold, not a universal release policy. Real decisions also depend on the cost of failures, traffic exposure, and other safety checks.

Under Beta(2, 2), the ten-task result doesn't pass this rule: 0.579 < 0.95. The hundred-task result does: 0.981 > 0.95, provided its tasks and policy satisfy the model assumptions. Neither decision follows from the raw 80% rate alone.

Try these changes before reading the answers:

  1. One more comparable task fails after the original eight passes and two failures. What are the new posterior and next-task forecast?
  2. Apply the 95% evidence rule to the original ten outcomes with Beta(1, 1) and Beta(20, 20) priors. Use beta.sf(0.7, a, b), not just the mean. Does either pass?
  3. Could the hundred-task result justify the same claim if every task came from an unusually easy benchmark family?

Decision and sensitivity analysis checks

  1. Add the failure once: Beta(10, 5), with forecast 10/15≈0.66710/15\approx0.66710/15≈0.667. Don't add the original ten observations again when starting from their posterior.
  2. Posteriors update to Beta(9, 3) and Beta(28, 22). Their probabilities above 0.7 evaluate to 0.687 and 0.019, respectively. Neither meets the 0.95 requirement. Although the estimates differ, all three priors produce the exact same rejection decision under this rule.
  3. No. That posterior describes the sampled task family. A narrow interval doesn't correct the mismatch with deployment traffic; sample from the intended population or explicitly model and weight its task families.

Report the observations, prior justification, posterior interval, threshold probability, and decision rule together. If reasonable priors do lead to opposite decisions, make that dependence visible rather than choosing the most convenient prior.

What should a release reviewer conclude when one justified prior passes the deployment threshold but another equally defensible prior fails it?

Answer

The available sample doesn't support a prior-robust decision. Record both priors and posterior results, keep the release undecided, and collect additional representative tasks before claiming the threshold is met.

Complete the lesson

Mastery Check

Answer every question, then check your score. Score 75% or higher to mark this lesson complete.

1.A Beta(2,2) prior observes eight passes and two failures. Which posterior follows from beta-binomial updating?

Correct answer: Beta(10,4), adding passes and failures to their matching prior counts.

The beta-binomial update adds successes to alpha and failures to beta, so Beta(2+8,2+2) becomes Beta(10,4).

2.What is the posterior predictive probability that the next comparable task passes under Beta(10,4)?

Correct answer: 0.714, because the predictive probability equals 10 divided by 14.

For a Bernoulli outcome with a beta posterior, the next-trial predictive probability is the posterior mean a/(a+b).

3.Why can a Beta(20,20) prior produce a much smaller posterior mean than Beta(1,1) for the same ten observations?

Correct answer: The stronger prior contributes more pseudo-count weight before the new evidence.

Beta(20,20) gives its prior mean weight 40 and the observations weight 10, producing 0.56. That parameter weight doesn't prove 40 historical tasks were observed; relative to a uniform Beta(1,1) baseline, 19 passes and 19 failures would yield the same prior.

4.Which statement correctly describes a 90% Bayesian credible interval?

Correct answer: The stated posterior assigns 90% probability to parameter values in the interval.

A credible interval is a statement about posterior probability under the chosen prior, likelihood, and observed evidence.

5.An agent's ten evaluation rows are retries of one prompt. What assumption becomes doubtful?

Correct answer: The rows behave like distinct representative task outcomes for the intended population.

The intended parameter concerns new tasks drawn from a deployment population. Ten retries of one prompt aren't ten independently sampled tasks, even if the agent's random choices on those retries are independent. They may support an inference about that prompt instead.

6.Which action most directly checks whether a release decision depends on an unjustified prior?

Correct answer: Recompute the decision under several defensible priors and record the changes.

Prior sensitivity analysis reveals whether limited observations support the same decision under reasonable historical assumptions.

7.What changes when the same Beta(2,2) prior receives eighty passes and twenty failures instead of eight passes and two failures?

Correct answer: The larger sample reduces prior influence and narrows posterior uncertainty.

For this comparison, the observed rate stays 0.8 while the sample grows tenfold. The posterior changes from Beta(10,4) to Beta(82,22), and its 90% interval narrows from about [0.505,0.887] to [0.720,0.851]. This doesn't remove sampling bias or guarantee that each future task passes.

8.Why isn't likelihood alone a posterior probability distribution over candidate success rates?

Correct answer: A posterior also requires an explicit prior and normalization by the evidence.

Likelihood scores fixed observations under candidate parameters. Bayes' rule multiplies that likelihood by a prior and normalizes the product. The 0.302 likelihood at p=0.8 is the chance of eight passes out of ten if that rate were true, not the posterior probability that the rate equals 0.8.

9.A release rule requires at least 95% posterior probability that the success rate exceeds 0.7. Beta(10,4) has mean 0.714 but P(p > 0.7 | data) = 0.579. Does it meet the rule?

Correct answer: No, because 0.579 is below the required posterior probability 0.95.

The rule has two different numbers: 0.7 is the minimum acceptable success rate, and 0.95 is the required posterior confidence in clearing it. The posterior average doesn't measure that confidence. The hundred-task Beta(82,22) example meets the numerical rule with probability about 0.981, subject to the sampling assumptions.

9 questions remaining.

Next Step
Continue to Statistics and Uncertainty

A posterior turns limited observations into a distribution; the next lesson compares sample estimates, variation, and uncertainty before those numbers drive model decisions.

PreviousProbability for Machine Learning
Share this article
XFacebookLinkedInBlueskyRedditHacker NewsEmail
References

Machine Learning: A Probabilistic Perspective.

Murphy, K. P. · 2012

https://probml.github.io/pml-book/book0.html

scipy.stats.beta

SciPy Developers · 2026

https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.beta.html

Gittins Index for Bayesian Bandits: Beta-Binomial Conjugacy

Bartlett, P. · 2014 · University of California, Berkeley

https://www.stat.berkeley.edu/~bartlett/courses/2014fall-cs294stat260/lectures/gittins-notes.pdf

On Calibration of Modern Neural Networks

Guo, C., Pleiss, G., Sun, Y., & Weinberger, K. Q. · 2017

https://arxiv.org/abs/1706.04599

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.