PART 1 • FOUNDATIONS • LEVEL 04

Probability & Statistics for Machine Learning

Turn uncertainty into measurable evidence. Learn how models reason about chance, summarize data, estimate unknown quantities and distinguish real signals from random variation.

⏱️ 150–180 min🎯 Beginner → Interview Ready🧪 2 Interactive Labs💼 Placement Statistics
μ−σ
PRIOR10%+ EVIDENCEPOSTERIOR

By the End of This Level, You Can

01Define experiments, outcomes, sample spaces and events precisely.
02Use conditional probability, independence, total probability and Bayes’ theorem.
03Recognize important discrete and continuous probability distributions.
04Calculate and interpret expectation, variance, covariance and correlation.
05Explain sampling, confidence intervals, hypothesis tests and p-values correctly.
06Connect likelihood and uncertainty to training, evaluation and model decisions.

Five Skills Used Throughout This Level

Probability becomes easier when these arithmetic and set ideas are clear.

FRACTIONPart of a whole

favourable / total for equally likely outcomes.

PERCENTAGEProbability × 100

0.25 and 25% express the same chance.

SETSUnion & intersection

A ∪ B means either; A ∩ B means both.

AVERAGECentre of values

The mean balances all observations but reacts to outliers.

SQUARE ROOTReturn to original units

Standard deviation is the square root of variance.

Experiment, Outcome, Sample Space and Event

A probability statement begins by defining exactly what can happen.

01Experiment

A repeatable uncertain process, such as rolling a die.

02Outcome

One observed result, such as rolling 4.

03Sample space Ω

Every possible outcome: {1, 2, 3, 4, 5, 6}.

04Event A

A subset of outcomes, such as even = {2, 4, 6}.

For equally likely outcomesP(A) = |A| / |Ω|Always: 0 ≤ P(A) ≤ 1
DETAILED EXPLANATION

An experiment is a repeatable uncertain process, an outcome is one possible result, the sample space contains all possible outcomes, and an event is a selected subset. Defining these precisely determines which probabilities are meaningful.

WORKED INTUITION

For two coin tosses the sample space is {HH, HT, TH, TT}; the event ‘exactly one head’ is {HT, TH}.

AI / PLACEMENT CONNECTION

In classification, events may represent positive predictions, real positives or specific error types.

COMMON MISCONCEPTION

Events must be defined before inspecting results to avoid changing the question after seeing the data.

Core Probability Rules

Use set structure to avoid double-counting outcomes.

COMPLEMENTP(Aᶜ) = 1 − P(A)

Often easier to calculate “not A” first.

ADDITIONP(A∪B)=P(A)+P(B)−P(A∩B)

Subtract the overlap counted twice.

MUTUALLY EXCLUSIVEP(A∩B) = 0

The events cannot occur together.

TOTAL PROBABILITYP(B)=ΣP(B|Aᵢ)P(Aᵢ)

Combine every disjoint route to B.

DETAILED EXPLANATION

Probabilities range from 0 to 1 and sum to 1 over mutually exclusive complete outcomes. The complement rule handles ‘not A,’ addition handles unions, and multiplication handles joint events through conditional probability. Inclusion–exclusion prevents double-counting overlap.

WORKED INTUITION

P(A or B)=P(A)+P(B)-P(A and B). If A and B cannot occur together, the intersection term is zero.

AI / PLACEMENT CONNECTION

These rules support confusion-matrix rates, probabilistic models and risk calculations.

COMMON MISCONCEPTION

Do not multiply P(A) and P(B) unless independence is justified.

Conditional Probability and Independence

New evidence changes the relevant sample space.

CONDITIONAL PROBABILITYP(A|B) = P(A∩B) / P(B)

Read as “probability of A given B.” Require P(B) > 0.

INDEPENDENCEP(A∩B) = P(A)P(B)

Knowing B does not change A, so P(A|B) = P(A).

Interview trap: Mutually exclusive events with positive probability are not independent. If one happens, the other becomes impossible.
DETAILED EXPLANATION

