Guide to AI and Data Courses · Lecture Notes

Chapter 32: Probability and Statistics

A hospital introduces a new screening test, and the manufacturer says it is "95 percent reliable". What should we tell a patient whose test comes back positive? The answer can be a much lower number than most people expect, and the way to find it runs through probability. Probability and Statistics teaches how to express uncertainty with numbers and how to say how sure we can be when we draw conclusions from limited data. These notes introduce the course and work through its three core ideas with small examples you can compute by hand.

Learning outcomes

Probability and Bayes
Define conditional probability and use Bayes' rule to compute the probability of disease from a test result.
Random variables
Compute the expected value and variance of a discrete random variable; find the standard error of a mean.
Estimation
Estimate a proportion from a sample and compute its approximate 95% confidence interval.
Hypothesis testing
Find the z statistic and the p-value for a difference of two proportions; interpret the p-value correctly.
Place of the course
State how probability and statistics relate to machine learning, data science, probabilistic graphical models and information theory.

32.1What question does the course ask?

How is uncertainty measured, and how do we draw reliable conclusions from limited data?

Probability is the language for measuring uncertainty; statistics uses it to draw general conclusions from limited data. Every model in AI and data courses works under uncertainty, and only this course can say how far a prediction can be trusted.

Certain knowledge is rare in the real world. We do not know a coin's probability of heads, we see a drug's effect in only a few hundred patients, we measure a model's quality only on the test sample we happen to have. In this situation the course asks two questions. The first is a probability question: when the process is known, which outcomes should we expect, and how often? The second is a statistics question: when the outcomes have been observed, what can we say about the process? Probability goes from cause to effect, statistics from effect to cause.

Mixing up these directions is the most common thinking error. "Does a sick person test positive?" and "is a person who tested positive sick?" are two different questions with very different answers; the bridge between them is Bayes' rule. The first core section builds that bridge.

32.1.1Sample and population

The basic distinction in statistics is between the sample we observe and the population we care about. In an A/B test, the 4000 users who saw the new screen are the sample; the population is everyone who will use the system in the future. When the sample is chosen at random, every number computed from it (a mean, a proportion) is itself a random variable: another sample would have given another value. Knowing how much it varies determines how far a result can be trusted. Estimation and hypothesis testing are the tools that measure this variation. The same tools appear in machine learning: the test-set accuracy in Machine Learning is also a number computed from a sample.

32.1.2At a glance

CriterionProbability and Statistics
Approachprobability models and inference
Inputsample data
Outputestimate, confidence interval, test result
Success measureunbiasedness, power, significance
Math loadthe theory itself
Data needsa sample

32.2A short history

YearMilestone
1654Pascal and Fermat exchange letters on dividing the stakes of an unfinished game of chance.
1763Bayes's essay is published after his death: probability updated by evidence.
1908Gosset, writing as "Student", publishes the t distribution for small samples.
1925Fisher's Statistical Methods for Research Workers popularizes significance testing.
1933Kolmogorov builds probability on axioms; probability theory rests on measure theory.
1979Efron proposes the bootstrap: measuring uncertainty by resampling.

32.3Core concepts

The rest of the course is built on the concepts below. The following sections work through the most important ones with examples.

ConceptMeaning
Conditional probabilityHow a probability changes given information.
Bayes' ruleTurning a prior belief into a posterior with evidence.
Random variableExpected value, variance and distribution.
Normal distributionCentral limit theorem: averages tend to normal.
Maximum likelihoodChoosing the parameter that makes the data most likely.
Confidence intervalReporting an estimate's uncertainty as a range.
Hypothesis testingIs the observed difference chance or real?
RegressionExplaining one variable by others, and testing it.

32.4Conditional probability and Bayes' rule

When we learn something about an event, its probability changes. Conditional probability is the probability of event A given that event B has happened. Bayes' rule turns the two directions around: knowing the probability of the evidence under a hypothesis, it gives the probability of the hypothesis under the evidence.