Conditional probability P(A|B) restricts attention to cases where B occurred. Independence means learning B does not change the probability of A. Conditional independence is weaker and depends on known context; it is central to graphical models and Naive Bayes.

WORKED INTUITION

Rain and traffic may be dependent overall but conditionally independent after controlling for location and time in a simplified model.

AI / PLACEMENT CONNECTION

Feature assumptions in probabilistic classifiers are statements about conditional relationships.

COMMON MISCONCEPTION

P(A|B) and P(B|A) answer different questions and are rarely equal.

Bayes’ Theorem: Update Belief with Evidence

Bayes reverses a conditional probability by combining prior belief and evidence reliability.

POSTERIORP(A|B)=
P(B|A)LIKELIHOOD
×
P(A)PRIOR
÷
P(B)EVIDENCE
Prior

Belief before observing current evidence.

Likelihood

How expected the evidence is if the hypothesis is true.

Evidence

Total probability of seeing the observation.

Posterior

Updated belief after combining prior and evidence.

DETAILED EXPLANATION

Bayes’ theorem reverses a conditional probability by combining prior belief, evidence likelihood and overall evidence rate. The posterior is proportional to likelihood times prior. It formalizes how base rates influence conclusions even when a test is accurate.

WORKED INTUITION

A rare disease can have many false positives because healthy people greatly outnumber affected people, reducing P(disease|positive).

AI / PLACEMENT CONNECTION

Bayesian reasoning appears in diagnosis, spam filtering, inference and uncertainty updates.

COMMON MISCONCEPTION

Ignoring prevalence creates the base-rate fallacy and overstates the meaning of a positive result.

Random Variables, PMF, PDF and CDF

A random variable maps each outcome to a numerical value.

DISCRETEPMF: P(X = x)

Assigns probability mass to countable values. All masses sum to 1.

CONTINUOUSPDF: f(x)

Probability is area under a density curve. At one exact point, probability is 0.

BOTHCDF: F(x)=P(X≤x)

Accumulated probability up to x. It never decreases and approaches 1.

DETAILED EXPLANATION

A random variable assigns a number to each outcome. A PMF gives probabilities for discrete values; a PDF describes density for continuous values; a CDF gives the probability of being at or below a value. For continuous variables, probability is area over an interval, not density at one point.

WORKED INTUITION

The CDF can answer the probability that response time is at most 200 ms regardless of whether the distribution is discrete or continuous.

AI / PLACEMENT CONNECTION

Models often predict distributions or quantiles rather than a single value.

COMMON MISCONCEPTION

A PDF value can exceed 1; only its total area must equal 1.

Important Distributions for AI & ML

A distribution describes which values are possible and how likely they are.

BERNOULLIOne success/failure trial

Click, churn, fraud or class label. Parameter: p.

BINOMIALSuccess count in n trials

Assumes fixed n, constant p and independent trials.

POISSONEvent count in an interval

Arrivals, failures or requests with average rate λ.

UNIFORMEqual density in a range

Useful for random initialization and simple simulation.

NORMALSymmetric bell-shaped values

Controlled by mean μ and variance σ².

DETAILED EXPLANATION

Bernoulli models one binary trial, Binomial counts successes across repeated trials, Gaussian models many symmetric continuous variations, Poisson counts events in an interval, and Exponential models waiting time under a constant event rate. Each distribution carries assumptions that must match the process.

WORKED INTUITION

Clicks per minute may be approximated by Poisson only if events are suitably independent and the average rate is stable.

AI / PLACEMENT CONNECTION

Choosing a loss function often corresponds to an assumed target distribution.

COMMON MISCONCEPTION

Do not select a distribution only because its curve looks familiar; check support and process assumptions.

Expectation, Variance and Standard Deviation

Expectation describes long-run centre; variance describes squared spread around it.

EXPECTED VALUEE[X] = ΣxP(X=x)

A probability-weighted average, not necessarily an observable outcome.

VARIANCEVar(X)=E[(X−μ)²]

Average squared deviation; units are squared.

STANDARD DEVIATIONσ = √Var(X)

Spread in the same units as X.

Useful identityVar(X) = E[X²] − E[X]²For independent X,Y: Var(X+Y)=Var(X)+Var(Y)
DETAILED EXPLANATION

Expectation is the long-run probability-weighted average. Variance measures expected squared deviation from the mean, and standard deviation returns to the original units. Linearity of expectation works even without independence, while variance addition usually needs covariance terms.

WORKED INTUITION

Two investments can have equal expected return but very different variance and therefore different risk.

AI / PLACEMENT CONNECTION

Expected loss is the quantity many learning algorithms seek to minimize.

COMMON MISCONCEPTION

The mean may be unrepresentative for heavy-tailed or strongly skewed data.

Covariance and Correlation

Both describe how two variables move together, but only correlation is scale-free.

COVARIANCECov(X,Y)=E[(X−μₓ)(Y−μᵧ)]

Sign indicates direction; magnitude depends on units and scale.

CORRELATIONρ = Cov(X,Y)/(σₓσᵧ)

Standardized linear association from −1 to +1.

−1
negative
0
none linear
+1
positive
Critical rule: Correlation does not prove causation, and zero correlation does not guarantee independence or absence of a non-linear relationship.
DETAILED EXPLANATION

Covariance measures whether two variables move together in their original scales. Correlation standardizes covariance to a unit-free value from -1 to 1. Both summarize linear association and may miss nonlinear dependence or be distorted by outliers.

WORKED INTUITION

Height measured in centimetres and metres changes covariance but not correlation.

AI / PLACEMENT CONNECTION

Correlation matrices support EDA, feature selection and multicollinearity diagnosis.

COMMON MISCONCEPTION

Correlation does not establish causation, and zero correlation does not always mean independence.

Population, Sample, LLN and CLT

We observe samples to learn about a larger population.

POPULATIONUnknown truth

Parameters such as μ, σ and p describe it.

RANDOM SAMPLEObserved evidence

Statistics such as x̄, s and p̂ summarize it.

INFERENCEEstimate uncertainty

Intervals and tests connect sample evidence to population claims.

Law of Large Numbers

As sample size grows, the sample average tends toward the expected value.

Central Limit Theorem

Under common conditions, standardized sample means approach a normal distribution as n grows.

DETAILED EXPLANATION

A population is the complete group of interest; a sample is the observed subset. The law of large numbers explains why sample averages stabilize with more independent observations. The central limit theorem explains why many properly normalized sample means approach a normal distribution under suitable conditions.

WORKED INTUITION

Repeatedly averaging larger random samples produces a tighter sampling distribution around the population mean.

AI / PLACEMENT CONNECTION

Sampling theory supports uncertainty estimates, experiment analysis and model evaluation.

COMMON MISCONCEPTION

More biased data converges to the wrong quantity; sample size cannot repair unrepresentative collection.

Descriptive Statistics and Robust Summaries

Choose summaries that match the data distribution and decision.

MEANUses every value

Efficient for symmetric data but sensitive to outliers.

MEDIANMiddle ordered value

Robust for skewed distributions and extreme observations.

MODEMost frequent value

Works with categories and repeated numeric values.

IQRQ3 − Q1

Robust spread of the central 50% of observations.

DETAILED EXPLANATION

Descriptive statistics summarize centre, spread, range, quantiles and shape. Mean and standard deviation are sensitive to extreme values; median and interquartile range are more robust. Always pair summaries with distributions and relevant subgroups.

WORKED INTUITION

For income data, the median usually represents a typical person better than the mean because the upper tail is long.

AI / PLACEMENT CONNECTION

Robust summaries guide imputation, scaling and anomaly investigation.

COMMON MISCONCEPTION

One overall average can hide opposite patterns across groups or time periods.

Estimation and Confidence Intervals

A point estimate gives one value; an interval reports plausible values under repeated-sampling logic.

LOWERUPPER
estimate ± critical value × standard error
Correct 95% interpretation:If we repeated the sampling method many times, about 95% of the constructed intervals would contain the true parameter. It is not a 95% probability statement about a fixed parameter after the interval is computed.
DETAILED EXPLANATION