Definition 32.1 (Conditional probability and Bayes' rule)

P(A | B) = P(A ∩ B) / P(B) (when P(B) > 0). Bayes' rule: P(H | E) = P(E | H) · P(H) / P(E), where P(H) is the prior, P(E | H) the likelihood and P(H | E) the posterior. The denominator comes from the law of total probability: P(E) = P(E | H) P(H) + P(E | Hc) P(Hc).

Example 32.1: What does a positive test tell us?

Let a disease occur in 1% of the population (the base rate). The test is positive for 90% of sick people (sensitivity 0.90) and negative for 95% of healthy people (specificity 0.95, so the false alarm rate is 0.05). What is the probability that a person with a positive test is sick? The easiest way is to imagine 10,000 people (natural frequencies).

  1. The sick. 1% of 10,000 are sick: 100 sick, 9,900 healthy.
  2. True positives. 90% of the 100 sick test positive: 90 people.
  3. False alarms. 5% of the 9,900 healthy test positive: 495 people.
  4. All positives. 90 + 495 = 585 people.
  5. Posterior. P(sick | positive) = 90 / 585 ≈ 0.154.

The formula gives the same result: 0.90 · 0.01 / (0.90 · 0.01 + 0.05 · 0.99) = 0.009 / 0.0585 ≈ 0.154. Even with a "very reliable" test, a person who tests positive is sick with a probability of only about 15%, because the disease is rare and healthy people vastly outnumber the sick. (The values are illustrative.)

Now the same person takes the test a second time and is positive again (treat the two tests as independent). The prior is now 0.154. In odds form: 0.154 / 0.846 ≈ 0.182; each positive result multiplies the odds by 0.90 / 0.05 = 18: 0.182 · 18 ≈ 3.27, so the probability is 3.27 / 4.27 ≈ 0.77. After a second positive result the probability of being sick rises to about 77%.

This calculation is not only for physicians. The Naive Bayes classifier used as a spam filter performs the same operation: when the word "discount" appears in a message, it updates the probability that the message is spam using the prior odds and the frequency of the word in the two classes. Updating a probability as evidence accumulates is the heart of Bayesian inference.

Common mistake

Reading "the test is 95% accurate" as "a person who tests positive is sick with 95% probability". The first statement is about P(positive | sick), the second about P(sick | positive). The difference between them is the base rate: the gap between 0.90 and 0.154 in the example above comes from it. Reasoning that ignores the base rate is called the base rate fallacy.

32.5Expectation, variance and the central limit theorem

A random experiment whose outcomes are numbers is described by a random variable. The center of a distribution is measured by the expected value, its spread by the variance. The square root of the variance is the standard deviation, which has the same units as the variable.

Definition 32.2 (Expected value and variance)

For a discrete X, E[X] = Σ x · P(X = x) and Var(X) = E[(X − E[X])2] = E[X2] − (E[X])2. For a linear transformation, E[aX + b] = a E[X] + b and Var(aX + b) = a2 Var(X).

Example 32.2: The mean of a fair die and the spread of the average

Let X be the number on the top face of a fair die.

  1. Expected value. E[X] = (1 + 2 + 3 + 4 + 5 + 6) / 6 = 3.5.
  2. Second moment. E[X2] = (1 + 4 + 9 + 16 + 25 + 36) / 6 = 91/6 ≈ 15.167.
  3. Variance. Var(X) = 91/6 − 3.52 = 35/12 ≈ 2.917; standard deviation σ ≈ 1.708.
  4. Linear transformation. For Y = 2X + 1, E[Y] = 2 · 3.5 + 1 = 8 and Var(Y) = 4 · 35/12 ≈ 11.67.
  5. Average of 36 rolls. For the mean X̄ of n independent observations, E[X̄] = 3.5 and Var(X̄) = σ2/n. Its standard deviation (the standard error) is σ/√n = 1.708 / 6 ≈ 0.285.
  6. Central limit theorem. X̄ is approximately normal. For the probability that the average exceeds 4, z = (4 − 3.5) / 0.285 ≈ 1.76; from the normal distribution, P(X̄ > 4) ≈ 0.039.

A single roll can be as far as 2.5 from 3.5, but the average of 36 rolls stays in a very narrow region around 3.5: fewer than 4% of averages exceed 4.

32.5.1Why is the normal distribution everywhere?

The central limit theorem says that the average of independent, identically distributed observations approaches the normal distribution as n grows, even when the individual observations are not normal. A single die is uniform and looks nothing like a bell curve, yet its averages do. The practical value of the theorem is that we can build confidence intervals and tests for means even when we do not know the distribution of the process. The law of large numbers says that X̄ approaches the expected value as n grows; this is the justification for using the sample mean as an estimate.

Common mistake

Confusing the standard deviation with the standard error. The standard deviation (1.708) is the spread of a single observation; the standard error (0.285) is the spread of the mean and shrinks with √n. To halve the margin of error one needs four times as many observations.

32.6Estimation, confidence intervals and hypothesis testing

When we sample from a distribution whose parameter we do not know, the first step is an estimate (a point estimate). In a Bernoulli or binomial model, for example for a click rate p, the maximum likelihood estimate is the observed proportion: p̂ = k / n. The second step is to measure the uncertainty of the estimate. The standard error of a proportion is √(p̂(1 − p̂)/n), and the approximate 95% confidence interval is p̂ ± 1.96 · SE.

Example 32.3: A/B test: is the new model really better?

We ask whether a new recommendation model raises clicks. Users are split at random into two groups. Old model (A): 200 clicks from 2000 users; new model (B): 250 clicks from 2000 users (the values are illustrative).

  1. Estimates. p̂A = 200/2000 = 0.100, p̂B = 250/2000 = 0.125; difference 0.025.
  2. Standard error of the difference. √(0.1·0.9/2000 + 0.125·0.875/2000) = √(9.97·10−5) ≈ 0.00998.
  3. 95% confidence interval. 0.025 ± 1.96 · 0.00998 → about [0.0054, 0.0446]. The interval does not contain 0.
  4. Test. The null hypothesis is H0: pA = pB. The pooled proportion is 450/4000 = 0.1125; the standard error is √(0.1125 · 0.8875 · (1/2000 + 1/2000)) ≈ 0.00999.
  5. z statistic. z = 0.025 / 0.00999 ≈ 2.50.
  6. p-value. Two-sided, p = 2 · P(Z > 2.50) ≈ 0.012.

Since p = 0.012 < 0.05, the null hypothesis is rejected at the 5% level: if the two models were the same, a difference this large would appear by chance only about 1.2% of the time. The confidence interval says more: the difference may be anywhere between 0.5 and 4.5 percentage points, so the increase may be real but small. A decision should also ask whether an effect of that size is worth its cost.

Definition 32.3 (p-value)

The probability, if the null hypothesis is true, of a result as extreme as the one observed or more extreme. A small p-value makes the data surprising under the null hypothesis; it is not the probability that the null hypothesis is true.

Common mistake

Saying "p = 0.012, so the probability that the new model is better is 98.8%". The p-value is not the probability of a hypothesis; computing the probability of hypotheses takes Bayesian inference and a prior. Also, running hundreds of comparisons on the same data and reporting only those with p < 0.05 (p-hacking, multiple testing) manufactures false findings: when none of 20 independent tests has a real effect, the probability that at least one comes out "significant" is 1 − 0.9520 ≈ 0.64.

32.7How is the course taught?

32.7.1A typical workflow

Askwhat do wewant to know?SamplerandomsampleModeldistributionassumptionEstimateparameter,intervalDecidetest, risk
Figure 32.1: A typical workflow in Probability and Statistics

An AI team asks whether a new recommendation model raises clicks. Half of the users see the new model at random (an A/B test), click rates are estimated, a confidence interval for the difference is computed, and if chance cannot explain the difference the model ships.

32.7.2Topics over the semester

  1. Counting, probability axioms, conditional probability
  2. Bayes' rule and independence
  3. Discrete distributions: Bernoulli, binomial, Poisson
  4. Continuous distributions: uniform, exponential, normal
  5. Expectation, variance and covariance
  6. Joint and conditional distributions
  7. Law of large numbers and central limit theorem
  8. Point estimation: method of moments, maximum likelihood
  9. Confidence intervals and the bootstrap
  10. Hypothesis testing: t-test, chi-square, p-values
  11. Linear regression and inference
  12. Bayesian inference: priors and posteriors

This is a typical semester; the order and coverage vary between universities.

32.7.3Skills you will gain

  • running tests with scipy.stats
  • regression in R or statsmodels
  • computing confidence intervals
  • checking probabilities by simulation
  • designing an A/B test

32.7.4Try it yourself

The Try It: Does the New Recommender Work? slide in the presentation lets you solve a typical problem of this course yourself: Does the new recommendation model raise the purchase rate? Half of the visitors see the old model (A), half the new one (B). Change the sample size and the true difference, and repeat the experiment.

32.8Are you ready for this course?

32.8.1Prerequisites

CourseWhy it is needed
Calculusintegrals and derivatives: continuous distributions and maximum likelihood
Discrete Mathematicssets and counting (permutations, combinations)

32.8.2Ask yourself

For every "no", the right-hand column shows where to start. If you can say "yes" to most of them, you are ready.

QuestionIf not, start with
Can you integrate a function to find the area under a curve?Definite integrals from calculus
Can you find the maximum of a function by taking its derivative?Derivatives and extreme values from calculus
Can you count selections with permutations and combinations?Counting from discrete mathematics
Can you compute the mean of a list in Python and plot its histogram?An intro programming course, then a short NumPy tutorial

32.9Neighboring courses

Artificial IntelligenceMachine LearningPattern RecognitionGraphical ModelsData MiningData ScienceTime SeriesInformation TheoryProbability & Statistics
subfieldbuilds onshares methodsapplication
Figure 32.2: Neighbors of Probability and Statistics and the kind of relation

32.9.1Where it overlaps

RelationCourseShared ground
builds onArtificial Intelligence builds on this coursereasoning under uncertainty, Bayes' rule
builds onMachine Learning builds on this coursegeneralization error, bias-variance, probabilistic models
builds onPattern Recognition builds on this courseBayesian decision theory, density estimation
builds onProbabilistic Graphical Models builds on this courseconditional independence, joint distribution
builds onData Mining builds on this coursesupport, confidence, significance
builds onData Science builds on this coursehypothesis testing, regression, visualization
builds onTime Series Analysis and Forecasting builds on this coursestationarity, autocorrelation, ARIMA
shares methodsShares methods with Information Theoryentropy, mutual information

32.9.2Where it differs

  • Machine Learning: ML puts predictive performance first; statistics asks about a model's meaning, assumptions and uncertainty.
  • Data Science: Data science covers the whole process (data, analysis, communication); this course gives the theory of inference behind it.
  • Probabilistic Graphical Models: Probabilistic graphical models structure multivariate distributions with graphs; this course starts with one or a few variables.
  • Information Theory: Information theory measures uncertainty with entropy; this course is built on estimation and decisions with probability.

32.10In practice

32.10.1Applications

AreaWhat is done
A/B testingWhether a new model is really better.
Naive BayesText and spam classification.
UncertaintyConfidence intervals and calibration of predictions.
Model comparisonIs the gap between two models significant?
Generative modelsLearning a data distribution and sampling it.
Medical testsSensitivity, specificity and base rate.

32.10.2Risks and ethics

RiskExplanation
p-hackingTrying many analysis choices and reporting only the "significant" one makes chance look like a finding.
Multiple testingAt the 0.05 level, a hundred comparisons yield about five false positives; without a correction, spurious findings appear.
Simpson's paradoxA trend can reverse when groups are combined; the 1973 Berkeley graduate admissions data is the well-known example.
Selection biasA non-random sample misleads however large it is, as the 1936 Literary Digest poll showed.

These issues are discussed in depth in Explainable AI and AI Ethics.

32.10.3Tools and datasets

Tools: R, SciPy (scipy.stats), statsmodels, pandas, PyMC, Stan.

Classic example problems: Monty Hall, Birthday paradox, Medical test and base rate, Galton's height data, A/B test, Gambler's fallacy.

32.11Common misconceptions

Common mistake

If p = 0.03, the hypothesis is 97% likely to be true.

The p-value is the probability of data this extreme if the null hypothesis holds; it is not the probability of the hypothesis.

Common mistake

Correlation implies causation.

A common cause or chance also produces correlation; causation needs an experiment.

Common mistake

If a test is 99% accurate, a positive means 99% disease.

If the disease is rare, most positives may be false alarms; Bayes' rule brings in the base rate.

Common mistake

With enough data, statistics is unnecessary.

In big data even trivial differences come out "significant"; effect size and bias still matter.

32.12Summary

  • Probability goes from process to outcomes, statistics from outcomes to process; estimation and testing account for the fact that a number computed from a sample varies at random.
  • Bayes' rule derives P(sick | positive) from P(positive | sick); for a rare disease most positive tests can be false alarms, because the base rate determines the result.
  • The expected value measures the center and the variance the spread; the standard error of the mean of n observations is σ/√n, and by the central limit theorem the mean is approximately normal.
  • A point estimate gives a single number; a confidence interval gives the uncertainty of the estimate, and a hypothesis test tells whether a difference is chance.
  • The p-value is not the probability of the null hypothesis; multiple testing and p-hacking manufacture false findings. The course is the foundation of machine learning, data science and probabilistic graphical models.

32.13Test Yourself

  1. A disease has a base rate of 2%, and the test has sensitivity 0.80 and specificity 0.90. What is the probability that a person who tests positive is sick?

    Answer

    Among 10,000 people there are 200 sick and 9,800 healthy. True positives: 200 · 0.80 = 160. False alarms: 9,800 · 0.10 = 980. P = 160 / (160 + 980) = 160/1140 ≈ 0.140. Even with high sensitivity, only about 14% of those who test positive are sick.

  2. For the sum S of two fair dice, what are E[S] and Var(S)? Use the fact that the variance of one die is 35/12.

    Answer

    Expectation is additive: E[S] = 3.5 + 3.5 = 7. Because the dice are independent, the variances add too: Var(S) = 35/12 + 35/12 = 35/6 ≈ 5.83.

  3. Five measurements: 4, 6, 5, 7, 8. Compute the mean, the sample standard deviation (denominator n − 1) and the standard error of the mean.

    Answer

    The mean is 30/5 = 6. The squared deviations are 4, 0, 1, 1, 4, summing to 10. The sample variance is 10/4 = 2.5 and the standard deviation ≈ 1.58. The standard error is 1.58/√5 ≈ 0.71.

  4. A coin shows heads 60 times in 100 tosses. Find the 95% confidence interval for the probability of heads and the z statistic for H0: p = 0.5. Is the coin biased?

    Answer

    For the interval, SE = √(0.6 · 0.4 / 100) ≈ 0.049; 0.6 ± 1.96 · 0.049 → about [0.504, 0.696]. For the test, the standard error under the null hypothesis is √(0.5 · 0.5 / 100) = 0.05; z = (0.6 − 0.5) / 0.05 = 2, two-sided p ≈ 0.046. The evidence is borderline: the null is rejected at the 5% level, but p is very close to 0.05 and the lower end of the interval is very close to 0.5. It is too early to call the coin biased from one experiment; it should be repeated.

  5. A paper reports "p = 0.03" and claims "the result is true with 97% probability". Why is this wrong?

    Answer

    The p-value is the probability of data this extreme when the null hypothesis is true, not the probability that the hypothesis is true. The probability of a hypothesis also needs a prior (Bayes' rule); for a hypothesis with a low prior, even p = 0.03 often does not make it true.

  6. A researcher compares 20 different features with the outcome in the same data set, running a test at the 0.05 level for each; in truth, no feature has any effect. How many "significant" results are expected, and what is the probability of at least one? What should be done?

    Answer

    The expected number is 20 · 0.05 = 1. The probability of at least one is 1 − 0.9520 ≈ 0.64. The number of tests should be declared in advance and a correction applied (for example Bonferroni: a threshold of 0.05/20 = 0.0025 per test); the finding should be confirmed on separate data.

32.14After this course

After this course, machine learning, probabilistic graphical models, pattern recognition and information theory become easier to approach. Bayesian statistics and causal inference are two natural next steps that treat uncertainty and cause and effect in more depth.

Courses that build on or extend this one: Artificial Intelligence, Machine Learning, Pattern Recognition, Probabilistic Graphical Models, Data Mining, Data Science, Time Series Analysis and Forecasting.

Related careers: Statistician, Data scientist, Machine learning researcher, Biostatistician, Actuary.

32.15Further reading

  • L. Wasserman, All of Statistics (2004): a short, dense account of probability and inference; its chapters on estimation and hypothesis testing deepen the second half of these notes.
  • M. DeGroot and M. Schervish, Probability and Statistics (4th ed., 2012): covers the topics of these notes at textbook level with many worked examples.
  • J. Blitzstein and J. Hwang, Introduction to Probability (2nd ed., 2019): presents ideas such as Bayes' rule and conditional probability with intuitive examples and plenty of exercises.

32.16References

  1. Wasserman, All of Statistics, Springer, 2004.
  2. DeGroot and Schervish, Probability and Statistics, 4th ed., Pearson, 2012.
  3. Blitzstein and Hwang, Introduction to Probability, 2nd ed., CRC Press, 2019.
  4. Gelman, Carlin, Stern, Dunson, Vehtari and Rubin, Bayesian Data Analysis, 3rd ed., CRC Press, 2013.

Related pages: Slides · Slides (PDF) · Course page