A point estimate gives one plausible parameter value; a confidence interval describes the long-run performance of an interval-building procedure. Its width reflects sample size, variability and confidence level. Assumptions about sampling and dependence determine whether the interval is valid.

WORKED INTUITION

A 95% confidence procedure captures the true parameter in about 95% of repeated compatible studies—not with 95% probability for one fixed frequentist interval.

AI / PLACEMENT CONNECTION

Intervals communicate uncertainty more honestly than reporting a metric to several decimals.

COMMON MISCONCEPTION

Narrow intervals are not meaningful when data collection is biased or observations are dependent.

Hypothesis Testing Without Misinterpretation

A test asks whether observed data would be unusually incompatible with a specified null hypothesis.

1State H₀ and H₁

Define the claim and alternative before inspecting results.

2Choose α

Set the false-positive tolerance, commonly 0.05.

3Calculate evidence

Use an appropriate test statistic and assumptions.

4Decide carefully

Reject or fail to reject H₀; report effect size and uncertainty.

TYPE I • FALSE POSITIVEReject a true H₀

Probability controlled by α under the null.

TYPE II • FALSE NEGATIVEFail to reject a false H₀

Probability β; power equals 1 − β.

P-VALUEP(data this extreme | H₀)

Not the probability that H₀ is true.

DETAILED EXPLANATION

Hypothesis testing compares observed evidence with a null model. A p-value is the probability, assuming the null and test assumptions, of obtaining a result at least as extreme. It is not the probability that the null is true and does not measure practical importance.

WORKED INTUITION

A tiny improvement can be statistically significant with a huge sample but still be operationally useless.

AI / PLACEMENT CONNECTION

A/B testing requires effect size, uncertainty, power and decision cost in addition to a p-value.

COMMON MISCONCEPTION

Repeated peeking or testing many hypotheses without correction increases false discoveries.

Likelihood, MLE and MAP

Model training often chooses parameters that make observed data probable.

LIKELIHOODL(θ|data)

Treat data as fixed and compare candidate parameter values.

MAXIMUM LIKELIHOODθ̂MLE = argmax L

Select parameters that best explain observed data.

MAP ESTIMATIONθ̂MAP = argmax posterior

Combine likelihood with a prior; regularization often has this interpretation.

Numerical practice: Maximize log-likelihood instead of multiplying many tiny probabilities. Logs convert products into stable sums.
DETAILED EXPLANATION

Likelihood treats observed data as fixed and compares parameter values by how well they explain it. Maximum likelihood chooses the highest-likelihood parameters. MAP adds a prior and maximizes the posterior, often producing a regularized solution.

WORKED INTUITION

For Bernoulli observations, the maximum-likelihood success probability is the observed fraction of successes.

AI / PLACEMENT CONNECTION

Cross-entropy training is maximum likelihood for common classification models.

COMMON MISCONCEPTION

Likelihood is not a probability distribution over parameters unless a prior and normalization create a posterior.

Experiment Design and A/B Testing

Good statistics begins before data collection.

RANDOMIZE

Reduce systematic allocation bias.

CONTROL

Provide a meaningful comparison baseline.

PREDEFINE

Choose primary metric, α and stopping rule first.

CHECK POWER

Use enough observations to detect a meaningful effect.

SEGMENT CAREFULLY

Avoid uncontrolled multiple comparisons.

REPORT EFFECT

Statistical significance is not practical importance.

DETAILED EXPLANATION

A controlled experiment changes one factor and uses random assignment to balance known and unknown confounders. Define the unit, treatment, primary metric, guardrails, duration and analysis before starting. Practical significance and user harm matter alongside statistical significance.

WORKED INTUITION

Randomize users—not page views—when repeated views from the same person could contaminate both variants.

AI / PLACEMENT CONNECTION

Online ML systems often require experiments to verify that offline metric gains improve real outcomes.

COMMON MISCONCEPTION

Stopping as soon as significance appears inflates false-positive risk unless a sequential method was planned.

INTERACTIVE LEARNING • CODEBHAVYA PREMIUM VISUALIZER

🎬 Bayes’ Theorem — Visual Flow

Trace a factory alert where 10% of items are defective, sensitivity is 80% and the false-positive rate is 20%.

LIVE
STEP 1 OF 7

Begin with 100 items

Use a natural-frequency view to make every probability concrete.

Step 1 of 7
PROGRAM TRACING • TRUE LOOP FLOW

Trace a Monte Carlo Probability Estimate

Watch the cursor revisit the loop and condition while six recorded die rolls estimate P(rolling a six).

Estimate Probability from Repeated Trials

Monte Carlo methods approximate an unknown quantity by repeating a random experiment and aggregating outcomes.

rolls = [2, 6, 4, 1, 6, 3]
successes = 0
for roll in rolls:
    if roll == 6:
        successes += 1
trials = len(rolls)
estimate = successes / trials
print(round(estimate, 2))
MONTE CARLO ESTIMATE
p̂ = successes / trials
  • Trial: one repetition of the experiment.
  • Success: the event being estimated.
  • Estimate: observed relative frequency.
  • LLN: p̂ tends toward p as trials grow.
  • Uncertainty: finite simulations still contain sampling error.

Practise Probability and Statistical Reasoning

Attempt each problem independently. The checker rewards correct formulas, NumPy operations and requested output.

0 / 5Solved independently0 / 500Best score

Test Probability and Statistical Interpretation

Select one answer for every question. Results show your answer, the correct answer and an explanation.

Not checked yet

How Statistics Appears in Hiring Rounds

Interviewers look for correct interpretation, not only memorized formulas.

ROUND 01

Bayes Reasoning

Convert rates into natural frequencies and avoid base-rate neglect.

ROUND 02

Distribution Choice

Match Bernoulli, Binomial, Poisson or Normal assumptions to a scenario.

ROUND 03

Experiment Analysis

Interpret confidence intervals, p-values, effect size and power.

ROUND 04

ML Connection

Explain likelihood, loss functions, calibration and uncertainty.

CodeBhavya interview pattern:Define the quantity → State assumptions → Show the formula → Interpret in context → Mention one misuse.

🎤 Probability & Statistics — Interview Questions

Answer aloud before selecting Show Answer for each explanation.

Statistical Reasoning in One View

1Model chance

Events and distributions describe uncertainty.

2Summarize

Centre, spread and association reveal data structure.

3Infer

Samples estimate populations with measurable uncertainty.

4Decide

Combine evidence, assumptions and practical importance.

Statistics does not remove uncertainty—it makes uncertainty visible enough to reason and act responsibly.

Habits of Reliable Statistical Thinkers

01

Define the sample space and event before calculating probability.

02

Use natural frequencies such as “8 out of 100” for Bayes problems.

03

Plot the distribution before reporting only mean and standard deviation.

04

Check independence, sampling and distribution assumptions explicitly.

05

Report effect sizes and confidence intervals beside p-values.

06

Separate statistical significance from practical or business value.

Strengthen Probability and Statistics

Solve conceptually first, then verify through code or simulation.

  1. 01

    List the sample space for tossing two coins.

  2. 02

    Find the probability of at least one head in two tosses.

  3. 03

    Explain the difference between mutually exclusive and independent events.

  4. 04

    Calculate P(A∪B) when P(A)=0.5, P(B)=0.4 and P(A∩B)=0.2.

  5. 05

    Use Bayes’ theorem for a 1% base rate, 95% sensitivity and 5% false-positive rate.

  6. 06

    Choose a distribution for the number of calls arriving each minute.

  7. 07

    Calculate the expected value of a fair six-sided die.

  8. 08

    Compare mean and median for [2, 3, 4, 5, 100].

  9. 09

    Explain why standard deviation is easier to interpret than variance.

  10. 10

    Describe what correlation 0.8 does and does not prove.

  11. 11

    Interpret a 95% confidence interval for an A/B conversion difference.

  12. 12

    Explain a p-value of 0.03 without saying H₀ has a 3% chance of being true.