Learning from data: describing it, measuring uncertainty, and not fooling yourself.
From what data is to regression, the bootstrap and Bayesian inference. You learn to describe data with pictures and numbers, then probability and the distributions that model chance, how samples behave, and how to estimate and test with confidence intervals and p-values. Later modules cover regression, resampling, Bayesian thinking, and designing studies that answer the question you meant to ask. Graphs show every idea, you work problems on paper in every module, and you compute each statistic in small programs, so nothing is a black box.
What you’ll be able to do
Describe a data set with the right chart and the right numbers: centre, spread, shape and outliers.
Calculate probabilities, including conditional ones, and use Bayes' theorem.
Model chance with random variables and the binomial, Poisson and normal distributions.
Estimate with confidence intervals and test claims with hypothesis tests, and say what a p-value does and does not mean.
Fit and interpret linear and logistic regression, and check a model's assumptions.
Use simulation, the bootstrap and Bayesian methods, and design studies that avoid bias and confounding.
Modules
Data and variables· 13 slides
Seeing data: charts and distributions· 11 slides
The centre: mean, median and mode· 13 slides
Spread: range, variance and standard deviation· 13 slides
Two variables: scatter plots and correlation· 12 slides
Probability· 12 slides
Conditional probability and Bayes' theorem· 11 slides
Random variables and expected value· 12 slides
Binomial, geometric and Poisson· 13 slides
Continuous distributions and the normal curve· 11 slides
Sampling and the central limit theorem· 11 slides
Estimating: confidence intervals· 13 slides
Hypothesis tests and p-values· 14 slides
Comparing groups: t-tests, chi-squared and ANOVA· 13 slides
Linear regression· 12 slides
Multiple and logistic regression· 13 slides
Simulation, the bootstrap and permutation tests· 12 slides
Bayesian statistics· 13 slides
Designing studies: experiments, causation and pitfalls· 11 slides
Modelling like an expert· 13 slides
Interactive parts (exercises, code to run, walkthroughs, flashcards, checklists) are drawn still and marked “Interactive · disabled in the PDF”. Do them in the app; the answers are at the end.
Module 1: Data and variables
Statistics1 / 246
Module 1 · Data and variables
Data is a set of observations of variables
Statistics is the craft of learning from data while keeping track of how sure you can be. Data is a record of things you looked at. Each thing you looked at, a person, a shop order, a day of weather, is an observation (also called a case or a unit). Each property you wrote down about it, an age, a price, a temperature, is a variable: it varies from one observation to the next.
Name
Age (years)
Height (cm)
Travels by
Siblings
Coffee rating
Ana
19
164.2
bus
2
good
Ben
22
181.0
bike
0
poor
Chloe
20
170.5
walk
1
excellent
Dev
21
175.8
bus
3
good
Ema
19
158.9
car
1
fair
This little survey of a class has 5 observations (the rows) and 6 variables (the columns). Statisticians write the number of observations as , so here . You will meet this class again throughout the module.
Observation
One thing you recorded: a person, an order, a day. A row of the table.
Variable
A property recorded for every observation: age, price. A column.
Value
What one variable is for one observation: Ben’s age is 22.
Data set
All the values together, usually as a table.
Statistics2 / 246
Module 1 · Data and variables
Variables are categories or numbers
The first question to ask of any variable is what kind it is, because the kind decides which charts and which numbers make sense. A categorical variable puts each observation in a group: how someone travels (bus, bike, walk, car), a blood type, a colour. A numerical (or quantitative) variable is a measured or counted amount: a height, a number of siblings. A useful test: does it make sense to add two values, or take their average? The average height of the class means something; the average of “bus” and “bike” does not.
Variable
Categoricalgroups
Nominalno order: bus, bike
Ordinalordered: poor < good
Numericalamounts
Discretecounts: 0, 1, 2
Continuousmeasures: 170.5 cm
The kinds of variable. Each one allows different summaries.
QuizInteractive · disabled in the PDF
In the class survey, which variables are categorical?
In the class survey, which variables are categorical?
ProblemInteractive · disabled in the PDF
A café records 8 orders. For each order it writes down the drink (tea, coffee or juice), the cup size (small, medium or large), the price in dollars and the number of items bought. How many observations are there, how many variables, and how many of the variables are categorical?
Statistics3 / 246
Module 1 · Data and variables
Counts are discrete, measurements are continuous
Numerical variables come in two kinds. A discrete variable takes separate values with gaps between them, usually counts: 0, 1, 2 or 3 siblings, never 1.5. A continuous variable can take any value in a range: a height could be 170.5 cm, 170.52 cm or 170.523 cm, limited only by how finely you measure. Rounding a continuous variable to whole centimetres does not make it discrete; the thing itself is still continuous.
Variable
Kind
Why
Number of siblings
Discrete
A count: whole numbers only
Goals in a match
Discrete
A count
Height
Continuous
Any value in a range
Time to run 100 m
Continuous
A measurement
Age in whole years
Discrete, as recorded
Rounded from a continuous age
QuizInteractive · disabled in the PDF
Which of these is a continuous variable?
Which of these is a continuous variable?
Going deeper
Age is a good example of how the line blurs. True age is continuous, but recorded in whole years it behaves like a discrete variable with many values. In practice, a discrete variable with many possible values (incomes in cents, ages in years) is usually treated as continuous, and that works well. The distinction matters most for small counts, such as 0 to 5 siblings, where a bar for each value is the natural picture.
Statistics4 / 246
Module 1 · Data and variables
Ordered categories and numbers that are only labels
An ordinal variable is categorical with a natural order: poor < fair < good < excellent, or school year 1, 2, 3. You can say which is higher, but not by how much: is “good” to “excellent” the same step as “poor” to “fair”? Nobody measured it. A nominal variable has no order at all: bus, bike, walk, car.
Watch out for numbers that are only names. A postcode, a phone number, a football shirt number or a product code is written in digits but is nominal: the average shirt number of a team is a number with no meaning. Data sets often store categories as codes (1 = bus, 2 = bike), and a computer will happily average them if you ask.
Averaging a rating scale. Surveys often code “strongly disagree … strongly agree” as 1 to 5 and report the mean. It is common and can be useful, but it assumes the steps are equal. Reporting how many people chose each answer is always honest; a mean of 3.4 hides whether everyone was lukewarm or opinion was split.
QuizInteractive · disabled in the PDF
A team’s shirt numbers are 1, 4, 7, 9, 10 and 23. What kind of variable is the shirt number?
A team’s shirt numbers are 1, 4, 7, 9, 10 and 23. What kind of variable is the shirt number?
Statistics5 / 246
Module 1 · Data and variables
You study a sample to learn about a population
The population is every observation you want to know about: all the students in a country, every bottle a factory fills this year. You can rarely look at all of it, so you look at a sample, a part of it, and reason from the sample to the population. A number that describes a population, such as the true average height of all students, is a parameter; it is fixed but usually unknown. A number worked out from a sample is a statistic; it changes from sample to sample.
The population is too big to measure in full.
Pick some of it. How you pick matters a lot (a later module).
Calculate a number from the sample.
Use it as an estimate of the population’s number, with some uncertainty.
Inference runs the other way from sampling: from what you saw back to what you want to know.A small for the sample, a capital for the population.
QuizInteractive · disabled in the PDF
A poll asks 1000 voters and finds 52% plan to vote yes. In the language of statistics, the 52% is…
A poll asks 1000 voters and finds 52% plan to vote yes. In the language of statistics, the 52% is…
Statistics6 / 246
Module 1 · Data and variables
The C++ this course uses
This course computes each statistic in small C++ programs, as Algebra does, so nothing is a black box. Here is all the C++ it needs, in one program. Run it, then change the waits.
PlaygroundInteractive · disabled in the PDF
C++
1#include<cmath>2#include<iostream>3#include<vector>45doublelargest(const std::vector<double>& values){6double best = values[0];7for(double v : values){ // each value in turn8if(v > best) best = v;9}10return best;11}1213intmain(){14 std::vector<double> waits ={3,4,5,5,8};15int n = waits.size();16bool longWait =largest(waits)>6;17 std::cout <<"n = "<< n <<", largest = "<<largest(waits)<<"\n";18if(longWait) std::cout <<"someone waited long\n";19 std::cout <<"7 / 2 = "<<7/2<<", 7.0 / 2 = "<<7.0/2<<"\n";20 std::cout <<"sqrt(2) = "<< std::sqrt(2.0)<<"\n";21 std::cout <<"2 to the 10th = "<< std::pow(2,10)<<"\n";22for(int i =0; i < n; i++) std::cout << waits[i]-5<<" ";23 std::cout <<"\n";24return0;25}
A whole program: main runs, std::cout << x prints. The exercises are functions only, like largest.
Every value has a type: int (whole numbers), double (decimals), bool (true or false). std::vector<double> is a list of doubles: v.size() is its length and v[i] the value at index i, counting from 0.
A function says what it returns, then what it is given: double largest(const std::vector<double>& values). The const …& reads the caller’s list without copying or changing it.
for (double v : values) visits each value; for (int i = 0; i < n; i++) counts with an index. if (…) decides.
#include <cmath> brings std::sqrt, std::pow, std::exp, std::log and std::abs. A struct groups named values: a row of a table, or a function’s two answers.
A function can be handed to another as a std::function<double(double)>, and a lambda, [](double x) { return x * x; }, writes one in place.
Two traps in statistics code. Whole numbers divide to a whole number: 7 / 2 is 3, and a share like count / n with two ints is 0 whenever count < n. Make one side a double first: double(count) / n. And ^ is not a power in C++ (2 ^ 3 is 1): square with x * x or std::pow(x, 2).
Statistics7 / 246
Module 1 · Data and variables
A tidy table has one row per observation
Data is easiest to work with in a tidy shape: each row is one observation, each column is one variable, and each cell holds one value. Spreadsheets drift away from this: a column per year, two values in one cell, totals mixed in with the rows. Tidy data is what every tool, and every program in this course, expects.
Untidy
Columns “2023” and “2024” hold the same variable, sales
A cell says “170 cm / 65 kg”: two variables in one
A “Total” row that is not an observation
Tidy
Columns: shop, year, sales; one row per shop and year
Separate height and mass columns, units in the header
Totals are calculated, not stored as rows
In code, a tidy table is a list of records: a std::vector of structs, one per observation, with the same fields. That is how the class survey looks in C++.
C++
1structStudent{2 std::string name;3int age;4double heightCm;5 std::string travel; // "bus", "bike", "walk" or "car"6int siblings;7};89std::vector<Student> students ={10{"Ana",19,164.2,"bus",2},11{"Ben",22,181.0,"bike",0},12{"Chloe",20,170.5,"walk",1}};1314std::vector<double>heightsOf(const std::vector<Student>& rows){15 std::vector<double> heights; // one column16for(constStudent& s : rows) heights.push_back(s.heightCm);17return heights;18}
The struct lists the variables; each {…} is a row. The loop pulls out one column.
QuizInteractive · disabled in the PDF
A table of exam results has the columns Student, Maths, Physics, Chemistry, with one mark per cell. To make it tidy for “mark by subject”, which columns should it have?
A table of exam results has the columns Student, Maths, Physics, Chemistry, with one mark per cell. To make it tidy for “mark by subject”, which columns should it have?
Statistics8 / 246
Module 1 · Data and variables
Every measurement has error
No measurement is perfect. Random error scatters readings around the true value, some too high and some too low: a shaky hand, a rounding, a noisy sensor. Averaging several readings shrinks it. Systematic error, or bias, pushes every reading the same way: a scale that reads 2 kg heavy, shoes left on for a height. Averaging does nothing for bias. In the words of measurement, low random error is precision and low bias is accuracy.
True height
Average of the readings
Average minus true (cm)0.08
Five readings of someone whose true height is 170 cm. Drag the bias and the spread: averaging cancels the spread, never the bias.
QuizInteractive · disabled in the PDF
A kitchen scale always reads 15 g too heavy. You weigh a bag of flour 10 times and average the readings. What happens to the 15 g?
A kitchen scale always reads 15 g too heavy. You weigh a bag of flour 10 times and average the readings. What happens to the 15 g?
Statistics9 / 246
Module 1 · Data and variables
Where data comes from shapes what it can tell you
Before trusting a number, ask how it was collected. In an observational study you record what happens without changing anything. A survey is one kind: you ask people questions. In an experiment you deliberately change something, such as giving half the plants a fertiliser, and compare. Logs are records a system writes as it runs: website visits, card payments, sensor readings. They are huge and cheap, but nobody designed them to answer your question.
Source
Example
Strength
Watch out for
Survey
Ask 500 shoppers about prices
Asks exactly what you want
Who answers; how it is worded
Observational
Record which patients take a drug
Real life, often large
Other differences between groups
Experiment
Randomly give half the plants fertiliser
Can show cause and effect
Cost; may be unethical
Logs
Every page view on a website
Huge, automatic
Only covers who used the system
QuizInteractive · disabled in the PDF
A school wants to know if a new reading app improves reading scores. Which design lets it say the app caused any change?
A school wants to know if a new reading app improves reading scores. Which design lets it say the app caused any change?
Statistics10 / 246
Module 1 · Data and variables
A first look at a data set
Faced with a new data set, look before you calculate. How many observations? Which variables, of which kinds? Are any values missing (an empty cell: in C++, a std::optional<double> holding std::nullopt, nothing, instead of a number) or impossible (a height of 1700 cm, a typing slip)? For a categorical variable, count how many observations fall in each group. Those counts are its frequencies, and they are the first picture of it.
How 20 students in the class travel. Counting is the first summary of a categorical variable.
Run it. 1755 looks like 175.5 typed without the point. !h means “no value”, and *h reads the number inside. A std::map counts by name, in alphabetical order.
ProblemInteractive · disabled in the PDF
Fifteen students say how they travel to school: bus, walk, bus, car, bike, bus, walk, bus, bike, car, bus, walk, bus, bike, walk. Find the frequency of “bus” and of “walk”, and the share of the students who travel by bus, as a percentage.
%
Statistics11 / 246
Module 1 · Data and variables
Try it: count and check a column
Two small programs that every analysis starts with: counting the groups of a categorical variable, and finding the missing values of a numerical one.
Code challengeInteractive · disabled in the PDF
Finish frequencies(values): return a std::map whose keys are the distinct values and whose values are how many times each appears.
Finish cleanHeights(heights): return a new vector without the missing values (std::nullopt) and without any height outside 50 to 250 cm (inclusive), keeping the order.
A column of 10 heights, in cm, reads: 172.4, missing, 165.0, 1680, 158.2, 181.5, missing, 17.3, 169.9, 175.0. Any height outside 50 to 250 cm is impossible. How many values are missing, how many are impossible, and how many usable heights are left?
ProblemInteractive · disabled in the PDF
A farm scale is known to read 2 kg too heavy. A sack is weighed five times: 27.1, 26.8, 27.3, 26.9 and 26.9 kg. What is the average of the readings, and what is your best estimate of the sack’s true mass?
kg
kg
ProblemInteractive · disabled in the PDF
A spreadsheet has one row for each of 6 shops, and four columns, 2021, 2022, 2023 and 2024, holding each shop’s sales that year. You make it tidy, with the columns shop, year and sales. How many rows does the tidy table have, and how many columns?
ProblemInteractive · disabled in the PDF
A town has 24 000 voters. A poll asks 600 of them, chosen at random, and 255 say they will vote yes. What is the sample size ? What percentage of the population did the poll ask? What percentage of the sample says yes?
%
%
Statistics13 / 246
Module 1 · Data and variables
Recap
Data is observations (rows) of variables (columns); is the number of observations.
Categorical variables are nominal (no order) or ordinal (ordered); numerical ones are discrete (counts) or continuous (measurements).
Digits can be labels: postcodes and shirt numbers are nominal.
A sample is studied to learn about a population; statistics estimate parameters.
Tidy data: one observation per row, one variable per column, one value per cell.
Random error averages away; bias does not.
How data was collected, survey, observation, experiment or logs, limits what it can show.
First look: count, find missing and impossible values, before any calculation.
FlashcardsInteractive · disabled in the PDF
Observation
One thing recorded: a row of the table.
Variable
A property recorded for each observation: a column.
Nominal
Categories with no order: bus, bike, walk.
Ordinal
Categories with an order but no measured gaps: poor < fair < good.
Discrete
Numerical values with gaps between them, usually counts.
Continuous
Numerical values anywhere in a range: measurements.
Population vs sample
Everything you want to know about, vs the part you looked at.
Parameter vs statistic
A number about the population (unknown) vs one from the sample.
Bias
Systematic error: every reading pushed the same way. Averaging does not remove it.
Tidy data
One row per observation, one column per variable, one value per cell.
Module 2: Seeing data: charts and distributions
Statistics14 / 246
Module 2 · Seeing data: charts and distributions
A frequency table counts each value
The distribution of a variable says which values it takes and how often. The simplest way to write it down is a frequency table: each value or group, and its frequency, the number of observations with it. Dividing by the total gives the relative frequency, the share of the data, which lets you compare groups of different sizes. For an ordered variable, the cumulative frequency adds up the counts so far.
Coffee rating
Frequency
Relative frequency
Cumulative frequency
poor
2
0.10
2
fair
5
0.25
7
good
9
0.45
16
excellent
4
0.20
20
Total
20
1.00
Relative frequencies always add up to 1 (or 100%).
QuizInteractive · disabled in the PDF
Using the table, what share of the 20 students rated the coffee “fair” or worse?
Using the table, what share of the 20 students rated the coffee “fair” or worse?
ProblemInteractive · disabled in the PDF
25 people rate a film: 3 say poor, 6 fair, 11 good and 5 excellent. Find the relative frequency of “good” (as a decimal), the cumulative frequency at “good”, and the share of the people who rated the film “good” or worse (as a decimal).
Statistics15 / 246
Module 2 · Seeing data: charts and distributions
Bar charts show categorical data
A bar chart draws one bar per category, its height the frequency (or relative frequency). The bars have gaps between them, because the categories are separate things. For a nominal variable, sort the bars by height so the eye can rank them; for an ordinal one, keep the natural order.
The coffee ratings: an ordinal variable, so the bars keep their order rather than being sorted.
Pie charts. A pie chart shows the same shares as angles. People judge lengths far better than angles or areas, so two slices of 23% and 27% are hard to tell apart, while two bars are easy. Use a pie only for two or three parts of a whole, if at all.
QuizInteractive · disabled in the PDF
You chart the favourite fruit of 200 people: apple, banana, cherry, mango. How should the bars be arranged?
You chart the favourite fruit of 200 people: apple, banana, cherry, mango. How should the bars be arranged?
Statistics16 / 246
Module 2 · Seeing data: charts and distributions
Histograms show numerical data in bins
A continuous variable has too many different values for a bar each. A histogram splits the number line into equal intervals called bins, counts the observations in each, and draws touching bars, because the bins cover the line with no gaps. A value on a boundary must go in exactly one bin; the usual rule is that a bin includes its left edge and not its right, written .
How long 30 people take to get to work, in bins of 10 minutes. The tallest bar is 10 to 20 minutes; a few people take much longer.
Bar chart
Categorical variable
Gaps between bars
Order: by height or the natural order
Histogram
Numerical variable
Bars touch: the bins cover the line
Order: the number line, always
QuizInteractive · disabled in the PDF
With bins , , , which bin holds a commute of exactly 20 minutes?
With bins , , , which bin holds a commute of exactly 20 minutes?
ProblemInteractive · disabled in the PDF
Twelve deliveries took these times, in minutes: 8, 12, 15, 20, 21, 9, 30, 18, 25, 10, 14, 29. How many fall in each of the bins , , and ?
Statistics17 / 246
Module 2 · Seeing data: charts and distributions
The bin width changes the story
The same 30 commutes, with bins of 5 and of 20 minutes. Bins that are too narrow give a jagged picture where every bump is noise; bins that are too wide hide the shape, here the long tail of slow commutes. There is no single right width: try a few and pick one that shows the shape without the noise. Rules of thumb exist, such as about bins (about 5 or 6 for 30 values), as a starting point.
Bins of 5 minutes: more detail, but the gap at 45–50 is just chance with only 30 values.Bins of 20 minutes: smooth, but you can no longer see where the peak is or how far the tail goes.
QuizInteractive · disabled in the PDF
You draw a histogram of 40 exam marks with 40 bins. What is the most likely problem?
You draw a histogram of 40 exam marks with 40 bins. What is the most likely problem?
Statistics18 / 246
Module 2 · Seeing data: charts and distributions
Dot plots and stem-and-leaf plots keep every value
For a small data set you can draw every value. A dot plot puts one dot per observation above a number line, stacking equal values. A stem-and-leaf plot splits each number into a stem (the leading digits) and a leaf (the last digit), and writes the leaves beside their stem. Turned on its side, it is a histogram that still shows the exact numbers.
Six students have 0 siblings. In the stem-and-leaf plot, the row “6 | 1 4 7 7” is the marks 61, 64, 67, 67.
QuizInteractive · disabled in the PDF
In the stem-and-leaf plot of exam marks, how many students scored 80 or more?
In the stem-and-leaf plot of exam marks, how many students scored 80 or more?
Statistics19 / 246
Module 2 · Seeing data: charts and distributions
Shape: symmetric, skewed or bimodal
Look at a histogram from far away and describe its shape. Symmetric: the two sides are near mirror images, as with adult heights. Skewed right (positively skewed): a long tail to the right, as with incomes, house prices and the commute times, where most values are modest and a few are very large. Skewed left: the long tail is on the left, as with marks on an easy test. A peak is a mode; a bimodal shape has two, which often means two groups are mixed together.
Distribution
A smooth outline of a distribution with mean 5. Drag k: small k is strongly skewed right, large k is nearly symmetric.
Mixture
Group A
Group B
Two equal groups mixed, such as heights of two age groups. Drag the gap: two peaks appear once the centres are more than 2 units apart.
QuizInteractive · disabled in the PDF
Most people in a town earn between 20 000 and 50 000 a year, and a handful earn several million. The histogram of incomes is…
Most people in a town earn between 20 000 and 50 000 a year, and a handful earn several million. The histogram of incomes is…
Statistics20 / 246
Module 2 · Seeing data: charts and distributions
A box plot draws five numbers
A box plot (box-and-whisker plot) summarises a numerical variable with five numbers. Sort the data. The median is the middle value. The lower quartile is the middle of the lower half, and the upper quartile is the middle of the upper half. The box runs from to , so it holds the middle half of the data, with a line at the median. The whiskers reach out to the smallest and largest values that are not unusually far away; values beyond them are drawn as single points. The next modules define these numbers exactly.
Median
The 30 commutes: minimum 4, Q1 12, median 17.5, Q3 27, and two very long commutes, 51 and 58, drawn as points.
QuizInteractive · disabled in the PDF
Roughly what share of the commutes are between 12 and 27 minutes, the two ends of the box?
Roughly what share of the commutes are between 12 and 27 minutes, the two ends of the box?
Going deeper
Box plots shine when comparing groups: put several side by side on one axis, one per group, and the medians, spreads and skews line up for the eye. Their weakness is that five numbers cannot show two peaks. A bimodal distribution and a flat one can have the same box plot, so look at a histogram too.
Statistics21 / 246
Module 2 · Seeing data: charts and distributions
Charts can mislead
A chart is an argument, and it can be a dishonest one. The most common trick is a truncated axis: two bars of 50 and 52, drawn on an axis that starts at 49, look as if one is three times the other. Bar lengths are only honest when the axis starts at 0. Other tricks: pictures scaled in two directions (doubling a coin’s width and height quadruples its area), uneven bins or time steps, a 3D tilt that makes near slices look bigger, and two y-axes chosen so any two lines cross where you like.
Trick
What it does
What to ask
Axis not at 0
Small differences look huge
Where does the axis start?
Area for one number
Doubling looks like ×4
Is length or area the value?
Cherry-picked range
Shows only the years that fit
What happens just outside it?
Uneven bins
Wide bins look like big groups
Are the bins the same width?
Two y-axes
Lines cross wherever you like
Would the story survive one axis?
QuizInteractive · disabled in the PDF
An advert’s bar chart shows two brands at 50% and 52%, with the y-axis running from 49% to 53%. How many times taller is the second bar drawn than the first?
An advert’s bar chart shows two brands at 50% and 52%, with the y-axis running from 49% to 53%. How many times taller is the second bar drawn than the first?
Statistics22 / 246
Module 2 · Seeing data: charts and distributions
Try it: count values into bins
Put in orderInteractive · disabled in the PDF
Put the steps of drawing a histogram by hand in order.
1.Check that the counts add up to n
2.Count the values in each bin, edges going to the bin on their right
3.Find the smallest and largest values
4.Choose a bin width and the first bin’s left edge
5.Draw touching bars, one per bin
Code challengeInteractive · disabled in the PDF
Finish binCounts(values, start, width, bins): return a vector of bins counts, where bin i holds the values v with start + i * width <= v < start + (i + 1) * width. Values outside every bin are ignored.
C++
1#include<cmath>2#include<vector>34std::vector<int>binCounts(const std::vector<double>& values,5double start,double width,int bins){6 std::vector<int>counts(bins,0);7 // TODO: put each value in its bin8return counts;9}
Code challengeInteractive · disabled in the PDF
Finish relativeFrequencies(counts): return each count divided by the total of all the counts. If the total is 0, return all zeros.
C++
1#include<vector>23std::vector<double>relativeFrequencies(4const std::vector<int>& counts){5 std::vector<double>shares(counts.size(),0.0);6 // TODO: divide each count by the total7return shares;8}
Statistics23 / 246
Module 2 · Seeing data: charts and distributions
Practice problems
ProblemInteractive · disabled in the PDF
A stem-and-leaf plot of 15 test marks (key: 6 | 3 means 63) has these rows: 4 | 7 9, 5 | 2 5 8, 6 | 0 3 3 6 9, 7 | 1 4 8 and 8 | 2 5. How many marks are in the 60s, how many are 70 or more, and what is the median mark?
ProblemInteractive · disabled in the PDF
A bar chart shows this year’s sales, 126, beside last year’s, 120. Its y-axis starts at 110. How many times taller is this year’s bar drawn, and what is the true ratio of the two sales figures?
ProblemInteractive · disabled in the PDF
A box plot of 200 commute times has , median 22 and minutes. About how many of the commutes are under 14 minutes, how many are between 14 and 35 minutes, and how many are over 22 minutes?
ProblemInteractive · disabled in the PDF
A poster shows sales growing by 50% by drawing this year’s coin 1.5 times as wide and 1.5 times as tall as last year’s. How many times bigger does the new coin’s area look? By what factor should the width and the height have been scaled, so that the area grew by exactly 50%?
Statistics24 / 246
Module 2 · Seeing data: charts and distributions
Recap
A distribution is the values a variable takes and how often; a frequency table writes it down.
Relative frequency is frequency divided by ; cumulative frequency adds up counts in order.
Bar charts are for categories (gaps); histograms are for numbers in bins (touching bars).
The bin width changes the picture: try a few.
Dot plots and stem-and-leaf plots keep every value of a small data set.
Describe shape: symmetric, skewed right or left (named after the tail), unimodal or bimodal.
A box plot shows minimum, , median, and maximum; the box holds the middle half.
Check every chart’s axes: bars must start at 0.
FlashcardsInteractive · disabled in the PDF
Distribution
Which values a variable takes, and how often.
Relative frequency
A frequency divided by the total: a share of the data.
Histogram
Touching bars over equal bins of a numerical variable.
Bin
An interval of the number line, usually including its left edge: [10, 20).
Skewed right
A long tail towards large values: incomes, waiting times.
Bimodal
Two peaks; often two groups mixed in one data set.
Box plot
Five numbers: minimum, lower quartile, median, upper quartile, maximum.
Truncated axis
An axis not starting at 0, which makes small differences in bars look big.
Module 3: The centre: mean, median and mode
Statistics25 / 246
Module 3 · The centre: mean, median and mode
What is a typical value
Asked “how long do people wait at this café?”, you want one number that stands for all the waits: a measure of centre, or average. There are three in everyday use, and they answer slightly different questions. The mean shares the total out equally. The median is the middle value. The mode is the most common value. On tidy, symmetric data they agree; on skewed data they can be far apart, and choosing the wrong one tells a misleading story.
Measure
Question it answers
For the waits 3, 4, 5, 5, 8 minutes
Mean
If everyone waited the same, how long?
25 ÷ 5 = 5
Median
What is the middle wait?
5
Mode
What is the most common wait?
5
Measure of centre
One number that stands for the typical value of a variable.
Mean
The sum of the values divided by how many there are.
Median
The middle value once the data is sorted.
Mode
The value that appears most often.
Statistics26 / 246
Module 3 · The centre: mean, median and mode
The mean shares the total out equally
Call the values . The sample mean, written and read “x bar”, adds them all up and divides by . The symbol (capital sigma) means “add up”: is . The mean of a whole population is written (the Greek letter mu).
The café waits. The mean has the same units as the data.
QuizInteractive · disabled in the PDF
Four parcels have a mean mass of 2 kg. A fifth parcel of 7 kg is added. What is the new mean?
Four parcels have a mean mass of 2 kg. A fifth parcel of 7 kg is added. What is the new mean?
ProblemInteractive · disabled in the PDF
Five quiz scores have a mean of 72. Four of them are 65, 80, 70 and 74. What is the fifth?
Code challengeInteractive · disabled in the PDF
Finish mean(values): return the sum of the values divided by how many there are.
C++
1#include<vector>23doublemean(const std::vector<double>& values){4double sum =0;5 // TODO: add up the values6return sum;7}
Statistics27 / 246
Module 3 · The centre: mean, median and mode
The mean is the balance point
Put equal weights on a ruler at each value. The mean is where the ruler balances. In numbers: the deviations , how far each value is from the mean, always add up to exactly zero. The values above the mean pull as hard as the values below. Drag the pivot and watch the sum of deviations: it is zero only at the mean.
Sum of (value − c)10
The values 2, 3, 5, 6 and 9. Drag the pivot c until the sum of the deviations is 0.Why it is always zero: the sum of the values is , by the definition of the mean.
Statistics28 / 246
Module 3 · The centre: mean, median and mode
The median is the middle value
To find the median, sort the values from smallest to largest. With an odd number of values, the median is the one in the middle, at position . With an even number, there are two middle values, and the median is their mean. Half the data is at or below the median and half at or above it.
Adding a wait of 11 minutes moves the mean from 5 to 6, but not the median.
QuizInteractive · disabled in the PDF
What is the median of 12, 7, 3, 9, 15, 4?
What is the median of 12, 7, 3, 9, 15, 4?
ProblemInteractive · disabled in the PDF
Find the median of 14, 3, 9, 21, 6, 11, 8, 17. Then a ninth value, 2, is added: what is the median now?
Statistics29 / 246
Module 3 · The centre: mean, median and mode
Computing the median in code
Find the bugInteractive · disabled in the PDF
This median of whole numbers works for {3, 5, 4}, but returns 8 for {10, 9, 2, 8} instead of 8.5, and 1 for {1, 2} instead of 1.5. Which line is wrong?
C++
Code challengeInteractive · disabled in the PDF
Finish median(values): sort a copy of the values, then return the middle one, or the mean of the two middle ones when there is an even number. Do not change the vector you are given.
C++
1#include<algorithm>2#include<vector>34doublemedian(const std::vector<double>& values){5 // TODO: sort a copy, then find the middle6return values[0];7}
Statistics30 / 246
Module 3 · The centre: mean, median and mode
The mode is the most common value
The mode is the value that appears most often. It is the only measure of centre for a nominal variable: there is no mean or median of “bus, bike, walk”, but the most common way to travel is a fine summary. A data set can have two modes (bimodal) or more, or none worth naming if every value appears once. For continuous data, where values rarely repeat exactly, the mode means the highest bar of the histogram.
QuizInteractive · disabled in the PDF
A shoe shop wants to know which size to reorder most of. Last month it sold sizes 38, 39, 39, 40, 41, 41, 41, 42, 44, 46. Which measure answers its question, and what is it?
A shoe shop wants to know which size to reorder most of. Last month it sold sizes 38, 39, 39, 40, 41, 41, 41, 42, 44, 46. Which measure answers its question, and what is it?
Statistics31 / 246
Module 3 · The centre: mean, median and mode
One extreme value drags the mean
A small firm pays its seven staff 25, 27, 28, 30, 32 and 35 thousand a year, and its owner 200 thousand. The mean salary is thousand: more than six of the seven people earn. The median is 30 thousand, which describes a typical member of staff well. The mean uses every value’s size, so one huge value pulls it; the median uses only the order, so it barely notices. A measure that an extreme value cannot move much is called resistant (or robust).
Mean4.8
Median5
The values 2, 3, 5, 6 and one more, v. Drag v far to the right: the mean follows it, the median stops at 5.
QuizInteractive · disabled in the PDF
A data set of nine heights has median 171 cm and mean 172 cm. One height of 180 cm was mistyped as 1800 cm. Which measure is badly wrong?
A data set of nine heights has median 171 cm and mean 172 cm. One height of 180 cm was mistyped as 1800 cm. Which measure is badly wrong?
Going deeper
There is a precise sense in which each measure is “closest” to the data. The mean is the number that makes the sum of squared distances as small as possible; the median makes the sum of plain distances as small as possible; and the mode makes the number of values not equal to as small as possible. Squaring makes large distances count enormously, which is exactly why one outlier drags the mean. This idea of “the value that minimises a loss” returns in regression and in machine learning.
Statistics32 / 246
Module 3 · The centre: mean, median and mode
Skew pulls the mean towards the tail
In a symmetric distribution the mean and the median are about the same. In a skewed one, the values in the long tail pull the mean towards the tail, while the median stays with the bulk. So for data skewed right, as incomes, house prices and waiting times usually are, the mean is above the median; skewed left, it is below. Comparing the two is a quick test of skew.
Distribution
A right-skewed distribution: the mode (1) at the peak, then the median (about 1.68), then the mean (2), pulled out by the tail.
QuizInteractive · disabled in the PDF
A news report says the mean house price in a city is 450 000 and the median is 310 000. What does that suggest?
A news report says the mean house price in a city is 450 000 and the median is 310 000. What does that suggest?
Statistics33 / 246
Module 3 · The centre: mean, median and mode
A weighted mean lets some values count more
Sometimes values should not count equally. A course grade where homework is worth 20%, a midterm 30% and a final 50% gives each mark a weight . The weighted mean multiplies each value by its weight, adds up, and divides by the total weight. The plain mean is the special case where every weight is 1.
Marks of 90, 70 and 80. The plain mean would say 80, but the 70 is worth more than the 90.
The mean of means. Class A has 10 students with mean mark 70, and class B has 30 students with mean mark 80. The mean of all 40 students is not : weight each class by its size, . Averaging averages without weights is one of the most common mistakes in reports.
Code challengeInteractive · disabled in the PDF
Finish weightedMean(values, weights): multiply each value by the weight at the same index, add those up, and divide by the sum of the weights.
C++
1#include<vector>23doubleweightedMean(const std::vector<double>& values,4const std::vector<double>& weights){5 // TODO: two running totals6return0;7}
Statistics34 / 246
Module 3 · The centre: mean, median and mode
A trimmed mean drops the extremes
A trimmed mean sorts the data, removes the same number of values from each end, and takes the mean of the rest. A 20% trimmed mean of 10 values drops the 2 smallest and the 2 largest. It sits between the mean (trim nothing) and the median (trim everything but the middle): it uses most of the data but resists outliers. Judges’ scores in diving and gymnastics drop the highest and lowest for exactly this reason.
The 40 lifts the mean above every value but one; the trimmed mean ignores it.
Fill the blanksInteractive · disabled in the PDF
Finish trimmedMean, which drops k values from each end of the sorted data.
C++
1doubletrimmedMean(std::vector<double> values,int k){2 std::sort(values., values.end());3 std::vector<double>kept(values.begin()+,4 values.end()-);5double sum =0;6for(double v : kept) sum += v;7return sum / kept.;8}
Statistics35 / 246
Module 3 · The centre: mean, median and mode
Choosing a measure of centre
Data
Use
Because
Nominal (travel mode, colour)
Mode
No order, no arithmetic
Ordinal (ratings)
Median (or mode)
Order but no measured gaps
Numerical, roughly symmetric
Mean
Uses every value; fine without outliers
Numerical, skewed or with outliers
Median
Resists the tail
When totals matter (budgets, rainfall)
Mean
Mean × n is the total
Tip. When in doubt, report both the mean and the median. If they are close, the data is roughly symmetric; if they differ, the gap itself is worth reporting.
QuizInteractive · disabled in the PDF
A city plans water supply and needs to know how much water its 100 000 homes use in total. Which average of household use is the one to multiply by 100 000?
A city plans water supply and needs to know how much water its 100 000 homes use in total. Which average of household use is the one to multiply by 100 000?
Statistics36 / 246
Module 3 · The centre: mean, median and mode
Practice problems
ProblemInteractive · disabled in the PDF
A team scored these numbers of goals in 10 matches: 2, 0, 3, 1, 12, 2, 4, 1, 3, 2. Find the mean, the median and the mode.
ProblemInteractive · disabled in the PDF
A course counts homework 25%, a project 25% and the final exam 50%. A student scores 88 on homework, 72 on the project and 65 on the final. What is the course grade? What final-exam mark would have given a grade of exactly 75?
ProblemInteractive · disabled in the PDF
One class of 12 students has a mean mark of 68; another class of 18 students has a mean of 78. What is the mean mark of all 30 students together?
ProblemInteractive · disabled in the PDF
Ten delivery times, in minutes: 12, 15, 9, 14, 48, 13, 16, 11, 14, 38. Find the mean, the median and the 20% trimmed mean.
min
min
min
Statistics37 / 246
Module 3 · The centre: mean, median and mode
Recap
The mean shares the total equally; deviations from it add up to 0.
The median is the middle of the sorted data, or the mean of the two middle values.
The mode is the most common value, and the only centre for nominal data.
Outliers and skew drag the mean towards the tail; the median resists them.
Right skew: mean > median. Left skew: mean < median.
A weighted mean divides by ; never average averages of groups of different sizes.
A trimmed mean drops the same number of values at each end.
In code, sort a copy, and halve two whole numbers with / 2.0: (8 + 9) / 2 is 8.
FlashcardsInteractive · disabled in the PDF
Sample mean
The sum of the values divided by n, written x̄.
Median
The middle value of the sorted data; half are at or below it.
Mode
The most common value.
Resistant measure
One that an extreme value cannot move much: the median.
In a right-skewed distribution…
the mean is greater than the median.
Weighted mean
Σ wᵢxᵢ divided by Σ wᵢ: values count in proportion to their weights.
Trimmed mean
The mean after dropping the same number of values from each end.
Why / 2.0 in a median of ints?
Two whole numbers divide to a whole number: (8 + 9) / 2 is 8, not 8.5.
Module 4: Spread: range, variance and standard deviation
Statistics38 / 246
Module 4 · Spread: range, variance and standard deviation
The centre is not the whole story
Two bakeries both sell loaves that weigh 500 g on average. At the first, five loaves weigh 498, 499, 500, 501 and 502 g. At the second, 460, 480, 500, 520 and 540 g. Same mean, very different bakeries: at the second you might get a loaf 40 g light. Spread (or variability, or dispersion) measures how far the values stray from each other and from their centre. A centre without a spread is half a summary.
Bakery
Loaves (g)
Mean
Range
A
498, 499, 500, 501, 502
500 g
4 g
B
460, 480, 500, 520, 540
500 g
80 g
QuizInteractive · disabled in the PDF
Two trains both arrive on average exactly on time. Train A is always within 1 minute; train B is often 15 minutes early or late. Which statement is right?
Two trains both arrive on average exactly on time. Train A is always within 1 minute; train B is often 15 minutes early or late. Which statement is right?
Statistics39 / 246
Module 4 · Spread: range, variance and standard deviation
The range is simple but fragile
The range is the largest value minus the smallest. It is easy to compute and to explain, but it depends on only two values, the two most extreme ones, so a single outlier or typo can change it completely. It also tends to grow as you collect more data, because a bigger sample is more likely to contain an extreme value.
QuizInteractive · disabled in the PDF
Nine students’ reaction times are between 0.21 s and 0.30 s. A tenth student sneezes and records 1.40 s. What happens to the range?
Nine students’ reaction times are between 0.21 s and 0.30 s. A tenth student sneezes and records 1.40 s. What happens to the range?
Statistics40 / 246
Module 4 · Spread: range, variance and standard deviation
Quartiles and the interquartile range
The quartiles split sorted data into four parts with about the same number of values. The median is the middle quartile, . Here is the simple method: the lower quartile is the median of the values below the median, and the upper quartile is the median of the values above it (with an odd , the median itself is left out of both halves). The interquartile range, , is the spread of the middle half of the data. It ignores the top and bottom quarters, so outliers cannot move it.
Eleven values. The median is the 6th, 9; each half has five values.
Software disagrees a little. There are several definitions of quartiles. Spreadsheets and statistics libraries usually interpolate between values, and may give instead of 5 for this data. The differences shrink as grows. Say which method you use when the exact number matters.
QuizInteractive · disabled in the PDF
What is the IQR of 1, 3, 4, 6, 7, 9, 10, 15 using the median-of-halves method?
What is the IQR of 1, 3, 4, 6, 7, 9, 10, 15 using the median-of-halves method?
ProblemInteractive · disabled in the PDF
Nine values, sorted: 4, 7, 8, 10, 12, 15, 16, 21, 40. Using the median-of-halves method, find , , the IQR and the range.
Statistics41 / 246
Module 4 · Spread: range, variance and standard deviation
The 1.5 × IQR rule flags outliers
An outlier is a value far from the rest. A common rule, due to John Tukey, draws two fences 1.5 IQRs beyond the quartiles, and flags any value outside them. In a box plot, the whiskers stop at the most extreme values inside the fences, and the outliers are drawn as points. Flagged does not mean wrong: an outlier may be a typo, or the most interesting value in the data. Look at it before deciding.
For the eleven values: 30 is above 27.5, so it is flagged.
Median
Upper fence
The box plot of the eleven values: the upper whisker stops at 18, the largest value inside the fence, and 30 is a point.
Fill the blanksInteractive · disabled in the PDF
Finish fences, which returns the lower and upper fences for the quartiles q1 and q3.
For the nine values 4, 7, 8, 10, 12, 15, 16, 21, 40, with and , find the lower and upper fences, and the value where the upper whisker of the box plot stops.
Statistics42 / 246
Module 4 · Spread: range, variance and standard deviation
Variance is the mean squared deviation
The IQR uses only the quartiles. To use every value, start from the deviations , how far each value is from the mean. Their sum is always 0 (the last module showed why), so their mean is useless. Squaring each deviation makes it positive, and big deviations count much more. The mean of the squared deviations is the variance. For a whole population of values with mean , it is written (sigma squared).
2
4
4
4
5
5
7
9
Sum
−3
−1
−1
−1
0
0
2
4
0
9
1
1
1
0
0
4
16
32
Eight values with mean . The squared deviations add up to 32, so . The variance is in squared units (square grams, square minutes), which are hard to picture, so its square root, the standard deviation , is what people report: roughly, the typical distance of a value from the mean, in the data’s own units.
Statistics43 / 246
Module 4 · Spread: range, variance and standard deviation
A sample divides by n − 1
Usually your data is a sample, and you want to estimate the population’s spread. You do not know , so you measure deviations from instead. But is, by its definition, the point closest to this sample (in squared distance), closer than is. So the squared deviations from are a little too small on average. Dividing by instead of corrects this exactly. The result is the sample variance , and is the sample standard deviation.
Another way to see it: the deviations from must add up to 0, so once you know of them, the last is fixed. Only are free to vary: the sample has degrees of freedom left for estimating spread.
QuizInteractive · disabled in the PDF
You measure 12 apples picked at random from an orchard to estimate how much apple masses vary across the whole orchard. Which do you divide the sum of squared deviations by?
You measure 12 apples picked at random from an orchard to estimate how much apple masses vary across the whole orchard. Which do you divide the sum of squared deviations by?
Going deeper
Why exactly ? Write each deviation from as and expand. The cross terms vanish because the deviations from sum to 0, leaving the identity below. On average over many samples, the left side is , and the last term is times the variance of , which is (a later module shows this), so it averages to . That leaves the sum of squares from averaging . An estimator whose average equals the true value is called unbiased; is unbiased for , though is still very slightly biased for .
Statistics44 / 246
Module 4 · Spread: range, variance and standard deviation
Standard deviation is the width of the data
For a bell-shaped distribution, the standard deviation is the distance from the centre to where the curve bends from curving down to curving up. Drag σ: the centre stays put, the curve spreads out, and because the total area always stands for 100% of the data, a wider curve must be lower. You will meet this curve, the normal distribution, properly in a later module.
Distribution
Peak height0.199
A bell-shaped distribution with mean μ and standard deviation σ. The arrows run from μ to μ ± σ.
Standard deviation is not resistant. Because deviations are squared, one far-off value inflates a lot, just as it drags the mean. For skewed data or data with outliers, report the median and IQR; for roughly symmetric data, the mean and standard deviation.
Statistics45 / 246
Module 4 · Spread: range, variance and standard deviation
Try it: the sample standard deviation
Find the bugInteractive · disabled in the PDF
This returns 0 for every data set. Which line is wrong?
C++
Code challengeInteractive · disabled in the PDF
Finish sampleSd(values): compute the mean, add up the squared deviations from it, divide by n - 1, and return the square root.
C++
1#include<cmath>2#include<vector>34doublesampleSd(const std::vector<double>& values){5int n = values.size();6double mean =0;7for(double v : values) mean += v;8 mean /= n;9 // TODO: sum of squared deviations, divided by n - 110return0;11}
Statistics46 / 246
Module 4 · Spread: range, variance and standard deviation
A z-score measures distance in standard deviations
Is 78 in a maths test better than 85 in English? Not if the English test was easy. A z-score (standard score) says how many standard deviations a value is above or below the mean. Positive is above, negative below, 0 is exactly average. Because it has no units, it compares values from different scales: test marks, heights and temperatures alike.
Maths: mean 70, SD 4. English: mean 80, SD 10. The 78 in maths is the far more unusual result.
Code challengeInteractive · disabled in the PDF
Finish zScores(values, mean, sd): return each value’s z-score, in the same order.
Module 4 · Spread: range, variance and standard deviation
The 68–95–99.7 rule for bell-shaped data
For data with a bell shape (a normal distribution, coming later), the standard deviation tells you a lot: about 68% of the values are within 1 SD of the mean, about 95% within 2 SDs, and about 99.7% within 3. This is the empirical rule. A z-score beyond ±3 is then very rare, which makes it a natural flag for an outlier in bell-shaped data.
Where the values of a bell-shaped distribution fall, by z-score. The bars add up to 100%, give or take rounding.
QuizInteractive · disabled in the PDF
Adult heights in a country are bell-shaped with mean 170 cm and SD 7 cm. About what share of adults are taller than 184 cm?
Adult heights in a country are bell-shaped with mean 170 cm and SD 7 cm. About what share of adults are taller than 184 cm?
Statistics48 / 246
Module 4 · Spread: range, variance and standard deviation
Chebyshev’s inequality works for any shape
The empirical rule needs a bell shape. Chebyshev’s inequality needs nothing: for any distribution, at least of the values lie within standard deviations of the mean, for any . So at least 75% are within 2 SDs and at least 88.9% within 3, whatever the data. The guarantee is weak because it must hold even for the strangest shapes, but it is always true.
At least (any shape)
Chebyshev’s guarantee for any shape (the curve), against what a bell shape actually gives (the points).
QuizInteractive · disabled in the PDF
Delivery times have mean 30 minutes and SD 5 minutes, and you know nothing about their shape. What can you say for certain about deliveries between 20 and 40 minutes?
Delivery times have mean 30 minutes and SD 5 minutes, and you know nothing about their shape. What can you say for certain about deliveries between 20 and 40 minutes?
Statistics49 / 246
Module 4 · Spread: range, variance and standard deviation
Practice problems
ProblemInteractive · disabled in the PDF
A sample of five parcels weighs 6, 8, 9, 11 and 16 kg. Find the mean, the sample variance and the sample standard deviation . Then find the variance you would get if these five parcels were the whole population, dividing by .
kg
kg²
kg
kg²
ProblemInteractive · disabled in the PDF
In a running club, 100 m times have mean 13.0 s and SD 0.4 s, and long jumps have mean 5.0 m and SD 0.5 m. Mia runs 100 m in 12.4 s and jumps 5.6 m. Find the z-score of each result.
ProblemInteractive · disabled in the PDF
The weights of bags of flour are bell-shaped, with mean 500 g and SD 10 g. Using the 68–95–99.7 rule, about what percentage of bags weigh between 480 and 520 g? More than 510 g? Between 490 and 520 g?
%
%
%
ProblemInteractive · disabled in the PDF
Waiting times at a clinic have mean 40 minutes and SD 6 minutes, and you know nothing about their shape. What is the smallest percentage of waits that Chebyshev’s inequality guarantees are between 28 and 52 minutes? Between 31 and 49 minutes?
%
%
Statistics50 / 246
Module 4 · Spread: range, variance and standard deviation
Recap
Spread is how far values stray from each other and from the centre.
Range = max − min: simple, but set by two extreme values.
Quartiles split the sorted data into quarters; IQR = is the spread of the middle half.
The fences and flag outliers: look at them, do not just delete them.
Variance is the mean squared deviation; the standard deviation is its square root, in the data’s units.
Population: divide by . Sample: divide by , because deviations from are a little too small.
A z-score counts standard deviations from the mean.
Bell-shaped: 68–95–99.7. Any shape: at least within SDs.
FlashcardsInteractive · disabled in the PDF
Range
The largest value minus the smallest.
IQR
Q3 − Q1: the spread of the middle half of the data.
Tukey’s fences
Q1 − 1.5 IQR and Q3 + 1.5 IQR; values outside are flagged as outliers.
Variance
The mean of the squared deviations from the mean, in squared units.
Standard deviation
The square root of the variance: a typical distance from the mean.
Why n − 1?
Deviations from x̄ are smaller than from μ; dividing by n − 1 makes s² unbiased.
z-score
How many standard deviations a value is from the mean: (x − x̄) / s.
Empirical rule
Bell-shaped data: about 68%, 95% and 99.7% within 1, 2 and 3 SDs.
Chebyshev’s inequality
Any data: at least 1 − 1/k² within k SDs of the mean.
Module 5: Two variables: scatter plots and correlation
Statistics51 / 246
Module 5 · Two variables: scatter plots and correlation
A scatter plot shows two numerical variables
So far each variable was looked at alone. Often the question is how two relate: do students who study longer score higher? A scatter plot draws one point per observation, with one variable across and the other up. If one variable might help explain or predict the other, it goes on the x-axis and is called the explanatory variable; the one it may explain goes on the y-axis and is the response variable.
Twelve students: hours of study for a test, and their mark. Each point is one student.
QuizInteractive · disabled in the PDF
You study whether the outside temperature affects how many ice creams a kiosk sells each day. Which goes on the x-axis?
You study whether the outside temperature affects how many ice creams a kiosk sells each day. Which goes on the x-axis?
Statistics52 / 246
Module 5 · Two variables: scatter plots and correlation
Describe direction, form and strength
Describe a scatter plot in three words. Direction: positive if y tends to rise as x rises, negative if it falls. Form: does the cloud follow a straight line (linear), a curve, or no pattern? Strength: how tightly the points hug that form. Also look for outliers, points far from the pattern. The study data is positive, linear and strong. Drag r below to see what the strengths look like.
Trend
r0.7
Ten points whose correlation is r. Near ±1 they hug a line; near 0 they are a shapeless cloud.
QuizInteractive · disabled in the PDF
For used cars, the older the car, the lower its price, and the points lie close to a gently curving line. How would you describe it?
For used cars, the older the car, the lower its price, and the points lie close to a gently curving line. How would you describe it?
Statistics53 / 246
Module 5 · Two variables: scatter plots and correlation
Covariance: do the deviations agree
To put a number on it, draw lines through the means and , cutting the plot into four quarters. A point up and to the right of the means has both deviations and positive, so their product is positive; down and to the left, both negative, product positive again. In the other two quarters the product is negative. The covariance is the average of these products (dividing by for a sample). Positive: the points sit mostly in the agreeing quarters.
Product
1
2
−2
−2
4
2
4
−1
0
0
3
5
0
1
0
4
4
1
0
0
5
5
2
1
2
Sum
6
Here and , so . The trouble is its units: x in hours and y in marks give a covariance in hour-marks, and measuring in minutes would multiply it by 60. Its size says nothing about strength on its own.
QuizInteractive · disabled in the PDF
Most points of a scatter plot lie above and left of the means, or below and right of them. The covariance is…
Most points of a scatter plot lie above and left of the means, or below and right of them. The covariance is…
ProblemInteractive · disabled in the PDF
Five points have = 2, 4, 6, 8, 10 and = 5, 9, 7, 13, 11. Find , the sum of the products of deviations , and the sample covariance .
Statistics54 / 246
Module 5 · Two variables: scatter plots and correlation
Correlation is covariance without units
Divide the covariance by both standard deviations and the units cancel. The result is Pearson’s correlation coefficient . Equivalently, it is the average product of the two variables’ z-scores. It always lies between −1 and 1: 1 for points exactly on a rising line, −1 on a falling line, and around 0 when there is no linear pattern.
The five points from the last slide. The $n - 1$s cancel, so the sums are enough.
QuizInteractive · disabled in the PDF
Which of these are true of Pearson’s ?
Which of these are true of Pearson’s ?
ProblemInteractive · disabled in the PDF
Five points have = 1, 2, 3, 4, 5 and = 10, 8, 9, 5, 3. Find , , and Pearson’s .
Statistics55 / 246
Module 5 · Two variables: scatter plots and correlation
Correlation only sees straight lines
Pearson’s measures linear association. Points exactly on the curve , from to , have : the left half falls and the right half rises, and the products cancel. A perfect relationship, and a correlation of zero. And one outlier can create a strong correlation from nothing, or hide a real one. Always plot the data before trusting .
Seven points on y = x². The relationship is perfect, yet r = 0.
QuizInteractive · disabled in the PDF
A report says the correlation between two variables is . What can you conclude?
A report says the correlation between two variables is . What can you conclude?
Statistics56 / 246
Module 5 · Two variables: scatter plots and correlation
Try it: compute the correlation
Compute from the sums: the means first, then three sums over the points.
Code challengeInteractive · disabled in the PDF
Finish correlation(xs, ys): return Pearson’s r, the sum of the products of deviations divided by the square root of the product of the two sums of squared deviations.
C++
1#include<cmath>2#include<vector>34doublecorrelation(const std::vector<double>& xs,5const std::vector<double>& ys){6int n = xs.size();7double mx =0, my =0;8for(int i =0; i < n; i++){9 mx += xs[i];10 my += ys[i];11}12 mx /= n;13 my /= n;14 // TODO: three sums, then r15return0;16}
Statistics57 / 246
Module 5 · Two variables: scatter plots and correlation
Rank correlation for any rising pattern
Replace each value by its rank, its position when sorted (1 for the smallest), and compute Pearson’s on the ranks. That is Spearman’s rank correlation . It is 1 whenever y always rises with x, in a straight line or not: it measures a monotonic relationship. And since an outlier can only be the top rank, not a huge number, it is resistant. It also works for ordinal data, such as two judges’ rankings.
x
y
Rank of x
Rank of y
1
1
1
1
2
4
2
2
3
9
3
3
4
16
4
4
5
100
5
5
Here y always rises, so the ranks agree perfectly and , while Pearson’s , dragged down by the jump to 100. With no tied values, there is a shortcut, where is the difference between the two ranks of observation :
Code challengeInteractive · disabled in the PDF
Finish ranks(values): return the rank of each value, in the original order, where the smallest value has rank 1. You can assume there are no ties.
C++
1#include<algorithm>2#include<utility>3#include<vector>45std::vector<int>ranks(const std::vector<double>& values){6 std::vector<int>result(values.size(),1);7 // TODO: rank each value8return result;9}
Statistics58 / 246
Module 5 · Two variables: scatter plots and correlation
Two-way tables relate two categorical variables
For two categorical variables there is no scatter plot; count every combination instead, in a two-way table (or contingency table). To compare groups of different sizes, turn the counts into percentages within each group: of each row, or of each column, depending on the question.
Age group
Prefers tea
Prefers coffee
Total
Under 30
20
60
80
30 and over
70
50
120
Total
90
110
200
Row percentages: 25% of under-30s prefer tea (), against about 58% of those 30 and over (). Age and drink preference are associated: knowing someone’s age changes the chance they prefer tea. If they were not, both rows would show the same 45% ().
QuizInteractive · disabled in the PDF
Of the people who prefer tea, what share are 30 or over?
Of the people who prefer tea, what share are 30 or over?
Statistics59 / 246
Module 5 · Two variables: scatter plots and correlation
Correlation is not causation
Across the days of a year, ice cream sales and drownings are positively correlated. Ice cream does not cause drowning: hot weather drives both, as more people buy ice cream and more people swim. A variable that is not in your data but affects both of the ones you are looking at is a lurking variable (a confounder when it muddles a cause you are trying to measure). Other explanations of a correlation: the cause runs the other way, or it is chance in a small sample.
Temperature drives both; the link between the other two is only a shadow of it.
QuizInteractive · disabled in the PDF
Across towns, the number of fire engines sent to a fire is positively correlated with the damage it does. What best explains this?
Across towns, the number of fire engines sent to a fire is positively correlated with the damage it does. What best explains this?
Statistics60 / 246
Module 5 · Two variables: scatter plots and correlation
Simpson’s paradox: the trend can reverse
A real study of two treatments for kidney stones (Charig and colleagues, 1986) found that treatment A worked better for small stones and for large stones, yet treatment B worked better overall. How? Doctors gave A, the more serious operation, mostly to the hard cases, large stones, where any treatment succeeds less often. B’s overall rate is flattered by its many easy cases. A trend that appears in every group but reverses when the groups are combined is Simpson’s paradox; the lurking variable here is stone size.
Small stones
Large stones
All
Treatment A
81 / 87 = 93%
192 / 263 = 73%
273 / 350 = 78%
Treatment B
234 / 270 = 87%
55 / 80 = 69%
289 / 350 = 83%
Success rates (%). A wins within each size; B wins overall, because B treated mostly small stones.
QuizInteractive · disabled in the PDF
You have a kidney stone of unknown size. Based on this data, which treatment should you prefer?
You have a kidney stone of unknown size. Based on this data, which treatment should you prefer?
Going deeper
The arithmetic behind the reversal: an overall rate is a weighted mean of the group rates, weighted by how many patients each group has. A’s 78% is mostly its 73% (263 of its 350 patients had large stones); B’s 83% is mostly its 87% (270 of 350 had small stones). Different weights can put the combined rates in either order. Simpson’s paradox can only happen when the groups are unequally split between the things being compared.
Statistics61 / 246
Module 5 · Two variables: scatter plots and correlation
Practice problems
ProblemInteractive · disabled in the PDF
Two judges rank five bakers. Judge A ranks them 1, 2, 3, 4, 5, and judge B ranks the same five bakers, in the same order, 2, 1, 4, 3, 5. Find and Spearman’s .
ProblemInteractive · disabled in the PDF
Of 300 shoppers, 120 saw an advert, and 48 of those bought the product. Of the 180 who did not see it, 36 bought it. What percentage of those who saw the advert bought? Of those who did not see it? And what percentage of the buyers had seen the advert?
%
%
%
ProblemInteractive · disabled in the PDF
Hospital A saves 190 of 200 mild cases and 240 of 400 severe cases. Hospital B saves 360 of 400 mild cases and 110 of 200 severe cases. Find each hospital’s overall survival rate, as a percentage.
%
%
ProblemInteractive · disabled in the PDF
For study time (in hours) and marks, hour-marks, hours and marks. Find . Then study time is measured in minutes instead: find the new covariance and the new .
Statistics62 / 246
Module 5 · Two variables: scatter plots and correlation
Recap
A scatter plot shows two numerical variables; the explanatory one goes on x, the response on y.
Describe direction, form and strength, and look for outliers.
Covariance averages the products of deviations; its sign gives direction, but it has units.
Pearson’s is between −1 and 1, has no units, and only measures straight lines.
Spearman’s is Pearson’s on ranks: monotonic patterns, resistant to outliers.
Two-way tables relate categorical variables; compare percentages within groups.
Correlation is not causation: look for lurking variables, reversed causes and chance.
Simpson’s paradox: a trend in every group can reverse when the groups are combined.
FlashcardsInteractive · disabled in the PDF
Explanatory variable
The one that may explain or predict the other: on the x-axis.
Covariance
The average product of the deviations of x and y from their means.
Pearson’s r
Covariance divided by both standard deviations: linear association, −1 to 1.
r = 0 means…
no linear relationship; there may still be a curved one.
Spearman’s rank correlation
Pearson’s r computed on the ranks: measures monotonic relationships.
Two-way table
Counts of every combination of two categorical variables.
Lurking variable
A variable outside the data that affects both variables you are comparing.
Simpson’s paradox
A trend within every group reverses when the groups are combined.
Module 6: Probability
Statistics63 / 246
Module 6 · Probability
Probability puts a number on chance
Statistics reasons from samples to populations, and samples involve chance. To measure how sure you can be, you need the language of chance: probability. A random experiment is anything with an uncertain result: rolling a die, tossing a coin, picking a person at random. Each possible result is an outcome, and the set of all of them is the sample space . An event is a set of outcomes you care about, and its probability is a number from 0 (impossible) to 1 (certain).
One roll of a fair die.
Experiment
Something with an uncertain result that could be repeated: a roll, a draw.
Outcome
One possible result: rolling a 4.
Sample space
The set of all outcomes, .
Event
A set of outcomes: “even”, “more than 4”.
Probability
A number from 0 to 1 saying how likely an event is.
QuizInteractive · disabled in the PDF
You toss a coin twice and record each result. Which is the sample space?
You toss a coin twice and record each result. Which is the sample space?
Statistics64 / 246
Module 6 · Probability
Equally likely outcomes: count and divide
When every outcome is equally likely, as with a fair die or a well-shuffled deck, the probability of an event is the number of outcomes in it divided by the number in the sample space. Rolling two dice has equally likely outcomes (a red die and a blue die, so 3 then 4 is different from 4 then 3). Six of them add up to 7: (1, 6), (2, 5), (3, 4), (4, 3), (5, 2), (6, 1).
The probability of each total of two dice: count the ways and divide by 36. Seven is most likely.
QuizInteractive · disabled in the PDF
Two fair dice are rolled. What is the probability that the total is 10 or more?
Two fair dice are rolled. What is the probability that the total is 10 or more?
ProblemInteractive · disabled in the PDF
Two fair dice are rolled. What is the probability that the total is 8? That both dice show the same number?
Statistics65 / 246
Module 6 · Probability
Probability as long-run frequency
Most chances cannot be counted: the chance a bus is late, or a seed sprouts. Then probability is the long-run relative frequency: repeat the experiment many times, and the share of times the event happens settles down towards its probability. The settling is slow. The typical gap between the share and the true probability shrinks like : to halve it, you need four times as many trials. This is the law of large numbers, which a later module makes precise.
True probability
Typical range
Tossing a fair coin n times. The share of heads typically lands between these curves (one standard deviation either side of 0.5).
PlaygroundInteractive · disabled in the PDF
C++
1#include<iostream>2#include<random>34intmain(){5 std::mt19937gen(42); // makes random numbers, from the seed 426 std::uniform_real_distribution<double>uniform(0.0,1.0);7int heads =0;8for(int n =1; n <=10000; n++){9if(uniform(gen)<0.5) heads++;10if(n ==10|| n ==100|| n ==1000|| n ==10000){11double share =double(heads)/ n;12 std::cout << n <<" tosses: "<< share <<"\n";13}14}15}
uniform(gen) gives a number from 0 up to 1, so < 0.5 is a fair coin. The same seed gives the same tosses every run: change 42 to toss again. The share wobbles less as n grows. (heads / n with two ints would print 0.)
The gambler’s fallacy. After five heads in a row, a fair coin is not due a tail: the next toss is still 50–50. The law of large numbers does not work by evening things out; early streaks are not cancelled, they are swamped by the many tosses that follow.
Statistics66 / 246
Module 6 · Probability
Three rules every probability obeys
Whatever probability means, counting, frequency or degree of belief, it follows three rules, called axioms (Kolmogorov, 1933). Everything else in probability is derived from them. Two events are disjoint (mutually exclusive) when they cannot both happen: rolling a 1 and rolling a 6 on one roll.
Every probability is at least 0: .
Something must happen: .
For disjoint events, probabilities add: .
QuizInteractive · disabled in the PDF
A weather model gives tomorrow: sunny 0.5, cloudy 0.3, rainy 0.3, snowy −0.1. Exactly one of the four will happen. What is wrong?
A weather model gives tomorrow: sunny 0.5, cloudy 0.3, rainy 0.3, snowy −0.1. Exactly one of the four will happen. What is wrong?
Statistics67 / 246
Module 6 · Probability
The complement: one minus the chance
The complement of , written (“not A”), is every outcome not in . and are disjoint and together make up , so the rules give . This is the trick for any “at least one” question: the opposite of “at least one six in four rolls” is “no six in four rolls”, which is easy to work out.
Each roll avoids a six with probability 5/6, and the rolls do not affect each other, so the chances multiply (two slides on).
P(at least one six)0.518
The chance of at least one six in n rolls. Drag n: it passes one half at 4 rolls.
QuizInteractive · disabled in the PDF
Someone says: “each roll has a 1/6 chance of a six, so in 6 rolls you are certain to get one.” What is the real chance?
Someone says: “each roll has a 1/6 chance of a six, so in 6 rolls you are certain to get one.” What is the real chance?
ProblemInteractive · disabled in the PDF
What is the probability of at least one head in 5 tosses of a fair coin? Of at least one six in 3 rolls of a fair die?
Going deeper
This is a 17th-century puzzle. The gambler Chevalier de Méré won money betting on at least one six in 4 rolls, then lost betting on at least one double six in 24 rolls of two dice, having reasoned that . The complement shows why: , just under one half. His question to Pascal, and Pascal’s letters with Fermat, are often called the start of probability theory.
Statistics68 / 246
Module 6 · Probability
The addition rule: or
For events that can happen together, adding their probabilities counts the overlap twice, so subtract it once. That is the general addition rule. Draw one card from a standard deck of 52 (4 suits of 13). The chance it is a heart or a king: 13 hearts plus 4 kings counts the king of hearts twice.
(union) is “or, or both”; (intersection) is “and”. For disjoint events , giving the third rule.
QuizInteractive · disabled in the PDF
In a class, 60% of students play a sport, 30% play an instrument, and 20% do both. What share does at least one of the two?
In a class, 60% of students play a sport, 30% play an instrument, and 20% do both. What share does at least one of the two?
Statistics69 / 246
Module 6 · Probability
Independent events multiply
Two events are independent if knowing that one happened does not change the chance of the other: two separate coin tosses, two dice. For independent events the probability that both happen is the product. Many events are not independent: the chance of rain tomorrow depends on whether it rains today, and drawing two cards without putting the first back changes the deck.
QuizInteractive · disabled in the PDF
Events A and B both have probability 0.4, and they are disjoint: they cannot both happen. Are they independent?
Events A and B both have probability 0.4, and they are disjoint: they cannot both happen. Are they independent?
Going deeper
Multiplying probabilities that are not independent is behind some famous errors. In the 1999 trial of Sally Clark in England, an expert squared 1 in 8543, the chance of one cot death in a family like hers, to claim 1 in 73 million for two, as if the deaths were independent. Genetic and environmental factors make a second death far more likely after a first. The Royal Statistical Society publicly criticised the figure, and the conviction was overturned in 2003. The next module covers the other error in that case.
Statistics70 / 246
Module 6 · Probability
Counting: arrangements and choices
Equally likely outcomes need counting, and the counts get big fast. The multiplication principle: if one choice can be made in ways and then another in ways, the pair can be made in ways. Arranging different things in order gives ways ( factorial). Choosing of in order is a permutation; choosing of when order does not matter is a combination, written and read “n choose k”.
Each set of 6 lottery numbers can be drawn in orders, all counting as one ticket, so divide by 720.The number of ways to choose k of 10 things. Choosing 3 is the same as leaving out 7, so the bars are symmetric.
QuizInteractive · disabled in the PDF
A club of 10 people picks a committee of 3, with no roles. How many different committees are possible?
A club of 10 people picks a committee of 3, with no roles. How many different committees are possible?
Statistics71 / 246
Module 6 · Probability
Try it: choose and the birthday problem
Code challengeInteractive · disabled in the PDF
Finish choose(n, k): the number of ways to choose k of n things. Return 0 when k < 0 or k > n. Build it up as a product, one factor at a time, rather than computing big factorials.
C++
1longlongchoose(int n,int k){2 // TODO: multiply in one factor at a time3return1;4}
In a room of people, what is the chance that two share a birthday? Use the complement. Ignoring 29 February and assuming all 365 days are equally likely: the second person avoids the first’s birthday with probability , the third avoids both with , and so on.
Code challengeInteractive · disabled in the PDF
Finish sharedBirthday(n): the probability that at least two of n people share a birthday, using the formula above.
C++
1doublesharedBirthday(int n){2double allDifferent =1;3 // TODO: multiply in each person's chance of a new birthday4return allDifferent;5}
The birthday problem: the chance of a shared birthday grows much faster than intuition says.
Statistics72 / 246
Module 6 · Probability
When counting is hard, simulate
Some probabilities are hard to count but easy to act out. Simulation (the Monte Carlo method) runs the random experiment many times on a computer and uses the share of runs where the event happened as an estimate. By the law of large numbers the estimate approaches the true probability, with a typical error of about at worst, so 10 000 runs give about two correct decimal places. Simulation is also the best way to check a calculation.
PlaygroundInteractive · disabled in the PDF
C++
1#include<iostream>2#include<random>3#include<set>45std::mt19937gen(1); // the seed: change it for another run6std::uniform_int_distribution<int>birthday(0,364);78boolsomeoneShares(int people){9 std::set<int> seen;10for(int i =0; i < people; i++){11int day =birthday(gen);12if(seen.contains(day))returntrue;13 seen.insert(day);14}15returnfalse;16}1718intmain(){19int runs =10000, hits =0;20for(int r =0; r < runs; r++)21if(someoneShares(23)) hits++;22 std::cout <<"estimate: "<<double(hits)/ runs23<<", exact: 0.5073\n";24}
Change the seed a few times: the estimate wobbles by about 0.005. Change 23 to 40, or runs to 100. birthday(gen) picks a whole number from 0 to 364, each as likely: a day of the year.
Put in orderInteractive · disabled in the PDF
Put the steps of a Monte Carlo estimate in order.
1.Repeat the experiment many times, counting the runs where it happened
2.Decide how to tell whether the event happened in one run
3.Divide the count by the number of runs
4.Run it again with more runs to see how much the estimate wobbles
5.Write a function that performs the random experiment once
Statistics73 / 246
Module 6 · Probability
Practice problems
ProblemInteractive · disabled in the PDF
One card is drawn from a standard deck of 52. What is the probability that it is red or a face card (a jack, queen or king)? That it is neither?
ProblemInteractive · disabled in the PDF
A machine works only if all three of its parts work. The parts work independently, with probabilities 0.9, 0.95 and 0.8. What is the probability that the machine works? That at least one part fails? That all three parts fail?
ProblemInteractive · disabled in the PDF
A door code is 3 letters, each from A to F, and letters may repeat. How many codes are there? How many have three different letters? If a code is chosen at random, what is the chance that its letters are all different?
ProblemInteractive · disabled in the PDF
A committee of 3 is chosen at random from 6 women and 4 men. How many different committees are possible? How many are all women? What is the probability that the committee is all women?
Statistics74 / 246
Module 6 · Probability
Recap
An experiment has outcomes; the sample space is all of them; an event is a set of outcomes.
Equally likely outcomes: = outcomes in ÷ outcomes in .
Otherwise, probability is the long-run relative frequency; its wobble shrinks like .
Axioms: , , and disjoint events add.
Complement: , the trick for “at least one”.
Addition: .
Independent events multiply: . Disjoint is not independent.
When counting is hard, simulate, and report how much the estimate wobbles.
FlashcardsInteractive · disabled in the PDF
Sample space
The set of all possible outcomes of an experiment.
Event
A set of outcomes; its probability is between 0 and 1.
Complement rule
P(not A) = 1 − P(A).
Addition rule
P(A or B) = P(A) + P(B) − P(A and B).
Independent events
Knowing one happened does not change the chance of the other; P(A and B) = P(A)P(B).
Disjoint events
Events that cannot both happen: P(A and B) = 0.
n choose k
n! / (k!(n − k)!): ways to choose k of n when order does not matter.
Gambler’s fallacy
Believing independent events “even out”: after five heads, a tail is not due.
Monte Carlo
Estimating a probability by simulating the experiment many times.
Module 7: Conditional probability and Bayes' theorem
Statistics75 / 246
Module 7 · Conditional probability and Bayes' theorem
Conditional probability: once you know something
New information changes chances. The probability of given , written , is the chance of once you know happened. Knowing shrinks the sample space to ’s outcomes; among those, you want the ones that are also in . So divide the chance of both by the chance of .
Age group
Prefers tea
Prefers coffee
Total
Under 30
20
60
80
30 and over
70
50
120
Total
90
110
200
The table from the last module. The condition picks the row or column you divide by.
QuizInteractive · disabled in the PDF
Using the table, what is ?
Using the table, what is ?
ProblemInteractive · disabled in the PDF
Of 250 students, 120 are in their first year and 130 in their second. 90 of the first-years and 110 of the second-years passed an exam. Find , and .
Statistics76 / 246
Module 7 · Conditional probability and Bayes' theorem
Chances multiply along a chain
Rearranging the definition gives the general multiplication rule: the chance of and is the chance of , times the chance of once has happened. It works for any events. If , knowing changes nothing, which is the precise definition of independence, and the rule becomes the simple product from the last module.
Two cards drawn without putting the first back: after one ace, 3 aces remain among 51 cards.
QuizInteractive · disabled in the PDF
A drawer holds 5 black and 3 white socks. You pull out two without looking. What is the chance both are white?
A drawer holds 5 black and 3 white socks. You pull out two without looking. What is the chance both are white?
ProblemInteractive · disabled in the PDF
A bag holds 4 red and 6 blue counters. You draw two without putting the first back. What is the probability that both are red? That they are one of each colour?
Statistics77 / 246
Module 7 · Conditional probability and Bayes' theorem
Tree diagrams lay out the chain
A tree diagram draws a chain of chances. Each branch is one possibility, labelled with its conditional probability; multiply along a path for the chance of that whole path, and add the paths that make up an event. A factory has two machines. Machine A makes 60% of the parts and 2% of its parts are defective; machine B makes 40%, and 5% of its parts are defective.
A part
Machine A0.6
Defective0.02 → 0.6 × 0.02 = 0.012
Fine0.98 → 0.588
Machine B0.4
Defective0.05 → 0.4 × 0.05 = 0.020
Fine0.95 → 0.380
Multiply along each path. The four end chances add up to 1.
QuizInteractive · disabled in the PDF
From the tree, what is the probability that a part is fine and came from machine B?
From the tree, what is the probability that a part is fine and came from machine B?
Statistics78 / 246
Module 7 · Conditional probability and Bayes' theorem
The law of total probability adds the paths
What share of all parts are defective? A defective part comes from A or from B, never both, so add the two defective paths. In general, if events split the sample space into disjoint pieces (a partition), any event’s chance is the sum over the pieces of “piece, then event”. This is the law of total probability: a weighted mean of the conditional chances, weighted by how common each piece is.
3.2% of all parts are defective: between the machines’ 2% and 5%, nearer the bigger machine’s rate.
Code challengeInteractive · disabled in the PDF
Finish totalProbability(priors, likelihoods): priors[j] is and likelihoods[j] is . Return .
C++
1#include<vector>23doubletotalProbability(const std::vector<double>& priors,4const std::vector<double>& likelihoods){5 // TODO: add up each piece's share6return0;7}
Statistics79 / 246
Module 7 · Conditional probability and Bayes' theorem
Bayes’ theorem turns the condition around
A part is defective. What is the chance it came from machine B? You know but want . Bayes’ theorem turns one into the other: the chance of the path through B and defective, divided by the chance of all defective paths. The starting chance is the prior; is the likelihood; the answer is the posterior, the prior updated by the evidence.
Machine B makes only 40% of the parts, but 62.5% of the defective ones.Prior and posterior: each machine’s share of all parts, and of the defective parts.
QuizInteractive · disabled in the PDF
A part is defective. What is the chance it came from machine A?
A part is defective. What is the chance it came from machine A?
Statistics80 / 246
Module 7 · Conditional probability and Bayes' theorem
A positive test for a rare condition
A condition affects 1% of people (the prevalence). A test for it catches 90% of people who have it (its sensitivity), but also comes back positive for 9% of people who do not (the false positive rate). You test positive. Most people, including many doctors in surveys, guess about 90%. Count it out with 1000 people instead: natural frequencies make Bayes almost obvious.
1000 people
10 have it
9 test positive
1 tests negative
990 do not
89 test positive9% of 990
901 test negative
1000 people, split by the condition and then by the test.Only about 9% of positives have the condition: the few true positives are swamped by false ones from the many healthy people.
Posterior
P(condition | positive)0.092
The chance a positive is real, against prevalence. Drag the test’s rates: for rare conditions, the false positive rate matters most.
Statistics81 / 246
Module 7 · Conditional probability and Bayes' theorem
Ignoring the base rate is the classic mistake
The prior, how common something is before the evidence, is called the base rate. Ignoring it, and reading as if it were , is base rate neglect. It is why screening a whole population for a rare condition produces many false alarms, and why a positive screen is followed by a second, more specific test. A test does not hand you an answer; it updates what you believed before.
Who is tested
Prevalence
P(condition | positive)
Everyone, as a screen
1%
9%
People with symptoms
10%
53%
After one positive test
9.2%
50% after a second positive
QuizInteractive · disabled in the PDF
After a first positive (posterior about 9.2%), you take a second, independent test with the same rates and it is also positive. Which number is your new prior?
After a first positive (posterior about 9.2%), you take a second, independent test with the same rates and it is also positive. Which number is your new prior?
Code challengeInteractive · disabled in the PDF
Finish posterior(prior, sensitivity, falsePositive): the probability of the condition after a positive test, by Bayes’ theorem.
Module 7 · Conditional probability and Bayes' theorem
The prosecutor’s fallacy
A DNA sample from a crime scene matches a suspect, and an expert says only 1 in a million people would match by chance. The prosecutor says: “so there is only a one in a million chance the suspect is innocent.” That swaps the condition: 1 in a million is , not . In a city of 10 million people, about 10 innocent people would match too. If the suspect was found only by searching a DNA database, with no other evidence, the guilty person is one of about 11 matches.
QuizInteractive · disabled in the PDF
What is the prosecutor’s fallacy?
What is the prosecutor’s fallacy?
Statistics83 / 246
Module 7 · Conditional probability and Bayes' theorem
The Monty Hall problem
A game show has three doors: a car behind one, goats behind the other two. You pick door 1. The host, who knows where the car is, always opens a different door with a goat, say door 3, and offers you the switch to door 2. Should you switch? Yes: switching wins 2/3 of the time. Your first pick is right 1/3 of the time, and nothing the host does changes that. In the other 2/3, the car is behind one of the two doors you did not pick, and the host has just shown you which one.
Car is behind
Host opens
Stay with door 1
Switch
Door 1 (chance 1/3)
Door 2 or 3
Win
Lose
Door 2 (chance 1/3)
Door 3
Lose
Win
Door 3 (chance 1/3)
Door 2
Lose
Win
PlaygroundInteractive · disabled in the PDF
C++
1#include<iostream>2#include<random>34intmain(){5 std::mt19937gen(7);6 std::uniform_int_distribution<int>door(0,2);7 std::uniform_real_distribution<double>uniform(0.0,1.0);8int games =10000, stayWins =0, switchWins =0;9for(int g =0; g < games; g++){10int car =door(gen);11int pick =0;12 // The host opens a goat door that is not your pick.13int opened =1;14if(car ==1||(car ==0&&uniform(gen)<0.5)) opened =2;15int other =3- pick - opened;16if(pick == car) stayWins++;17if(other == car) switchWins++;18}19 std::cout <<"stay wins: "<<double(stayWins)/ games <<"\n";20 std::cout <<"switch wins: "<<double(switchWins)/ games <<"\n";21}
Doors are 0, 1 and 2. When the car is behind your pick, the host chooses either goat at random. Change the seed, 7, for another 10 000 games.
QuizInteractive · disabled in the PDF
Change the rules: the host does not know where the car is, opens one of the other two doors at random, and it happens to show a goat. Now what is your chance of winning if you switch?
Change the rules: the host does not know where the car is, opens one of the other two doors at random, and it happens to show a goat. Now what is your chance of winning if you switch?
Statistics84 / 246
Module 7 · Conditional probability and Bayes' theorem
Practice problems
ProblemInteractive · disabled in the PDF
A shop buys 50% of its bulbs from supplier A, 30% from B and 20% from C. Of their bulbs, 1%, 3% and 5% are faulty. What share of all the bulbs are faulty? A bulb is faulty: what is the probability that it came from C? From A?
ProblemInteractive · disabled in the PDF
A condition affects 2% of people. A test for it is positive for 95% of those who have it, and for 5% of those who do not. Out of 10 000 people tested, how many true positives and how many false positives do you expect? What is ?
ProblemInteractive · disabled in the PDF
Take the same test (positive for 95% of people with the condition and 5% without), where 2% have the condition. Someone tests positive, so their chance is now , and then takes a second, independent test, also positive. What is their chance of having the condition now? And for someone who tests negative once, what is the chance they do not have it?
ProblemInteractive · disabled in the PDF
The chance of rain today is 0.3. If it rains today, the chance of rain tomorrow is 0.6; if it does not, the chance is 0.2. What is the probability that it rains on both days? That it rains tomorrow? If it rains tomorrow, what is the probability that it also rained today?
Statistics85 / 246
Module 7 · Conditional probability and Bayes' theorem
Recap
: the chance of in the world where happened.
and are different numbers.
General multiplication: ; independence means .
Tree diagrams: multiply along paths, add the paths of an event.
Total probability: .
Bayes: posterior = likelihood × prior ÷ evidence.
Base rates matter: a positive test for a rare condition is often a false alarm.
The prosecutor’s fallacy swaps the condition; Monty Hall shows how information is produced matters.
FlashcardsInteractive · disabled in the PDF
P(A | B)
The probability of A given that B happened: P(A and B) / P(B).
Independence, precisely
P(A | B) = P(A): knowing B does not change the chance of A.
Law of total probability
P(D) = Σ P(Bⱼ) P(D | Bⱼ) over a partition B₁ … Bₖ.
Bayes’ theorem
P(B | D) = P(D | B) P(B) / P(D).
Prior, likelihood, posterior
Belief before the evidence; chance of the evidence given the hypothesis; belief after.
Sensitivity
P(positive test | has the condition).
Base rate neglect
Ignoring how common something is, and reading P(+ | sick) as P(sick | +).
Prosecutor’s fallacy
Treating P(evidence | innocent) as P(innocent | evidence).
Monty Hall
Switching wins 2/3, because the host knowingly avoids the car.
Module 8: Random variables and expected value
Statistics86 / 246
Module 8 · Random variables and expected value
A random variable is a number decided by chance
Often you care about a number that an experiment produces, not the outcome itself: the number of heads in three tosses, the total of two dice, the money you win in a game. A random variable is a rule that gives a number to every outcome. It is written with a capital letter, , and the values it takes with small letters, . A random variable with separate values you can list (0, 1, 2, 3) is discrete; one that can take any value in a range, such as a waiting time, is continuous and comes in a later module.
Outcome of 3 tosses
HHH
HHT
HTH
THH
HTT
THT
TTH
TTT
= number of heads
3
2
2
2
1
1
1
0
Random variable
A number given to each outcome of a random experiment, written .
Discrete
Takes separate values you can list, usually counts.
Continuous
Takes any value in a range: times, lengths, masses.
Statistics87 / 246
Module 8 · Random variables and expected value
A probability mass function lists the chances
The distribution of a discrete random variable is its probability mass function (pmf): each value and its probability . From the table, three tosses give 3 heads in 1 of 8 equally likely outcomes, 2 heads in 3, 1 head in 3, and 0 heads in 1. Like any probability model, the chances are all at least 0 and add up to 1.
The pmf of the number of heads in 3 fair tosses.
QuizInteractive · disabled in the PDF
A random variable takes the values 1, 2 and 3 with and . What is , and ?
A random variable takes the values 1, 2 and 3 with and . What is , and ?
ProblemInteractive · disabled in the PDF
The number of children in a household takes the values 0, 1, 2, 3 and 4 with probabilities 0.2, 0.3, 0.25, and 0.1. Find and .
Statistics88 / 246
Module 8 · Random variables and expected value
The expected value is the long-run average
The expected value (or mean) of , written or , weights each value by its probability and adds them up. It is the mean of the distribution: if you repeated the experiment many times, the average of the values would settle near . It need not be a value can take: a die’s expected value is 3.5, which no roll shows.
QuizInteractive · disabled in the PDF
A café sells 0, 1 or 2 cakes an hour with probabilities 0.3, 0.5 and 0.2. How many cakes does it expect to sell in an 8-hour day?
A café sells 0, 1 or 2 cakes an hour with probabilities 0.3, 0.5 and 0.2. How many cakes does it expect to sell in an 8-hour day?
Statistics89 / 246
Module 8 · Random variables and expected value
The variance of a random variable
Spread works as for data: the variance of is the expected squared distance from its mean, and the standard deviation is its square root. A shortcut is often easier to compute: the mean of the squares minus the square of the mean.
One roll of a fair die.
Note. There is no here. That correction is for estimating a spread from a sample; here the whole distribution is known, so this is a population variance.
ProblemInteractive · disabled in the PDF
The number of children in a household is 0, 1, 2, 3 or 4, with probabilities 0.2, 0.3, 0.25, 0.15 and 0.1. Find , and the standard deviation .
Statistics90 / 246
Module 8 · Random variables and expected value
Try it: the mean and variance of a distribution
Code challengeInteractive · disabled in the PDF
Finish expectedValue(values, probs): probs[i] is the probability of values[i]. Return the sum of each value times its probability.
C++
1#include<vector>23doubleexpectedValue(const std::vector<double>& values,4const std::vector<double>& probs){5 // TODO: each value times its probability6return0;7}
Find the bugInteractive · disabled in the PDF
This variance gives about −2.92 for a fair die. Which line is wrong?
C++
Code challengeInteractive · disabled in the PDF
Finish variance(values, probs): the variance of the distribution, using or the shortcut.
C++
1#include<vector>23doublevariance(const std::vector<double>& values,4const std::vector<double>& probs){5 // TODO: the mean first, then the squared distances6return0;7}
Statistics91 / 246
Module 8 · Random variables and expected value
Shifting and scaling a random variable
If you multiply a random variable by and add , its mean does the same. Its spread is scaled by , but the shift moves every value equally, so it does not change the spread at all. The variance, being in squared units, is multiplied by .
Daily highs with mean 20 °C and SD 5 °C, converted to Fahrenheit. The +32 moves the mean only.
QuizInteractive · disabled in the PDF
A shop’s daily profit has mean 200 and variance 900 (in coins). Each day 50 coins of rent are paid, and the owner keeps half of what is left: . What are the mean and SD of ?
A shop’s daily profit has mean 200 and variance 900 (in coins). Each day 50 coins of rent are paid, and the owner keeps half of what is left: . What are the mean and SD of ?
Statistics92 / 246
Module 8 · Random variables and expected value
Expected values always add
For any two random variables, the expected value of their sum is the sum of their expected values. Always: they do not need to be independent. This linearity of expectation is one of the most useful facts in probability, because it lets you break a hard count into easy pieces. The trick is the indicator variable: 1 if something happens, 0 if not, whose expected value is just its probability.
An example. guests leave their coats, and the coats are handed back at random. How many guests expect to get their own coat? Let if guest gets their own coat. Each has a chance, so . The total is , so its expected value is , for any . The are not independent (if guest 1 has guest 2’s coat, guest 2 cannot have their own), and it does not matter.
QuizInteractive · disabled in the PDF
You roll 10 dice. What is the expected number of sixes?
You roll 10 dice. What is the expected number of sixes?
Statistics93 / 246
Module 8 · Random variables and expected value
Variances add for independent variables
Variances add too, but only when the variables are independent. Then the spread of a sum grows more slowly than you might think: the SDs do not add, their squares do. The total of dice has mean but SD , so 100 dice have SD about 17, not 171. And a difference has the sum of the variances: subtracting a random amount adds uncertainty, it never cancels it.
SD of the total: 1.708√n
Adding the SDs (wrong)
Mean of the total35
SD of the total5.4
The SD of the total of n dice. Drag n: the real SD (the curve) grows like √n, far below n times one die’s SD (the line).
QuizInteractive · disabled in the PDF
Two independent machines fill bags: one with SD 3 g, the other with SD 4 g. What is the SD of the difference between a bag from each?
Two independent machines fill bags: one with SD 3 g, the other with SD 4 g. What is the SD of the difference between a bag from each?
Going deeper
For variables that are not independent, a term for how they move together appears: , with the covariance from the module on two variables. Positively related risks add up to more than independent ones, which is why a portfolio of shares that rise and fall together is riskier than one of unrelated shares, and why diversification works only for risks that are not correlated.
Statistics94 / 246
Module 8 · Random variables and expected value
Games and fair bets
A bet is a random variable: your net winnings. It is fair if its expected value is 0, so neither side gains in the long run. Casinos offer bets with a small negative expected value for the player: the house edge. On a European roulette wheel, 18 of the 37 pockets are red. Bet 1 coin on red: win 1 coin with probability 18/37, lose it with probability 19/37.
On average you lose 2.7% of every bet. The green zero pocket is the house’s edge.
E = pw − (1 − p)
Fair at p =0.5
A bet that pays w coins with probability p, and loses your 1 coin otherwise. Drag w: the bet is fair where the line crosses 0.
QuizInteractive · disabled in the PDF
A game: roll a die, and you are paid as many coins as the number shown. What is the fair price to play?
A game: roll a die, and you are paid as many coins as the number shown. What is the fair price to play?
Statistics95 / 246
Module 8 · Random variables and expected value
Expected value is not the whole story
Two offers have the same expected value of 1 coin: A gives you 1 coin for sure; B gives you 100 coins with probability 0.01 and nothing otherwise. Most people prefer A, and that is not irrational: B has SD about 9.95 coins and usually pays nothing. Insurance makes sense for the same reason: its expected value is negative for you (the insurer has costs and profit), but it removes a small chance of a ruinous loss. Report the spread with the mean.
Offer A
1 coin, for sure
E = 1
SD = 0
Offer B
100 coins with probability 0.01
E = 1
SD = √(100 − 1) ≈ 9.95
QuizInteractive · disabled in the PDF
A lottery ticket costs 2 coins and its expected payout is 0.9 coins. Which statement is right?
A lottery ticket costs 2 coins and its expected payout is 0.9 coins. Which statement is right?
Going deeper
The St Petersburg paradox (Daniel Bernoulli, 1738): toss a coin until the first head; if it comes on toss , you win coins. The expected payout is , which is infinite, yet nobody would pay even 100 coins to play. Bernoulli’s answer was that money’s value to you grows more slowly than the amount, and that you should maximise expected utility, an idea that founded decision theory. Another answer: no bank can pay the huge prizes, and capping them makes the expected value small.
Statistics96 / 246
Module 8 · Random variables and expected value
Practice problems
ProblemInteractive · disabled in the PDF
A random variable has mean 12 and standard deviation 3. Let . Find , the standard deviation of , and .
ProblemInteractive · disabled in the PDF
A gift box holds 4 jars of jam. Each jar’s mass has mean 150 g and SD 6 g, independently of the others, and the empty box weighs exactly 80 g. Find the mean and the SD of the full box’s mass. Then find the SD of the difference in mass between two single jars.
g
g
g
ProblemInteractive · disabled in the PDF
A game costs 4 coins. You roll a fair die: a 6 pays 12 coins, a 4 or a 5 pays 3 coins, and anything else pays nothing. Find the expected payout, your expected net winnings per game, and the fair price to play.
coins
coins
coins
ProblemInteractive · disabled in the PDF
A quiz has 12 questions, each with 4 options, and you guess every answer at random. What is the expected number of right answers? If each right answer scores and each wrong one , what is your expected score?
Statistics97 / 246
Module 8 · Random variables and expected value
Recap
A random variable gives a number to each outcome; its pmf lists , adding up to 1.
: the long-run average, not necessarily a possible value.
, never negative.
and .
Expected values always add; indicator variables turn counts into sums of probabilities.
Variances add for independent variables, for sums and differences alike; SDs do not add.
A fair bet has expected winnings 0; the house edge makes casino bets negative.
Expected value ignores risk: report the spread too.
FlashcardsInteractive · disabled in the PDF
Random variable
A number given to each outcome of a random experiment.
Probability mass function
The list of values of a discrete random variable and their probabilities.
Expected value
E[X] = Σ x p(x): the probability-weighted average of the values.
Variance shortcut
Var(X) = E[X²] − (E[X])².
Linearity of expectation
E[X + Y] = E[X] + E[Y], for any random variables, independent or not.
Indicator variable
1 if an event happens, 0 if not; its expected value is the event’s probability.
Var(X − Y) for independent X, Y
Var(X) + Var(Y): uncertainty adds even when you subtract.
Fair bet
A bet whose expected net winnings are 0.
Module 9: Binomial, geometric and Poisson
Statistics98 / 246
Module 9 · Binomial, geometric and Poisson
A Bernoulli trial: success or failure
Some random patterns come up so often that they have names. The simplest is a Bernoulli trial: one experiment with two outcomes, called success (1) and failure (0), with success probability . A coin toss, a free throw, whether a customer buys. “Success” is just the outcome you count, even if it is a defect or an illness. Its mean is , and its variance is , largest at , when the outcome is hardest to guess.
when is 0 or 1, so .
The variance of one Bernoulli trial: zero when the result is certain, largest at p = 0.5.
QuizInteractive · disabled in the PDF
A website visitor buys something with probability 0.1. What is the SD of the Bernoulli variable “buys”?
A website visitor buys something with probability 0.1. What is the SD of the Bernoulli variable “buys”?
Statistics99 / 246
Module 9 · Binomial, geometric and Poisson
The binomial counts successes in n trials
Repeat a Bernoulli trial times and count the successes. The count has a binomial distribution, written , when four conditions hold. A memory aid is BINS: Binary outcomes; Independent trials; a fixed Number of trials; the Same chance each time. Heads in 10 tosses, defective items in a sample of 20, patients who recover out of 50.
QuizInteractive · disabled in the PDF
Which of these counts are binomial?
Which of these counts are binomial?
Statistics100 / 246
Module 9 · Binomial, geometric and Poisson
The binomial formula
What is the chance of exactly successes in trials? Any one particular sequence with successes and failures, such as SSFFF, has probability , by independence. And there are such sequences, one for each choice of which trials succeed. They are disjoint, so add them up.
Five customers, each buying with probability 0.3: the chance that exactly two buy.
QuizInteractive · disabled in the PDF
A fair coin is tossed 10 times. Which is ?
A fair coin is tossed 10 times. Which is ?
ProblemInteractive · disabled in the PDF
Each seed sprouts with probability 0.8, independently of the others. You plant 6. What is the probability that exactly 5 sprout? That all 6 sprout? That at least 5 sprout?
Statistics101 / 246
Module 9 · Binomial, geometric and Poisson
The shape of the binomial
Drag and . With the distribution is symmetric. With small it is skewed right, piled up near 0 with a tail; with large , skewed left. As grows, it spreads out and becomes more bell-shaped whatever is, a first glimpse of the normal curve of the next module.
Mean np3
SD √(np(1 − p))1.449
The binomial pmf: one point per value k. The line marks the mean, np.
Statistics102 / 246
Module 9 · Binomial, geometric and Poisson
Mean np, variance np(1 − p)
You could compute the mean from the formula, but linearity makes it one line. A binomial count is a sum of independent Bernoulli indicators, one per trial, each with mean and variance . Expected values add, and for independent trials variances add too.
QuizInteractive · disabled in the PDF
A basketball player makes 80% of free throws, independently. In 10 throws, what are the mean and SD of the number made?
A basketball player makes 80% of free throws, independently. In 10 throws, what are the mean and SD of the number made?
Statistics103 / 246
Module 9 · Binomial, geometric and Poisson
Try it: the binomial pmf and cdf
Code challengeInteractive · disabled in the PDF
Finish binomialPmf(n, k, p): the chance of exactly k successes in n trials. A choose function is given.
C++
1#include<cmath>23doublechoose(int n,int k){4if(k <0|| k > n)return0;5double r =1;6for(int i =1; i <= k; i++) r = r *(n - k + i)/ i;7return r;8}910doublebinomialPmf(int n,int k,double p){11 // TODO: sequences, successes, failures12return0;13}
Code challengeInteractive · disabled in the PDF
Finish binomialCdf(n, k, p): the chance of at mostk successes, . binomialPmf is given.
C++
1#include<algorithm>2#include<cmath>34doublebinomialPmf(int n,int k,double p){5double c =1;6for(int i =1; i <= k; i++) c = c *(n - k + i)/ i;7return c * std::pow(p, k)* std::pow(1- p, n - k);8}910doublebinomialCdf(int n,int k,double p){11 // TODO: add up the pmf12returnbinomialPmf(n, k, p);13}
Statistics104 / 246
Module 9 · Binomial, geometric and Poisson
The geometric distribution: waiting for a success
Instead of fixing the number of trials, keep going until the first success, and count the trials it takes, the success included. That count has a geometric distribution. To first succeed on trial , you need failures and then a success. On average the wait is trials: a die needs 6 rolls on average to show a six.
Rolls until the first six (p = 1/6). The first roll is always the single most likely, and the tail goes on for ever.
QuizInteractive · disabled in the PDF
You have rolled a die 10 times without a six. What is the expected number of further rolls until the first six?
You have rolled a die 10 times without a six. What is the expected number of further rolls until the first six?
Statistics105 / 246
Module 9 · Binomial, geometric and Poisson
The Poisson distribution counts rare events
How many calls reach a help desk in a minute? How many typos on a page, meteorites a year, goals in a match? These count events that happen independently, one at a time, at a steady average rate (lambda) per interval. Such a count has a Poisson distribution, named after Siméon Denis Poisson. There is no upper limit on the count, and remarkably its mean and its variance are both .
P(X = 0)0.0498
SD √λ1.732
The Poisson pmf. Drag λ: small rates pile up at 0; larger rates spread out and look like a bell.
QuizInteractive · disabled in the PDF
A help desk gets on average 3 calls a minute. What is the chance of a minute with no calls?
A help desk gets on average 3 calls a minute. What is the chance of a minute with no calls?
ProblemInteractive · disabled in the PDF
A shop gets 4 complaints a week on average, at random and independently. What is the probability of exactly 2 complaints in a week? Of no complaints in half a week?
Statistics106 / 246
Module 9 · Binomial, geometric and Poisson
The Poisson is the binomial for rare events
Split a minute into tiny slices, each with a small chance of a call. The number of calls is then . As grows, this binomial gets closer and closer to the Poisson with rate . That is where the Poisson comes from, and it means you can use it for any binomial with large and small : rare defects in big batches, rare side effects in big trials.
The key step: , from the algebra course’s definition of e.
p = λ/n0.25
Binomial with p = λ/n (dark) and Poisson (light). Drag n up: the binomial points settle onto the Poisson ones.
QuizInteractive · disabled in the PDF
A chip has a 1 in 1000 chance of a defect, independently. In a batch of 2000 chips, what is the Poisson approximation to the chance that none are defective?
A chip has a 1 in 1000 chance of a defect, independently. In a batch of 2000 chips, what is the Poisson approximation to the chance that none are defective?
Statistics107 / 246
Module 9 · Binomial, geometric and Poisson
Try it: the Poisson pmf
Code challengeInteractive · disabled in the PDF
Finish poissonPmf(k, lambda): . Build the terms up in a loop, rather than computing and separately, so large k does not overflow.
C++
1#include<cmath>23doublepoissonPmf(int k,double lambda){4double term = std::exp(-lambda); // the k = 0 term5 // TODO: multiply in lambda / i for i = 1 .. k6return term;7}
Statistics108 / 246
Module 9 · Binomial, geometric and Poisson
Which distribution fits
You count…
Distribution
Mean
Variance
One trial: success or not
Bernoulli()
Successes in fixed trials
Binomial()
Trials until the first success
Geometric()
Events in an interval at rate
Poisson()
Overdispersion. A Poisson model forces the variance to equal the mean. Real counts are often overdispersed: their variance is bigger, because the rate itself varies (some days are busier, some pages are written in a hurry). If the sample variance of your counts is much larger than their mean, a Poisson model will understate the uncertainty; the negative binomial distribution is the usual fix.
QuizInteractive · disabled in the PDF
A quality inspector tests bulbs from a production line, one after another, until she finds the first faulty one. Which distribution models the number of bulbs tested?
A quality inspector tests bulbs from a production line, one after another, until she finds the first faulty one. Which distribution models the number of bulbs tested?
Statistics109 / 246
Module 9 · Binomial, geometric and Poisson
Practice problems
ProblemInteractive · disabled in the PDF
A test has 20 multiple-choice questions with 5 options each, and a student guesses every answer. Find the mean and the SD of the number of right answers, and the probability of getting none right.
ProblemInteractive · disabled in the PDF
At a fair, each throw lands a ring on the peg with probability 0.25, independently. What is the probability that the first success comes on the 3rd throw? That you need more than 4 throws? What is the expected number of throws up to and including the first success?
ProblemInteractive · disabled in the PDF
Each letter a firm sends has a 1 in 500 chance of being lost, independently. It sends 1500 letters. Using the Poisson approximation, what is the probability that none are lost? That at most one is lost?
ProblemInteractive · disabled in the PDF
A machine makes 10% defective items, independently. In a sample of 10 items, what is the probability of no defective items? Of exactly one? Of at least two?
Statistics110 / 246
Module 9 · Binomial, geometric and Poisson
Recap
A Bernoulli trial succeeds with probability : mean , variance .
Binomial: successes in independent trials with the same (BINS).
, with mean and variance .
Geometric: trials until the first success, , mean , memoryless.
Poisson: events at a steady rate, , mean = variance = .
Binomial with large and small is close to Poisson with .
In code, build pmfs up term by term to avoid overflow, and check they add up to 1.
FlashcardsInteractive · disabled in the PDF
Bernoulli trial
One trial with two outcomes, success with probability p.
BINS
Binomial conditions: binary, independent, fixed number n, same p.
Binomial pmf
C(n, k) pᵏ (1 − p)ⁿ⁻ᵏ.
Binomial mean and variance
np and np(1 − p).
Geometric distribution
Trials until the first success: (1 − p)ᵏ⁻¹ p, mean 1/p.
Memoryless
The wait still to come does not depend on how long you have waited.
Poisson pmf
λᵏ e^(−λ) / k!: counts of independent events at rate λ.
Poisson limit
B(n, λ/n) approaches Poisson(λ) as n grows.
Cumulative distribution function
P(X ≤ k): the pmf added up to k.
Module 10: Continuous distributions and the normal curve
Statistics111 / 246
Module 10 · Continuous distributions and the normal curve
For continuous variables, probability is area
A waiting time can be 2 minutes, 2.1, 2.13 or 2.1374… With infinitely many possible values, the chance of any one exact value is 0, so a pmf cannot work. Instead, a continuous random variable has a probability density function (pdf) , a curve whose area between and is the probability that lands between them. The curve is never below 0 and its total area is 1. It is the smooth limit of a histogram whose bars have been scaled to have total area 1.
The integral is the area under the curve, from the calculus course. You do not need to compute integrals here: tables and code do it.
f(x)
P(a ≤ X ≤ b)0.5366
A density for waiting times, f(x) = x e^(−x). Drag a and b: the shaded area is the probability of a wait between them.
QuizInteractive · disabled in the PDF
A density curve has height 1.5 at . What does that mean?
A density curve has height 1.5 at . What does that mean?
Statistics112 / 246
Module 10 · Continuous distributions and the normal curve
The uniform distribution: flat
The simplest density is flat. A variable is uniform on if every value in the interval is equally likely: the density is a rectangle of width and height , so its area is 1. A bus that comes every 10 minutes, for someone who arrives at a random moment, gives a wait uniform on . Probabilities are then just widths: the chance of waiting more than 7 minutes is .
P(wait > c)0.3
The wait for a bus every 10 minutes. Drag c: the shaded area is the chance of waiting longer than c.
QuizInteractive · disabled in the PDF
For the bus wait, uniform on minutes, what are the mean and the SD?
For the bus wait, uniform on minutes, what are the mean and the SD?
ProblemInteractive · disabled in the PDF
A train comes every 15 minutes and you arrive at a random moment, so your wait is uniform on minutes. What is the probability that you wait more than 10 minutes? What are the mean and the SD of the wait?
min
min
Statistics113 / 246
Module 10 · Continuous distributions and the normal curve
The exponential distribution: waiting for the next event
If events happen at random at rate per unit of time, so their counts are Poisson, the time until the next one has an exponential distribution. Its density starts at and decays; short waits are most common, long ones possible. The mean wait is : calls at 3 per minute arrive on average 20 seconds apart. Like the geometric, which it is the continuous version of, it is memoryless.
P(wait > c)0.3679
Drag λ (events per minute) and c: the shaded tail is the chance of waiting longer than c minutes.
QuizInteractive · disabled in the PDF
Customers arrive at a rate of 2 per minute (a Poisson process). What is the chance the gap between two customers is more than 1 minute?
Customers arrive at a rate of 2 per minute (a Poisson process). What is the chance the gap between two customers is more than 1 minute?
Statistics114 / 246
Module 10 · Continuous distributions and the normal curve
The normal distribution: the bell curve
The normal distribution (or Gaussian) is the bell curve, symmetric about its mean with spread set by its standard deviation , written . Heights, measurement errors and test scores are often close to normal. The deep reason is that sums and averages of many small independent effects become normal whatever the effects look like: that is the central limit theorem, the subject of the next module. It is why the normal is everywhere in statistics.
Area within μ ± σ0.6827
Drag μ and σ. The shaded band, μ ± σ, always holds about 68% of the area: every normal curve is the same shape, stretched.
Statistics115 / 246
Module 10 · Continuous distributions and the normal curve
The standard normal and its table
Every normal variable becomes the standard normal when you take its z-score, . So one table, or one function, answers every normal question. The cumulative distribution function (cdf) of , written (capital phi), is the area to the left of : . The normal’s area has no formula in elementary functions, which is why it is tabulated, and computed in code by approximations.
Φ(z)0.8413
P(Z > z)0.1587
Drag z: the shaded area is Φ(z) = P(Z ≤ z).
0
0.5
1
1.28
1.645
1.96
2
2.576
3
0.5000
0.6915
0.8413
0.8997
0.9500
0.9750
0.9772
0.9950
0.9987
QuizInteractive · disabled in the PDF
The table only lists positive . How do you find ?
The table only lists positive . How do you find ?
Statistics116 / 246
Module 10 · Continuous distributions and the normal curve
Normal calculations: standardise, then look up
Heights are normal with cm and cm. What share are below 180 cm, and between 165 and 180? Convert each boundary to a z-score, then use . Going the other way, to find the height that only the tallest 10% exceed, find the with , which is 1.2816, and turn it back into centimetres: a percentile.
QuizInteractive · disabled in the PDF
Exam marks are normal with mean 60 and SD 12. A grade A goes to marks above 84. About what share of students get an A?
Exam marks are normal with mean 60 and SD 12. A grade A goes to marks above 84. About what share of students get an A?
ProblemInteractive · disabled in the PDF
Bottles are filled with a volume that is normal with mean 500 ml and SD 4 ml. Using the table of , what share of bottles (as a decimal) hold less than 508 ml? Between 498 and 504 ml? Above what volume are the fullest 5% of bottles?
ml
Statistics117 / 246
Module 10 · Continuous distributions and the normal curve
Try it: normal probabilities in code
Code challengeInteractive · disabled in the PDF
Finish normalBetween(a, b, mu, sigma): the probability that a normal variable with mean mu and SD sigma lands between a and b. phi(z), the standard normal cdf, is given.
C++
1#include<cmath>23// The standard normal cdf, from <cmath>'s error function.4doublephi(double z){5return0.5*(1+ std::erf(z / std::sqrt(2.0)));6}78doublenormalBetween(double a,double b,double mu,double sigma){9 // TODO: standardise a and b first10returnphi(b)-phi(a);11}
Code challengeInteractive · disabled in the PDF
Finish area(f, a, b, n): approximate the area under f from a to b with the trapezoid rule: split the interval into n equal strips of width h, and add up h * (f(left) + f(right)) / 2 for each strip.
C++
1#include<functional>23doublearea(const std::function<double(double)>& f,4double a,double b,int n){5double h =(b - a)/ n;6double total =0;7 // TODO: add the area of each strip8return total;9}
Statistics118 / 246
Module 10 · Continuous distributions and the normal curve
The normal approximation to the binomial
The last module’s binomial looked more and more like a bell as grew. For large , a binomial count is close to normal with the same mean and SD . A common rule of thumb: use it when both and are at least 10. Since the binomial is whole numbers and the normal is continuous, treat each whole number as the interval from to : the continuity correction.
Normal
np15
n(1 − p)15
Binomial points and the normal curve with the same mean and SD. Drag n and p: they match well once np and n(1 − p) are both large.At most 45 heads in 100 tosses. The exact binomial answer is 0.1841 too; without the correction, Φ(−1) = 0.1587.
QuizInteractive · disabled in the PDF
With the continuity correction, which normal probability approximates for ?
With the continuity correction, which normal probability approximates for ?
Statistics119 / 246
Module 10 · Continuous distributions and the normal curve
Checking normality with a QQ plot
Many methods assume data is roughly normal, so check it. A histogram helps, but with little data its shape is noisy. A normal quantile plot (QQ plot) is sharper: sort the data, and plot each value against the z-score where a normal sample of that size would be expected to have it. For values, the -th smallest is matched with . If the data is normal, the points lie near a straight line; curves and bends show skew or heavy tails.
Normal data would lie here
A QQ plot of 10 standardised values. Drag w from 0 (normal data) to 1 (skewed-right, exponential-like data): the points bend away from the line.
QuizInteractive · disabled in the PDF
In a QQ plot, the points follow the line in the middle, but at the right end they rise far above it, and at the left end they sit above it too, bunched up. What does that suggest?
In a QQ plot, the points follow the line in the middle, but at the right end they rise far above it, and at the left end they sit above it too, bunched up. What does that suggest?
Going deeper
Formal tests of normality exist (Shapiro–Wilk is a common one), but they behave awkwardly: with small samples they rarely detect anything, and with large samples they flag tiny departures that do not matter. Many methods, such as those for means, are also robust: they work well for moderately non-normal data once samples are large, thanks to the central limit theorem. Looking at the QQ plot and asking whether the departure matters for your method is usually more useful than a p-value.
Statistics120 / 246
Module 10 · Continuous distributions and the normal curve
Practice problems
ProblemInteractive · disabled in the PDF
Calls reach a help line at random, at a rate of 4 an hour. What is the probability of waiting more than 30 minutes for the next call? What is the mean wait, in minutes? What is the probability that the next call comes within 15 minutes?
min
ProblemInteractive · disabled in the PDF
Test scores are normal with mean 100 and SD 15. Above what score are the top 2.5%? What share of people (as a decimal) score above 130? Between 85 and 115?
ProblemInteractive · disabled in the PDF
A fair coin is tossed 100 times. Using the normal approximation with the continuity correction, find the probability of at most 52 heads, and of between 48 and 52 heads (both included).
ProblemInteractive · disabled in the PDF
A random variable has the density for , and 0 elsewhere: a triangle. Find , , and the median , the value with .
Statistics121 / 246
Module 10 · Continuous distributions and the normal curve
Recap
A continuous variable has a density ; probabilities are areas under it; .
Uniform on : flat, mean , variance .
Exponential with rate : waits between Poisson events, , mean .
Normal : the bell curve; sums of many small effects are close to it.
Standardise with , then use ; use symmetry for negative .
Percentiles go the other way: .
B() is close to N(, ) when and are at least 10; correct by ±0.5.
A QQ plot that is straight suggests normal data; bends show skew or heavy tails.
FlashcardsInteractive · disabled in the PDF
Probability density function
A curve whose area over an interval is the probability of landing in it.
Why is P(X = 2) = 0 for a continuous X?
A single point has no width, so the area above it is 0.
Uniform variance
(b − a)² / 12.
Exponential distribution
Waiting time at rate λ: P(X > t) = e^(−λt), mean 1/λ, memoryless.
Standard normal
N(0, 1), the normal with mean 0 and SD 1; any normal becomes it via z-scores.
Φ(z)
The standard normal cdf: the area to the left of z.
Φ(1.96)
0.975: 95% of a normal lies within 1.96 SDs of the mean.
Continuity correction
Treat whole number k as the interval [k − 0.5, k + 0.5] when approximating with the normal.
QQ plot
Sorted data against normal quantiles: a straight line suggests normal data.
Module 11: Sampling and the central limit theorem
Statistics122 / 246
Module 11 · Sampling and the central limit theorem
You study a sample to learn about a population
You want to know the average wait at a coffee shop, or the share of a website’s visitors who sign up. Asking everyone is usually impossible, so you measure a sample: a small group taken from the whole population. A number that describes the population, such as its true mean , is a parameter. You almost never know it. A number worked out from the sample, such as its mean , is a statistic, and you use it to estimate the parameter.
Population (parameter)
Sample (statistic)
Mean
Standard deviation
Proportion
Size
Population
Everyone or everything you want to learn about.
Sample
The part of the population you actually measure.
Parameter
A fixed, usually unknown, number describing the population.
Statistic
A number computed from a sample. It changes from sample to sample.
QuizInteractive · disabled in the PDF
A school has 2000 pupils. You pick 50 of them and find their mean exam score is 68. Which is the parameter?
A school has 2000 pupils. You pick 50 of them and find their mean exam score is 68. Which is the parameter?
Statistics123 / 246
Module 11 · Sampling and the central limit theorem
Random sampling gives every member a fair chance
How you choose the sample matters more than how big it is. In a simple random sample every group of members is equally likely to be the one chosen, as if you drew names from a hat. Chance, not you, decides who is in, so no kind of member is favoured. Other designs keep the randomness but add structure.
Method
How
Good for
Simple random
Draw members at random from a full list
The baseline every other method is compared to
Stratified
Split into groups (strata) that differ, e.g. year groups; draw randomly within each
Making sure every group is represented; often more precise
Cluster
Split into ready-made groups, e.g. classrooms; pick a few groups at random and measure everyone in them
Cheap when members are spread out; usually less precise
Systematic
Take every -th member of a list from a random start
Quick, if the list has no repeating pattern
QuizInteractive · disabled in the PDF
A city picks 12 of its 300 bus routes at random and surveys every passenger on those 12 routes one morning. What design is this?
A city picks 12 of its 300 bus routes at random and surveys every passenger on those 12 routes one morning. What design is this?
Going deeper
Stratifying helps most when the strata differ a lot from each other and little inside. The overall estimate is a weighted average of the strata’s estimates, each weighted by its share of the population, and its variance only has the within-stratum spread in it. Clustering is the opposite: when members of a cluster are alike (a high intraclass correlation), each extra member of a cluster adds little information, and the effective sample size is closer to the number of clusters than to the number of people.
Statistics124 / 246
Module 11 · Sampling and the central limit theorem
A biased method misses the same way every time
A method is biased when its estimates are off in one direction on average, not just by chance. A bigger sample does not fix bias: it only gives you a more precise wrong answer. Three common sources:
Convenience sampling: measuring whoever is easy to reach. Surveying the coffee shop’s waits only at 3 pm misses the morning rush.
Voluntary response: people choose to answer. Those with strong feelings reply more, so online star ratings pile up at 1 and 5.
Non-response and undercoverage: some chosen people never answer, or the list you sample from leaves some out. A phone survey misses people without a phone.
Biased
Ask the first 500 people who visit the help page if they like the site
Weigh the plants nearest the path
Unbiased
Show the question to 500 visitors chosen at random from all visits
Number every plant, and weigh those whose numbers a random generator picks
QuizInteractive · disabled in the PDF
A magazine asks readers to mail in their opinion and gets 50 000 replies. A pollster asks 1000 people chosen at random. Which estimate of national opinion should you trust more?
A magazine asks readers to mail in their opinion and gets 50 000 replies. A pollster asks 1000 people chosen at random. Which estimate of national opinion should you trust more?
Statistics125 / 246
Module 11 · Sampling and the central limit theorem
A statistic has a distribution of its own
Take a sample, work out . Take another sample: you get a different . This is sampling variability. If you could take every possible sample of size and plot their means, you would get the sampling distribution of . It is the key idea of statistical inference: it tells you how far a statistic tends to land from the parameter.
Small example. The population is the faces of a fair die, 1 to 6, each equally likely, with . Roll it twice and average: 36 equally likely pairs give means from 1 to 6. The middle values come up more often, because more pairs average to them.
One roll is flat, but the mean of two rolls already piles up around 3.5: 6 of the 36 pairs average exactly 3.5.
QuizInteractive · disabled in the PDF
What is the mean of this sampling distribution, the average of all 36 possible two-roll means?
What is the mean of this sampling distribution, the average of all 36 possible two-roll means?
Statistics126 / 246
Module 11 · Sampling and the central limit theorem
The standard error measures how much a statistic wobbles
The spread of a sampling distribution has its own name: the standard error (SE). For the mean of independent values from a population with standard deviation :
Averaging cancels out highs against lows, so means vary less than single values, by a factor of .Exam scores: single pupils vary by about 12 points, but the mean of 36 pupils varies by only about 2.
One pupil (σ = 12)
Mean of n pupils
SE = 12/√n6
Drag n: the sample mean’s distribution narrows like 1/√n. Going from 4 to 16 halves it; going from 16 to 64 halves it again.
Fill the blanksInteractive · disabled in the PDF
Complete the standard error of a mean, given the population standard deviation sigma and sample size n.
C++
1double se = sigma / std::();
ProblemInteractive · disabled in the PDF
Resting heart rates of adults have a standard deviation of beats per minute. What is the standard error of the mean of a random sample of 16 adults? How many adults would you need for a standard error of 1.5 beats per minute?
beats per minute
adults
Going deeper
Where comes from: for independent values the variances add, so . Dividing the sum by divides the variance by , giving , and the standard deviation is its square root, . Independence is doing the work: if the values move together (pupils in the same class, days in the same week), the SE is larger than this formula says.
When you sample a large share of a finite population without replacement, the SE is a little smaller: multiply by the finite population correction . It is close to 1 when the sample is under about 10% of the population, which is why it is usually left out.
Statistics127 / 246
Module 11 · Sampling and the central limit theorem
The law of large numbers: averages settle down
The law of large numbers says that as grows, the sample mean gets as close to as you like, with probability approaching 1. Roll a die 10 times and the average might be 2.9; roll it 10 000 times and it will be very near 3.5. The SE formula says how fast: the typical miss shrinks like .
μ = 3.5
μ + 2σ/√n
μ − 2σ/√n
For a die (σ ≈ 1.71), about 95% of runs of n rolls have their mean inside this band, μ ± 2σ/√n. It narrows fast at first, then slowly.
QuizInteractive · disabled in the PDF
A fair coin has come up heads 8 times in a row. By the law of large numbers, what is the chance the next flip is tails?
A fair coin has come up heads 8 times in a row. By the law of large numbers, what is the chance the next flip is tails?
Code challengeInteractive · disabled in the PDF
Write runningMeans(xs), which returns the mean of the first 1, 2, 3, … values of xs, so you can watch an average settle down. For {4, 2, 6, 0} it returns {4, 3, 4, 3}.
Module 11 · Sampling and the central limit theorem
The central limit theorem: means become normal
The law of large numbers says where ends up. The central limit theorem (CLT) says what shape its wobble has: for a large enough , the sampling distribution of is approximately normal, whatever the shape of the population, as long as it has a finite standard deviation.
Mean , standard error , normal shape. The -score is the one from the normal module.
Exact distribution of the mean
Normal with SE = 2/√n
SE = 2/√n2
Coffee-shop waits are very skewed: most are short, a few are long (mean 2 min, σ = 2 min). Drag n: the exact distribution of the mean wait (solid) moves towards the normal curve the CLT predicts (dashed).
QuizInteractive · disabled in the PDF
You take one sample of 100 waits from this skewed population. What does the CLT say is roughly normal?
You take one sample of 100 waits from this skewed population. What does the CLT say is roughly normal?
ProblemInteractive · disabled in the PDF
Coffee-shop waits are skewed, with mean minutes and minutes. You time a random sample of 64 customers. What is the standard error of their mean wait, and roughly what is the probability that the mean wait is more than 2.5 minutes? Use .
min
Going deeper
The exact curve here is a gamma distribution: the sum of independent exponential waits is gamma with shape . Its skewness is , so the asymmetry fades like , the same rate the Berry–Esseen theorem gives in general: the gap between the true distribution of the standardised mean and is at most a constant times , where . Heavy skew or heavy tails make big, which is why “” is a rule of thumb, not a theorem.
Statistics129 / 246
Module 11 · Sampling and the central limit theorem
Simulating a sampling distribution
You can see all of this without any theory: draw many samples on a computer, work out each mean, and look at the means. Computers make pseudo-random numbers: a formula that looks random but is fixed by a starting number, the seed. The same seed gives the same numbers, so a simulation can be repeated exactly. C++ has a good one built in, std::mt19937 (the Mersenne Twister), seeded when you make it; a distribution turns its raw output into the numbers you want, here std::uniform_int_distribution<int> die(1, 6) for die rolls.
PlaygroundInteractive · disabled in the PDF
C++
1#include<cmath>2#include<iostream>3#include<random>4#include<vector>56intmain(){7 std::mt19937gen(42); // the seed8 std::uniform_int_distribution<int>die(1,6);9int n =10; // rolls per sample10int reps =10000; // samples11 std::vector<double> means;12for(int r =0; r < reps; r++){13int total =0;14for(int i =0; i < n; i++) total +=die(gen);15 means.push_back(double(total)/ n);16}17double avg =0, ss =0;18for(double m : means) avg += m / reps;19for(double m : means) ss +=(m - avg)*(m - avg);20double sd = std::sqrt(ss /(reps -1));21 std::cout <<"mean of means "<< avg <<"\n"; // near 3.522 std::cout <<"SD of means "<< sd <<"\n";23 std::cout <<"theory σ/√n "<<1.7078/ std::sqrt(n)<<"\n";24}
Change n to 1, 4, 40: the SD of the means follows σ/√n. Change the seed to get another run. Note double(total) / n: total / n would cut every mean down to a whole number.
Put in orderInteractive · disabled in the PDF
Put the steps of simulating the sampling distribution of a mean in order.
1.Draw a random sample of values
2.Summarise the kept means: their average, SD and shape
3.Repeat the draw-and-average many thousands of times
4.Choose a population to draw from and a sample size
5.Work out the sample mean and keep it
Code challengeInteractive · disabled in the PDF
In practice you don’t know , so you estimate the SE from the sample: , where is the sample standard deviation (dividing by ). Write standardError(xs).
C++
1#include<cmath>2#include<vector>34doublestandardError(const std::vector<double>& xs){5int n = xs.size();6 // TODO: the sample SD s, then s / √n7return0;8}
Statistics130 / 246
Module 11 · Sampling and the central limit theorem
When the normal approximation can be trusted
The CLT is an approximation, and it rests on assumptions. Check them before you lean on it:
Random: the data come from a random sample or a randomised experiment. Without it, no formula rescues you from bias.
Independent: one value doesn’t affect another. When sampling without replacement, keep below about 10% of the population.
Large enough: a nearly symmetric population is fine with small ; a skewed one needs more (30 is a common rule of thumb; very skewed data need far more).
Finite spread: the population must have a finite . Some heavy-tailed distributions don’t, and their means never settle.
When averaging doesn’t help. The Cauchy distribution has tails so heavy that it has no mean and no variance. The average of Cauchy values has exactly the same distribution as one value, for every : the law of large numbers and the CLT both fail. Real data with occasional enormous values (file sizes, city populations, insurance claims) behave in between, so their sample means converge, but slowly.
QuizInteractive · disabled in the PDF
Which sample is the CLT least likely to describe well, for the sampling distribution of the mean?
Which sample is the CLT least likely to describe well, for the sampling distribution of the mean?
Statistics131 / 246
Module 11 · Sampling and the central limit theorem
Practice problems
Work these on paper, then type your answers: a number, or an exact value such as 5/18 or sqrt(11).
ProblemInteractive · disabled in the PDF
Roll a fair die twice and take the mean of the two rolls. Using the 36 equally likely pairs, what is the probability that the mean is at least 4.5? What is the probability that it is exactly 3.5?
ProblemInteractive · disabled in the PDF
Five tomato plants measure 4, 7, 7, 9 and 13 cm. Find the sample mean, the sample standard deviation (dividing by ) and the estimated standard error of the mean, .
cm
cm
cm
ProblemInteractive · disabled in the PDF
One roll of a fair die has mean and variance . You roll it 105 times and take the mean. What is the standard error of that mean? Between which two values do about 95% of such means fall, using ?
ProblemInteractive · disabled in the PDF
A lift’s sign says 12 people or 960 kg. Adult weights have mean 75 kg and standard deviation 12 kg. Twelve adults chosen at random get in. Find the standard error of their mean weight, the -score of the mean weight that makes the total exactly 960 kg, and the probability that the total is over 960 kg. Treat the mean as normal and use .
kg
Statistics132 / 246
Module 11 · Sampling and the central limit theorem
Recap
A statistic (, ) estimates a parameter (, ) and varies from sample to sample.
Random sampling (simple, stratified, cluster) avoids bias; a bigger biased sample is still biased.
The sampling distribution of is centred on , with standard error , estimated by .
Law of large numbers: approaches as grows. Four times the data halves the SE.
Central limit theorem: for large , is roughly normal whatever the population’s shape, given independence and finite .
Simulation with a seeded generator shows all of this, and is repeatable. Next: turning the SE into a confidence interval.
FlashcardsInteractive · disabled in the PDF
Parameter or statistic: the mean of your sample?
A statistic, . The population mean is the parameter.
Stratified vs cluster sampling
Stratified: some members from every group. Cluster: all members of a few random groups.
Sampling distribution
The distribution of a statistic over all possible samples of the same size.
Standard error of the mean
, estimated by : how much typically misses .
Law of large numbers
As grows, gets arbitrarily close to .
Central limit theorem
For large , is approximately , whatever the population’s shape.
Does a bigger sample fix bias?
No. It shrinks random error only; bias comes from how the sample was chosen.
Module 12: Estimating: confidence intervals
Statistics133 / 246
Module 12 · Estimating: confidence intervals
A point estimate is one best guess
A point estimate is a single number from the sample used as a guess for a parameter: for , for , for . The rule that makes it, such as “average the sample”, is the estimator. A good estimator is unbiased (right on average over samples) and has a small standard error (rarely far off).
The trouble with one number is that it is almost surely wrong. If 25 plants average 42.0 cm, the true mean is not exactly 42.0 cm. What you really want to say is “about 42, give or take something”. A confidence interval puts a number on the “give or take”.
QuizInteractive · disabled in the PDF
Which estimator of the population variance is unbiased, for a simple random sample of size ?
Which estimator of the population variance is unbiased, for a simple random sample of size ?
Statistics134 / 246
Module 12 · Estimating: confidence intervals
An interval is the estimate plus or minus a margin
From the last module: is roughly normal with mean and standard error . In 95% of samples a normal value lands within 1.96 standard deviations of its mean, so in 95% of samples is within of . Turn that round: is within of . That gives the interval, when is known:
Estimate margin of error. The critical value is 1.96 for 95% confidence. The part after is the margin of error.Plant heights, with known from years of past crops.
Confidence interval
A range of plausible values for a parameter, made by a method with a known success rate.
Confidence level
That success rate: the share of samples whose interval contains the parameter, such as 95%.
Critical value
How many standard errors to go out: or .
Margin of error
Critical value times standard error: the half-width of the interval.
ProblemInteractive · disabled in the PDF
A machine fills bags of flour, and from long experience the fill weights have g. A random sample of 16 bags has mean g. Find the standard error, the margin of error and the 95% confidence interval for the mean fill , with .
g
g
g
g
Statistics135 / 246
Module 12 · Estimating: confidence intervals
More confidence costs a wider interval
The confidence level fixes : you go out far enough to catch that share of the standard normal curve’s area in the middle. Asking for more confidence means going further out, so the interval gets wider. Nothing comes free: for a given sample, you trade precision for confidence.
Standard normal
Area between (about)0.95
Drag z: the share of the standard normal between −z and z. At 1.645 it is 90%, at 1.96 it is 95%, at 2.576 it is 99%.
Confidence
90%
95%
99%
1.645
1.960
2.576
QuizInteractive · disabled in the PDF
From the same sample of plants, a 95% interval is (40.04, 43.96) cm. What would the 99% interval be?
From the same sample of plants, a 95% interval is (40.04, 43.96) cm. What would the 99% interval be?
Going deeper
The readout uses a quick approximation of the area, , good to about three decimal places. The exact area is , where is the standard normal’s cumulative distribution function. In general for confidence .
Statistics136 / 246
Module 12 · Estimating: confidence intervals
Ninety-five per cent is about the method, not this interval
Here is the subtle part. is a fixed number; it doesn’t move. What is random is the interval, because it is built from a random sample. 95% confidence means: if you repeated the whole process (sample, compute an interval) many times, about 95% of those intervals would contain . Your one interval either contains it or doesn’t; you don’t know which, but you used a method that works 95% of the time.
PlaygroundInteractive · disabled in the PDF
C++
1#include<cmath>2#include<iostream>3#include<random>45intmain(){6 std::mt19937gen(7);7double mu =42, sigma =5, z =1.96;8int n =25, reps =1000, hits =0;9 std::normal_distribution<double>population(mu, sigma);10for(int r =0; r < reps; r++){11double total =0;12for(int i =0; i < n; i++) total +=population(gen);13double mean = total / n;14double margin = z * sigma / std::sqrt(n);15if(mean - margin <= mu && mu <= mean + margin) hits++;16}17 std::cout << hits <<" of "<< reps <<" intervals contain μ\n";18}
Run it: close to 950. Change z to 1.645 and the count drops to about 900. std::normal_distribution<double>(mu, sigma) draws normal values; change the seed, 7, for another thousand samples.
QuizInteractive · disabled in the PDF
A 95% confidence interval for the mean wait at a coffee shop is (3.35, 5.05) minutes. Which statements are correct?
A 95% confidence interval for the mean wait at a coffee shop is (3.35, 5.05) minutes. Which statements are correct?
Statistics137 / 246
Module 12 · Estimating: confidence intervals
When sigma is unknown, use the t distribution
You almost never know , so you plug in the sample’s . But is itself uncertain, especially for small , and the ratio varies more than a normal . It follows a t distribution with degrees of freedom (df): bell-shaped and centred on 0 like the normal, but with heavier tails. As df grows, gets reliable and becomes the normal.
Standard normal
t distribution
Drag the degrees of freedom: with 1 or 2 the tails are much fatter; by 30 the t curve and the normal nearly coincide.
df
1
2
5
10
15
20
30
∞
for 95%
12.706
4.303
2.571
2.228
2.131
2.086
2.042
1.960
QuizInteractive · disabled in the PDF
Why is bigger than 1.96 for a 95% interval from a small sample?
Why is bigger than 1.96 for a 95% interval from a small sample?
Going deeper
The density is for degrees of freedom. It is exact when the population is normal (W. S. Gosset found it in 1908, publishing as “Student” while testing barley at a brewery). For other populations the CLT makes it approximately right for moderate . With it is the Cauchy distribution from the last module, which has no mean.
Statistics138 / 246
Module 12 · Estimating: confidence intervals
The t interval for a mean
The everyday interval for a mean: the sample’s own , and with degrees of freedom.Waits at a coffee shop, timed for 16 random customers.
Find the bugInteractive · disabled in the PDF
This margin of error comes out far too small. Which line is wrong?
C++
Code challengeInteractive · disabled in the PDF
Write tInterval(xs, tStar), which returns the confidence interval for the mean as a pair {low, high}: , with dividing by . The caller looks up tStar.
C++
1#include<cmath>2#include<utility>3#include<vector>45std::pair<double,double>tInterval(const std::vector<double>& xs,6double tStar){7 // TODO: mean, s, SE, then mean ± tStar × SE8return{0,0};9}
ProblemInteractive · disabled in the PDF
Nine phone batteries last a mean of hours, with standard deviation hours. How many degrees of freedom does the t interval use? Find the 95% confidence interval for the mean battery life, using .
hours
hours
Statistics139 / 246
Module 12 · Estimating: confidence intervals
An interval for a proportion
For a yes/no question, the statistic is the sample proportion . By the CLT (a proportion is a mean of 0s and 1s) it is roughly normal with standard error . You don’t know , so you plug in :
Trust it when there are at least 10 successes and 10 failures: and .A website: 120 of 1500 randomly chosen visitors signed up. The sign-up rate is 6.6% to 9.4%.
Code challengeInteractive · disabled in the PDF
Write proportionInterval(successes, n, zStar), returning the pair {low, high} for .
C++
1#include<cmath>2#include<utility>34std::pair<double,double>proportionInterval(int successes,int n,5double zStar){6 // TODO: p-hat, its SE, then p-hat ± zStar × SE7return{0,1};8}
Going deeper
This simple (Wald) interval behaves badly when is near 0 or 1 or is small: with 0 successes it gives the absurd interval , and its true coverage can sit well below 95%. The Wilson interval, which solves for instead of plugging in , is much better and is what good software uses. A quick fix by hand is the plus four interval: add 2 successes and 2 failures, then use the formula above.
Statistics140 / 246
Module 12 · Estimating: confidence intervals
What makes the margin of error shrink
The margin is (critical value) × (spread) / . So three things set it: the confidence level (higher means wider), the spread of the data (more variable means wider), and the sample size (bigger means narrower, but only like ). Notice what is not there: the size of the population. A random sample of 1000 is as precise for a country as for a town.
1.96 √(p(1 − p)/n)
Margin at n = 10000.031
The 95% margin of error for a proportion as the sample grows. Drag p: it is widest at 0.5, which is why polls plan for 0.5.
QuizInteractive · disabled in the PDF
A survey of 400 people has a margin of error of 4.9 percentage points. What would it be with 1600 people?
A survey of 400 people has a margin of error of 4.9 percentage points. What would it be with 1600 people?
Going deeper
The margin of error covers chance only. A poll’s “±3 points” counts only random sampling error. It says nothing about bias: people who refuse to answer, a badly worded question, or a sample list that misses part of the population. In real elections, total error is often about twice the reported margin.
Statistics141 / 246
Module 12 · Estimating: confidence intervals
Choosing the sample size before you collect
Turn the margin formula around to plan a study: pick the margin you can live with, and solve for . You need a guess at (from a pilot study or past data); for a proportion, is the safe choice because it gives the largest . Always round up: rounding down would miss the target.
The second is the first with .Why so many national polls ask about a thousand people: that gives roughly ±3 points.
Code challengeInteractive · disabled in the PDF
Write sampleSize(sigma, margin, zStar): the smallest whole with , that is rounded up.
“95% chance is in this interval.” The 95% describes the method across samples; this interval is fixed once computed.
“95% of the data lie in it.” An interval for a mean is about the mean. Single values spread times wider.
“A 99% interval is better.” It is surer but wider. Choose the level before you look at the data.
“Overlapping intervals mean no difference.” Two 95% intervals can overlap a little while the difference is still clearly non-zero; compare groups with an interval for the difference (a later module).
“The margin covers all error.” Only random sampling error; bias needs a better design, not a wider interval.
QuizInteractive · disabled in the PDF
Twenty independent research teams each compute a correct 95% confidence interval for the same . How many intervals do you expect to miss ?
Twenty independent research teams each compute a correct 95% confidence interval for the same . How many intervals do you expect to miss ?
Statistics143 / 246
Module 12 · Estimating: confidence intervals
Practice problems
Work these on paper, then type your answers. Round only at the end: an interval’s ends need two or three decimal places.
ProblemInteractive · disabled in the PDF
In a random sample of 400 shoppers, 240 say they prefer paying by card. Find the sample proportion, its standard error, and the 95% confidence interval for the proportion of all shoppers who prefer card ().
ProblemInteractive · disabled in the PDF
You want to estimate the mean commuting time in a city to within minutes. A pilot survey suggests minutes. How many commuters do you need for 95% confidence ()? And for 99% ()?
commuters
commuters
ProblemInteractive · disabled in the PDF
A pollster wants a margin of error of 2 percentage points () at 95% confidence (). How many people must she ask if she plans with ? A past poll suggests is near 0.2: how many would she need then?
people
people
Statistics144 / 246
Module 12 · Estimating: confidence intervals
More practice problems
ProblemInteractive · disabled in the PDF
A report gives a 95% confidence interval for a mean of 12.4 to 15.6 kg, made with . What are the sample mean and the standard error? What is the 90% interval from the same data ()?
kg
kg
kg
kg
ProblemInteractive · disabled in the PDF
Fifty independent studies each make a correct 90% confidence interval for their own parameter. How many of the intervals do you expect to miss their parameter? What is the probability that all fifty contain it?
Statistics145 / 246
Module 12 · Estimating: confidence intervals
Recap
An interval is estimate critical value × standard error.
Mean, known: . Unknown (usual): .
Proportion: , with at least 10 successes and 10 failures.
Higher confidence, more spread or fewer data make it wider; four times the data halves it.
Plan , rounded up.
95% is the method’s hit rate over repeated samples, not the chance that this one interval is right.
FlashcardsInteractive · disabled in the PDF
Margin of error
Critical value × standard error: the half-width of the interval.
for 90%, 95%, 99%
1.645, 1.960, 2.576.
When to use instead of
When you estimate by , which is almost always. Use degrees of freedom.
What does 95% confidence mean?
About 95% of intervals made this way, over many samples, contain the parameter.
Sample size for a ±3-point poll
About 1068: , rounded up.
Does population size affect the margin?
Hardly, as long as the sample is a small part of it: only matters.
Module 13: Hypothesis tests and p-values
Statistics146 / 246
Module 13 · Hypothesis tests and p-values
A test asks whether chance alone could explain the data
A coffee shop says the average wait for a drink is 4 minutes. You time 36 customers and the average is 4.6 minutes. Is the shop wrong, or did you just catch a slow morning? Samples vary (that was the lesson of sampling distributions), so a sample mean of 4.6 could come from a true mean of 4. A hypothesis test asks how surprising your data would be if the dull explanation, "nothing is going on", were true.
The logic is like a proof by contradiction, but with probability. Assume the claim. Work out what samples usually look like under that assumption. If your sample is far outside that, the assumption is hard to believe. If it is not, you have no case against it.
Put in orderInteractive · disabled in the PDF
Put the steps of a hypothesis test in order.
1.Compute a test statistic from the data
2.Collect the data
3.State the null and alternative hypotheses
4.Find the p-value: how likely a result this extreme is if the null is true
5.Choose a significance level, such as 0.05
6.Compare the p-value with the significance level and decide
Statistics147 / 246
Module 13 · Hypothesis tests and p-values
The null hypothesis is the boring explanation
The null hypothesis says there is no effect: the claim holds, the coin is fair, the new drug does nothing. The alternative hypothesis is what you suspect instead. For the coffee shop, with the true mean wait in minutes:
The null always contains the equals sign: it is a single, exact value you can compute with.
Null hypothesis
: no effect, no difference. The test assumes it and looks for evidence against it.
Alternative hypothesis
(also written ): what is true if the null is not, such as or .
Parameter
The hypotheses are about the population, , never about the sample mean , which you already know.
QuizInteractive · disabled in the PDF
A website changes its sign-up button. Its old sign-up rate was 10%. You want to know whether the new button changes the rate. Which is the null hypothesis?
A website changes its sign-up button. Its old sign-up rate was 10%. You want to know whether the new button changes the rate. Which is the null hypothesis?
Statistics148 / 246
Module 13 · Hypothesis tests and p-values
A test statistic measures distance in standard errors
To judge whether 4.6 is far from 4, measure the gap in standard errors, the typical size of a sample mean’s wobble. Suppose the population standard deviation is known, minutes. Then , and the z statistic says how many standard errors the sample mean is from the null value :
The sample mean is 2.4 standard errors above 4. By the central limit theorem, if is true, follows (approximately) the standard normal distribution.
Fill the blanksInteractive · disabled in the PDF
Complete the z statistic for a sample mean xBar against the null value mu0.
C++
1double se =/ std::sqrt();2double z =(xBar -)/;
ProblemInteractive · disabled in the PDF
A machine should fill bottles with a mean of 500 ml, and its fills have ml. A random sample of 25 bottles has mean ml. Testing , find the standard error and the statistic.
ml
Statistics149 / 246
Module 13 · Hypothesis tests and p-values
The p-value is how surprising the data would be under the null
The p-value is the probability, assuming is true, of getting a test statistic at least as extreme as the one you got. Small means "this would rarely happen by chance alone". For , extreme means large: . Drag the statistic and watch the tail areas shrink.
z if H0 is true
As extreme or more
One-sided p, P(Z ≥ z)0.008
Two-sided p, P(|Z| ≥ z)0.0161
The curve is the distribution of z if the null is true. The p-value is the area in the tail, or both tails, beyond your statistic.
QuizInteractive · disabled in the PDF
The coffee shop test gives . Which sentence is right?
The coffee shop test gives . Which sentence is right?
Statistics150 / 246
Module 13 · Hypothesis tests and p-values
The significance level is the line you draw in advance
Before the data come in, choose a significance level , often 0.05. If , you reject : the result is called statistically significant. If , you fail to reject . With , you reject the shop’s claim of a 4-minute mean.
Failing to reject is not accepting. A large p-value means the data are consistent with , not that is true. With 5 customers you would fail to reject almost any claim, because tiny samples are vague. "No evidence of an effect" is not "evidence of no effect".
QuizInteractive · disabled in the PDF
A test at gives . What do you conclude?
A test at gives . What do you conclude?
Going deeper
Why 0.05? Ronald Fisher suggested it in the 1920s as a convenient rough guide, not a law. Physicists announcing a new particle use "5 sigma", a one-sided of about , because they run so many searches. Some statisticians have proposed 0.005 for new discoveries. The right level depends on the cost of being wrong.
Statistics151 / 246
Module 13 · Hypothesis tests and p-values
One-sided and two-sided tests
A one-sided test () counts only one tail as extreme. A two-sided test () counts both, so its p-value is twice as big: . Use two-sided unless, before seeing data, only one direction could matter. Picking one-sided after you see which way the data went halves the p-value dishonestly.
Test at α = 0.05
Reject when
Critical value
One-sided,
1.645
One-sided,
−1.645
Two-sided,
±1.96
Code challengeInteractive · disabled in the PDF
Write zTest(xBar, mu0, sigma, n), returning a ZResult with the z statistic and the two-sided p-value. normalCdf(z) is written for you: it gives .
You almost never know . Replace it with the sample standard deviation and you get the one-sample t statistic. As in confidence intervals, estimating adds uncertainty, so the statistic follows a t distribution with degrees of freedom, whose tails are heavier than the normal’s.
The two-sided critical value for 15 degrees of freedom is 2.131, not 1.96. So is not significant at 0.05, though would have been ().
Code challengeInteractive · disabled in the PDF
Write tStatistic(xs, mu0): the one-sample t statistic of the data xs against mu0. Use the sample standard deviation, dividing by .
C++
1#include<cmath>2#include<vector>34doubletStatistic(const std::vector<double>& xs,double mu0){5 // TODO: mean, sample standard deviation, then t6return0;7}
ProblemInteractive · disabled in the PDF
A battery maker claims a mean life of 1200 hours. You test 36 batteries: hours and hours. Find the standard error, the t statistic and its degrees of freedom. (The two-sided critical value at for those degrees of freedom is 2.030.)
hours
Statistics153 / 246
Module 13 · Hypothesis tests and p-values
Two ways to be wrong
A test makes a decision from noisy data, so it can be wrong in two ways. A Type I error rejects a true null: a false alarm. A Type II error fails to reject a false null: a missed effect. The significance level is the Type I error rate you accept: at , when is true you wrongly reject it 5% of the time.
is true
is false
Reject
Type I error, probability
Right: probability , the power
Fail to reject
Right: probability
Type II error, probability
QuizInteractive · disabled in the PDF
A smoke alarm’s null hypothesis is "there is no fire". It stays silent while the kitchen burns. Which error is that?
A smoke alarm’s null hypothesis is "there is no fire". It stays silent while the kitchen burns. Which error is that?
Statistics154 / 246
Module 13 · Hypothesis tests and p-values
Power is the chance of finding an effect that is there
The power of a test is : the probability it rejects when a real effect exists. It depends on the effect’s size (in standard deviations), the sample size and . For a one-sided z-test at 0.05, the statistic is centred at when the effect is real, and you reject when it passes 1.645. Drag and .
z if H0 is true
z if the effect is real
Reject beyond 1.645
Power0.804
Centre, d√n2.5
Power is the area of the right-hand curve beyond the dashed line. A small effect needs a large sample to be seen.
QuizInteractive · disabled in the PDF
Which of these raise the power of a test? Pick all that do.
Which of these raise the power of a test? Pick all that do.
Going deeper
For 80% power at one-sided : , so needs about 25 and about 155. Halving the effect quadruples the sample.
An underpowered study is worse than it looks. It usually misses the effect, and when it does reach significance, it is often because noise happened to inflate the estimate, so published significant results from small studies tend to exaggerate effects. Andrew Gelman calls this a Type M (magnitude) error.
Statistics155 / 246
Module 13 · Hypothesis tests and p-values
Tests and confidence intervals tell the same story
A two-sided test at level rejects exactly when lies outside the confidence interval. For the coffee shop, the 95% interval is :
4 is outside the interval, so the two-sided test rejects at 0.05, matching .
Report the interval. The p-value says only whether 4 is plausible. The interval also says how big the difference might be, 0.11 to 1.09 minutes, which is what someone deciding anything needs.
QuizInteractive · disabled in the PDF
A 95% confidence interval for a website’s mean session length is 3.2 to 5.8 minutes. A two-sided test of at …
A 95% confidence interval for a website’s mean session length is 3.2 to 5.8 minutes. A two-sided test of at …
Statistics156 / 246
Module 13 · Hypothesis tests and p-values
Run enough tests and something will be significant
Each test at has a 5% false-alarm rate when nothing is going on. Run 20 independent tests on pure noise and the chance at least one is "significant" is . P-hacking is trying analyses (more outcomes, subgroups, dropped outliers, stopping when dips below 0.05) until one works, and reporting only that one.
The chance of at least one false alarm, testing only true nulls at 0.05.
PlaygroundInteractive · disabled in the PDF
C++
1#include<iostream>2#include<random>34intmain(){5 std::mt19937gen(42); // a seeded generator: same seed, same numbers6 // When H0 is true, a p-value is equally likely anywhere in 0..1.7 std::uniform_real_distribution<double>pValue(0.0,1.0);8int studies =10000, testsEach =20, fooled =0;9for(int s =0; s < studies; s++){10bool found =false;11for(int k =0; k < testsEach; k++)12if(pValue(gen)<=0.05) found =true;13if(found) fooled++;14}15 std::cout <<"Studies with a \"finding\": "16<<double(fooled)/ studies <<"\n";17}
Change testsEach to 1, 5 or 50, and compare with the bars.
QuizInteractive · disabled in the PDF
A team tests whether 20 colours of sweets cause headaches. Only green gives , and the headline is "Green sweets cause headaches". What is the best response?
A team tests whether 20 colours of sweets cause headaches. Only green gives , and the headline is "Green sweets cause headaches". What is the best response?
Going deeper
In 2016 the American Statistical Association published a statement on p-values. Its points: p-values can indicate how incompatible data are with a model; they do not measure the probability that a hypothesis is true; decisions should not rest on whether passes a threshold; proper inference needs full reporting; a p-value does not measure the size or importance of an effect; and by itself it is not a good measure of evidence. Pre-registering the analysis before seeing the data, covered in the final module, is the main defence against p-hacking.
Statistics157 / 246
Module 13 · Hypothesis tests and p-values
Practice problems
Work these on paper, then type your answers. Where a table value is needed, the question gives it.
ProblemInteractive · disabled in the PDF
A test of gives . Find the p-value against , and against . Use .
ProblemInteractive · disabled in the PDF
For the coffee shop, minutes, minutes and , and the two-sided test of gave . Find the 99% confidence interval for (). Does a two-sided test at reject ?
min
min
ProblemInteractive · disabled in the PDF
A one-sided z-test at rejects when . The true effect is standard deviations and . Where is the statistic centred when the effect is real, and what is the power? What is the power with ? Use and .
Statistics158 / 246
Module 13 · Hypothesis tests and p-values
More practice problems
ProblemInteractive · disabled in the PDF
A lab runs 8 independent tests at , and in fact every null hypothesis is true. What is the probability of at least one significant result? How many false alarms does it expect? What significance level for each test would make the chance of any false alarm exactly 0.05?
ProblemInteractive · disabled in the PDF
A screening programme runs 250 tests at . In 200 of them the null hypothesis is true; in the other 50 there is a real effect, and each of those tests has power 0.9. How many Type I errors and how many Type II errors do you expect? What share of the significant results are real effects?
Statistics159 / 246
Module 13 · Hypothesis tests and p-values
Recap
A test assumes the null (no effect) and asks how surprising the data would be.
A test statistic measures the distance from the null in standard errors: with known , with and degrees of freedom.
The p-value is , not .
Reject when , fixed in advance. Failing to reject is not proof of the null.
Two-sided unless one direction was the only question before the data.
Type I is a false alarm (rate ), Type II a miss (rate ). Power is and grows with and effect size.
A two-sided test rejects exactly when the confidence interval excludes .
Many tests make false alarms likely: decide the analysis first and report everything.
FlashcardsInteractive · disabled in the PDF
Null hypothesis
The no-effect claim the test assumes, with an equals sign: .
p-value
The probability, if is true, of a result at least as extreme as the one observed.
Significance level α
The threshold for rejecting, chosen in advance; also the Type I error rate.
Type I error
Rejecting a true null: a false alarm.
Type II error
Failing to reject a false null: a missed effect.
Power
The probability of rejecting when a given effect is real: .
Two-sided critical value at 0.05
1.96 for z; larger for t with few degrees of freedom (2.131 for 15).
P-hacking
Trying analyses until one gives , and reporting only that one.
Module 14: Comparing groups: t-tests, chi-squared and ANOVA
Statistics160 / 246
Module 14 · Comparing groups: t-tests, chi-squared and ANOVA
A difference in means is only convincing next to the spread
You grow 20 tomato plants with a new fertiliser and 20 without. After six weeks the fertilised ones average 24.5 cm and the others 21.0 cm. Most questions in science and business look like this: two groups, one difference. The last module tested one mean against a fixed number; now both sides are samples, and both wobble.
Without fertiliser
With fertiliser
Difference ÷ spread2
The same gap between the means looks clear when each group is tight, and lost in the noise when each is spread out.
QuizInteractive · disabled in the PDF
Which result is the strongest evidence that the fertiliser works?
Which result is the strongest evidence that the fertiliser works?
Statistics161 / 246
Module 14 · Comparing groups: t-tests, chi-squared and ANOVA
The two-sample t-test
With independent groups, the null is . The variance of a difference of two independent means is the sum of their variances, so the standard error adds the two groups’ squared standard errors. This is Welch’s t-test, the safe default because it does not assume the groups have equal spreads.
Fertilised: , , . Control: , , . At , reject .
Code challengeInteractive · disabled in the PDF
Write welchT(a, b): Welch’s t statistic for the mean of a minus the mean of b. Use sample variances (divide by ).
C++
1#include<cmath>2#include<vector>34doublemean(const std::vector<double>& xs){5double sum =0;6for(double x : xs) sum += x;7return sum / xs.size();8}910doublevariance(const std::vector<double>& xs){11double m =mean(xs), squares =0;12for(double x : xs) squares +=(x - m)*(x - m);13return squares /(xs.size()-1);14}1516doublewelchT(const std::vector<double>& a,17const std::vector<double>& b){18return0; // TODO19}
ProblemInteractive · disabled in the PDF
Two classes sat the same test. Class 1: , , . Class 2: , , . Find the standard error of the difference in means and Welch’s t statistic for class 1 minus class 2.
Going deeper
The Welch–Satterthwaite degrees of freedom: here , between the smaller group’s 19 and the total’s 38.
The older pooled (Student’s) two-sample t-test assumes equal variances, averages them into one and uses degrees of freedom. When the variances and sample sizes are both unequal it can give badly wrong p-values, while Welch’s loses almost nothing when they are equal. Many statisticians now recommend Welch’s always.
Statistics162 / 246
Module 14 · Comparing groups: t-tests, chi-squared and ANOVA
Paired data: test the differences
Six students sit a practice exam, take a revision course, then sit another. The two scores belong to the same person, so the groups are not independent: a strong student scores high both times. A paired t-test takes each student’s difference, after minus before, and runs a one-sample t-test of those differences against 0.
Student
1
2
3
4
5
6
Before
62
70
55
80
68
74
After
66
73
57
85
67
80
Difference
4
3
2
5
−1
6
QuizInteractive · disabled in the PDF
Treating the same scores as two independent groups gives and . Why is the paired test so much stronger?
Treating the same scores as two independent groups gives and . Why is the paired test so much stronger?
Statistics163 / 246
Module 14 · Comparing groups: t-tests, chi-squared and ANOVA
Chi-squared compares counts with what you expected
Not every question is about means. Is a die fair? Roll it 60 times: a fair die gives an expected count of 10 per face. The chi-squared statistic adds up, for each category, the squared gap between the observed count and the expected count , scaled by .
Observed counts in 60 rolls. A fair die would give about 10 of each.
QuizInteractive · disabled in the PDF
A goodness-of-fit test has degrees of freedom, for categories. With and a critical value of 11.07 at , what do you conclude?
A goodness-of-fit test has degrees of freedom, for categories. With and a critical value of 11.07 at , what do you conclude?
ProblemInteractive · disabled in the PDF
A sweet maker says its four colours are equally common. A bag of 200 has 62 red, 45 green, 38 yellow and 55 blue. Find the expected count of each colour, the chi-squared statistic and its degrees of freedom. (The critical value at is 7.81.)
Statistics164 / 246
Module 14 · Comparing groups: t-tests, chi-squared and ANOVA
The chi-squared distribution
If the null is true and every expected count is at least about 5, the statistic approximately follows a chi-squared distribution with degrees of freedom. It is never negative, it is skewed right, and its mean equals its degrees of freedom. So a statistic near its degrees of freedom is ordinary; one far beyond is surprising. Drag the degrees of freedom: 13.4, the dashed line, sits far in the tail for 5.
Chi-squared density
The die’s 13.4
Mean5
Chi-squared densities. The p-value is the area to the right of the statistic.
Code challengeInteractive · disabled in the PDF
Write chiSquared(observed, expected): the sum over the categories of .
C++
1#include<vector>23doublechiSquared(const std::vector<double>& observed,4const std::vector<double>& expected){5double total =0;6 // TODO: add each category's contribution7return total;8}
Statistics165 / 246
Module 14 · Comparing groups: t-tests, chi-squared and ANOVA
Chi-squared for independence in a table
A website shows design A to 200 visitors and design B to 200. A test of independence asks whether signing up is independent of the design. Under the overall sign-up rate, , applies to both, so each cell’s expected count is its row total times its column total, divided by the grand total.
Signed up
Did not
Total
Design A
40 (expected 50)
160 (expected 150)
200
Design B
60 (expected 50)
140 (expected 150)
200
Total
100
300
400
An table has degrees of freedom. The critical value for 1 is 3.84, so design and sign-up look related.
Find the bugInteractive · disabled in the PDF
This works out the expected counts, but they come out wrong. Which line?
C++
Statistics166 / 246
Module 14 · Comparing groups: t-tests, chi-squared and ANOVA
ANOVA compares the spread between groups with the spread within
With three or more groups (three fertilisers, say), analysis of variance (ANOVA) tests : all the means are equal. It compares two estimates of noise. Within groups: how much plants given the same treatment differ. Between groups: how much the group means differ, scaled up by the group size. If is true both measure the same noise, and their ratio is near 1. Drag the gap and the spread.
Group 1
Group 2
Group 3
F = between ÷ within22.5
Three groups of 10, with means −g, 0 and g. F grows with the gap between means and shrinks with the spread inside each group.
QuizInteractive · disabled in the PDF
Why use one ANOVA instead of t-tests on every pair of the three groups?
Why use one ANOVA instead of t-tests on every pair of the three groups?
Statistics167 / 246
Module 14 · Comparing groups: t-tests, chi-squared and ANOVA
Computing the F statistic
groups, values in all, the mean of group , the mean of everything. MS means "mean square".
Code challengeInteractive · disabled in the PDF
Write fStatistic(groups): the one-way ANOVA F statistic for a list of groups, each a std::vector<double>. mean is written for you.
C++
1#include<vector>23doublemean(const std::vector<double>& xs){4double sum =0;5for(double x : xs) sum += x;6return sum / xs.size();7}89doublefStatistic(const std::vector<std::vector<double>>& groups){10int k = groups.size();11 std::vector<double> all;12for(const std::vector<double>& group : groups)13for(double x : group) all.push_back(x);14int n = all.size();15double grand =mean(all);16double between =0; // sum of n_j * (group mean - grand)^217double within =0; // sum of (x - group mean)^218 // TODO19return0;20}
Statistics168 / 246
Module 14 · Comparing groups: t-tests, chi-squared and ANOVA
Significant is not the same as large
A p-value mixes the size of an effect with the amount of data. An effect size measures the size alone. For two means, Cohen’s d is the difference in units of the pooled standard deviation. Rough guides: 0.2 small, 0.5 medium, 0.8 large, though what matters depends on the field.
The fertiliser effect is fairly large: about three quarters of a standard deviation.
Huge samples make tiny effects significant. With 100,000 plants per group and a spread of 4.5 cm, a difference of just 0.1 cm gives and . Real, but too small for any gardener to care. Always report the effect size and its confidence interval beside the p-value.
QuizInteractive · disabled in the PDF
Study A: 100,000 per group, , . Study B: 20 per group, , . Which found the larger effect?
Study A: 100,000 per group, , . Study B: 20 per group, , . Which found the larger effect?
Statistics169 / 246
Module 14 · Comparing groups: t-tests, chi-squared and ANOVA
Many comparisons need a stricter bar
After a significant ANOVA you want to know which groups differ. With 5 groups there are pairs, and 10 tests at 0.05 have about a 40% chance of a false alarm. The Bonferroni correction tests each of comparisons at , which keeps the chance of any false alarm, the family-wise error rate, at or below .
QuizInteractive · disabled in the PDF
You compare 4 groups pairwise (6 pairs), using Bonferroni at an overall . One pair gives . Is it significant?
You compare 4 groups pairwise (6 pairs), using Bonferroni at an overall . One pair gives . Is it significant?
Put in orderInteractive · disabled in the PDF
Put a careful comparison of several fertilisers in order.
1.Report effect sizes and confidence intervals for the differences
2.Decide the groups, the outcome and the tests before growing anything
3.Grow the plants and measure them
4.Run one ANOVA on all the groups
5.If it is significant, compare pairs with a correction such as Bonferroni
Going deeper
Holm’s method is uniformly better than Bonferroni and as safe: sort the p-values, test the smallest at , the next at , and so on, stopping at the first that fails. Tukey’s HSD is built for all pairwise comparisons after ANOVA. With thousands of tests (genes, say), researchers often control the false discovery rate instead, the expected share of false alarms among the results called significant, with the Benjamini–Hochberg procedure. Permutation tests, in a later module, give another route that needs fewer assumptions.
Statistics170 / 246
Module 14 · Comparing groups: t-tests, chi-squared and ANOVA
Practice problems
Work these on paper, then type your answers. Each one starts by choosing the right test: paired, chi-squared or ANOVA.
ProblemInteractive · disabled in the PDF
Five runners each ran 400 m before and after a training plan. Times in seconds, before: 62, 58, 65, 60, 70; after: 59, 53, 64, 56, 68. Using the improvements (before minus after), find the mean improvement , its standard deviation and the paired t statistic.
s
s
ProblemInteractive · disabled in the PDF
100 patients with back pain were split at random: 50 did a stretching programme and 30 of them improved; 50 had usual care and 20 of them improved. If improving is independent of the group, what is the expected number of improved patients in the stretching group? Find the chi-squared statistic and its degrees of freedom.
ProblemInteractive · disabled in the PDF
Three fertilisers were each given to 4 plants. Growth in cm, A: 3, 5, 4, 4; B: 6, 7, 5, 6; C: 8, 7, 9, 8. Find the mean square between groups (MSB), the mean square within groups (MSW) and .
Statistics171 / 246
Module 14 · Comparing groups: t-tests, chi-squared and ANOVA
More practice problems
ProblemInteractive · disabled in the PDF
Two groups of 10 pupils learned with different methods. Group 1 scored a mean of 52 with ; group 2 scored a mean of 47 with . Find the pooled standard deviation and Cohen’s .
ProblemInteractive · disabled in the PDF
After a significant ANOVA on 6 groups, you compare every pair, using Bonferroni at an overall . How many comparisons are there, and at what level is each tested? One pair gives : what is its Bonferroni-adjusted p-value (the p-value times the number of comparisons)?
Statistics172 / 246
Module 14 · Comparing groups: t-tests, chi-squared and ANOVA
Recap
Two independent means: Welch’s t, with .
Paired data (before and after, the same person twice): a one-sample t-test on the differences.
Counts against a model: chi-squared goodness of fit, , with degrees of freedom.
Two categorical variables: chi-squared independence, expected = row × column ÷ total, degrees of freedom.
Three or more means: ANOVA’s = between-group variance ÷ within-group variance; near 1 under .
Report an effect size such as Cohen’s : significance depends on sample size, effect size does not.
Many comparisons inflate false alarms: correct with Bonferroni or Holm.
FlashcardsInteractive · disabled in the PDF
Welch’s t-test
A two-sample t-test that does not assume equal variances: the safe default.
Paired t-test
A one-sample t-test on the differences within each pair.
Expected count
What a cell would hold on average if were true.
Chi-squared statistic
, over all the cells.
Degrees of freedom for an r × c table
.
F statistic
Mean square between groups ÷ mean square within groups.
Cohen’s d
The difference in means divided by the pooled standard deviation.
Bonferroni correction
Test each of comparisons at .
Family-wise error rate
The chance of at least one false alarm across a set of tests.
Module 15: Linear regression
Statistics173 / 246
Module 15 · Linear regression
A line that predicts one variable from another
Earlier you measured how strongly two variables move together with the correlation . Regression goes one step further: it draws the line that predicts one variable from the other. Five students wrote down how many hours they studied and the score they got. You want a rule like "each extra hour is worth about so many points".
Student
Hours studied,
Exam score,
A
1
51
B
2
54
C
3
62
D
4
70
E
5
73
The fitted line: ("y-hat") is the predicted score, the intercept and the slope.
Response
The variable you predict, : here the score. Also called the outcome.
Predictor
The variable you predict from, : here the hours. Also called the explanatory variable.
Fitted value
The line’s prediction for a point, .
Residual
What the line missed by: , actual minus predicted.
Statistics174 / 246
Module 15 · Linear regression
The best line makes the squared misses smallest
Any line makes some mistakes. Each residual is the vertical gap between a point and the line: positive when the point is above, negative when below. To score a line, square every residual (so misses above and below both count, and big misses count a lot) and add them up. That total is the sum of squared errors, SSE. The least squares line is the one with the smallest SSE.
ŷ = b₀ + b₁x
SSE50
Drag the intercept and the slope. The arrows are the residuals. The smallest SSE you can reach is 10, at intercept 44 and slope 6.
QuizInteractive · disabled in the PDF
Why add up the squared residuals instead of the residuals themselves?
Why add up the squared residuals instead of the residuals themselves?
Statistics175 / 246
Module 15 · Linear regression
The least squares formulas
Calculus finds the slope and intercept that make SSE smallest (set its two derivatives to 0), and the answer is short. Write for the sum of squared deviations of from its mean, and for the sum of products of deviations. The slope is their ratio, and the line always passes through the point of means .
For the study data, and . The deviations of are and of are .
Each extra hour of study goes with 6 more points, on average.
Fill the blanksInteractive · disabled in the PDF
Finish the last two lines: the slope, then the intercept from the means.
A small shop ran online adverts for 1, 2, 3, 4 and 5 hours on five days () and sold 3, 7, 5, 11 and 9 items (). Find the least squares slope and intercept .
items per hour
items
Going deeper
The slope is also : the correlation, rescaled into the units of per unit of . So the slope has the same sign as , and it is 0 exactly when is 0. Swapping and does not give the inverse slope: regressing hours on score gives , a different line, unless .
Statistics176 / 246
Module 15 · Linear regression
Fitting the line in code
Now compute it. Two passes over the data: one for the means, one for the sums of deviations.
Code challengeInteractive · disabled in the PDF
Write fitLine(xs, ys), returning the Line (its intercept and slope) of the least squares line. Use and .
C++
1#include<vector>23structLine{4double intercept;5double slope;6};78LinefitLine(const std::vector<double>& xs,9const std::vector<double>& ys){10int n = xs.size();11 // TODO: the means, then sxy and sxx12double slope =0;13double intercept =0;14return{intercept, slope};15}
Statistics177 / 246
Module 15 · Linear regression
Reading the slope and the intercept
Read the slope in the units of the data: "for each extra hour studied, the predicted score is 6 points higher". It describes the average change across students, not a promise for any one student, and on observational data it is an association, not proof that studying causes the gain. The intercept is the prediction at : 44 points for no study. It only means something when is a sensible value inside the data.
An intercept outside the data. A line for house price against floor area, fitted on houses of 60 to 200 square metres, has an intercept that is the "price" of a house with no floor. It may even be negative. That is not a finding; it is just where the line crosses the axis, far from any data.
QuizInteractive · disabled in the PDF
A fit of weekly sales (in units) on advertising spend (in thousands of euros) gives . Which reading is right?
A fit of weekly sales (in units) on advertising spend (in thousands of euros) gives . Which reading is right?
Statistics178 / 246
Module 15 · Linear regression
R squared: the share of the variation the line explains
How good is the line? Start from how much the scores vary around their mean: the total sum of squares, SST. The line explains part of it (SSR, the variation of the fitted values around the mean) and misses the rest (SSE). For least squares they add up exactly. is the share explained.
The residuals come from : the predictions are 50, 56, 62, 68 and 74.The total variation splits into the part the line explains and the part it misses.
QuizInteractive · disabled in the PDF
In a regression with one predictor, the correlation between and is . What is ?
In a regression with one predictor, the correlation between and is . What is ?
ProblemInteractive · disabled in the PDF
For the shop data ( = 1, 2, 3, 4, 5 and = 3, 7, 5, 11, 9), the least squares line is . Find SSE, SST and .
Going deeper
A high does not mean the line is the right model (a curve can have a high for a line through it), and a low one does not mean the slope is useless: in noisy fields like medicine a slope can matter a lot while explaining only a few per cent of the variation. answers "how much of the spread does this explain", nothing more.
Statistics179 / 246
Module 15 · Linear regression
Residual plots show what the line missed
A residual plot puts the residuals on the vertical axis against (or against ). If the line is a good model, it looks like a shapeless band around 0. A pattern means the line has missed something: a curve means the relationship bends, and a fan that widens means the spread grows with , so predictions are less precise at one end than the other.
Zero
The pattern
At 0, the study residuals scatter with no shape. Drag the curvature: if the true relationship bent, the residuals would form a U that the line cannot capture.
QuizInteractive · disabled in the PDF
The residual plot for house price against floor area is narrow for small houses and much wider for big ones. What does it tell you?
The residual plot for house price against floor area is narrow for small houses and much wider for big ones. What does it tell you?
Statistics180 / 246
Module 15 · Linear regression
Outliers and leverage: some points pull harder
An outlier has a large residual: it is far from the line in . A point with high leverage is far from the others in . A point is influential when removing it changes the fit a lot, and that usually takes both: an unusual at an unusual . A point at near can only move the line up and down; one far out acts like a long lever and tilts it.
Fit without the new point
Fit with it
Slope with the new point0.95
A sixth student joins. Put them at 3 hours and drag their score: the slope stays 6. Move them to 10 hours and drag again: the slope swings.
QuizInteractive · disabled in the PDF
At 10 hours with a score of 60, the new student drags the slope from 6 down to about 0.95. What makes this point so influential?
At 10 hours with a score of 60, the new student drags the slope from 6 down to about 0.95. What makes this point so influential?
Statistics181 / 246
Module 15 · Linear regression
Predicting inside the data, not beyond it
Predicting for an inside the range you observed is interpolation: for three and a half hours. Predicting outside it is extrapolation, and it assumes the line keeps going where you have no evidence. At 12 hours the line predicts 116 points on a test marked out of 100.
Interpolation
Inside the range of you observed
The data checked the line here
Still uncertain: report an interval
Extrapolation
Outside the range of
Nothing says the line stays straight
Growth curves, saturation and limits break it
QuizInteractive · disabled in the PDF
A line fitted to children aged 2 to 10 says height grows 6 cm a year. What does it predict for age 40, and should you trust it?
A line fitted to children aged 2 to 10 says height grows 6 cm a year. What does it predict for age 40, and should you trust it?
Going deeper
Two different intervals answer two questions. A confidence interval for the mean at says where the average score of all students who study hours lies. A prediction interval says where one new student’s score will fall, so it adds the scatter of individuals, , and is always wider. Both widen as moves away from , through a term .
Statistics182 / 246
Module 15 · Linear regression
Is the slope real? Inference on the slope
Five students are a sample. Another five would give a different line, so has a sampling distribution, like a mean. Under the model , with errors that are independent, normal and of equal spread, has standard error , where estimates the spread of the points around the line with degrees of freedom (two were spent on and ). Test with a t statistic.
3.182 is the t critical value for 3 degrees of freedom. The p-value is far below 0.01, and the interval excludes 0.
Linear: the mean of is a straight-line function of (check the residual plot for curves).
Independent errors: one student’s miss tells you nothing about another’s.
Normal errors: matters for small samples (check a histogram of residuals).
Equal spread: the residuals’ spread is the same for every (no fan).
Code challengeInteractive · disabled in the PDF
Write slopeTest(xs, ys), returning a SlopeResult: the least squares slope, its standard error se, with , and t, .
C++
1#include<cmath>2#include<vector>34structSlopeResult{5double slope, se, t;6};78doublemean(const std::vector<double>& v){9double sum =0;10for(double x : v) sum += x;11return sum / v.size();12}1314SlopeResultslopeTest(const std::vector<double>& xs,15const std::vector<double>& ys){16int n = xs.size();17double mx =mean(xs), my =mean(ys), sxy =0, sxx =0;18for(int i =0; i < n; i++){19 sxy +=(xs[i]- mx)*(ys[i]- my);20 sxx +=(xs[i]- mx)*(xs[i]- mx);21}22double slope = sxy / sxx;23 // TODO: SSE from the residuals, then s, se and t24return{slope,0,0};25}
Statistics183 / 246
Module 15 · Linear regression
Practice problems
Work these on paper, then type your answers. Keep the units of the data in mind: a slope is units of per unit of .
ProblemInteractive · disabled in the PDF
Still with the shop data: , , and . Find , the standard error of the slope and the t statistic for . (The two-sided 5% critical value for 3 degrees of freedom is 3.182.)
ProblemInteractive · disabled in the PDF
For a group of students, hours of revision have mean 10 and standard deviation 5, exam scores have mean 60 and standard deviation 12, and the correlation is . Find the least squares slope and intercept for predicting score from hours, and the predicted score for 15 hours.
points per hour
points
points
ProblemInteractive · disabled in the PDF
A fit of fuel use (, litres per 100 km) on car mass (, in hundreds of kg) gives , with correlation . A car of 1400 kg uses 9.1 litres per 100 km. Find its predicted fuel use, its residual and the of the fit.
L/100 km
L/100 km
ProblemInteractive · disabled in the PDF
The study data of this module are = 1, 2, 3, 4, 5 hours and = 51, 54, 62, 70, 73 points, fitted by . A sixth student studied 8 hours and scored 50. What did the line predict for them, what is their residual, and what is the slope refitted to all six? For the six, , , and .
points
points
points per hour
Statistics184 / 246
Module 15 · Linear regression
Recap
Least squares picks and to make the sum of squared residuals smallest: , .
Read the slope in data units, as an average association. The intercept matters only if is in range.
is the share of variation explained; with one predictor it is .
Residual plots reveal curves and fans that hides.
Points far out in have leverage; with a big residual too, they are influential.
Interpolate with care, extrapolate hardly ever.
Test the slope with on degrees of freedom, after checking the LINE conditions.
Put in orderInteractive · disabled in the PDF
Put a regression analysis in a sensible order.
1.Look at the residual plot for curves, fans and outliers
2.Report the slope with its confidence interval and
3.Predict only within the range of the data
4.Draw a scatter plot of the data
5.Fit the least squares line
FlashcardsInteractive · disabled in the PDF
Residual
Actual minus predicted: .
Least squares
Choosing the line that makes the sum of squared residuals smallest.
Slope formula
, and the line passes through .
The share of the variation in that the line explains: .
Leverage
How far a point’s is from the others; high leverage lets a point tilt the line.
Extrapolation
Predicting outside the range of you observed. Risky.
Standard error of the slope
, with .
Module 16: Multiple and logistic regression
Statistics185 / 246
Module 16 · Multiple and logistic regression
Real outcomes have more than one cause
A house’s price depends on its size, but also on its age, its location, whether it has a garage. A line with one predictor lumps all of that into the residuals, and worse, it can credit size with effects that belong to something else. Multiple regression gives each predictor its own coefficient, fitted together by the same least squares rule as before: make the sum of squared residuals smallest.
predictors, to , each with its own slope.
Say a fit on houses gives price (in thousands of euros) from floor area (square metres) and age (years):
Multiple regression
A linear model with two or more predictors.
Coefficient
The number multiplying a predictor: its slope, with the others held fixed.
Design matrix
The table of predictor values, one row per observation and one column per predictor (plus a column of 1s for the intercept).
Going deeper
In matrix form the model is , and the least squares coefficients solve the normal equations , so when can be inverted. Software solves it with a QR decomposition instead of inverting, which is more accurate.
Statistics186 / 246
Module 16 · Multiple and logistic regression
Each coefficient holds the others fixed
The coefficient of size, 1.8, means: between two houses of the same age, one with 1 square metre more is predicted to cost 1.8 thousand euros more. The −0.9 means: between two houses of the same size, one a year older is predicted to cost 0.9 thousand less. Each slope is the effect of its predictor after allowing for the others.
Same age, 10 m² more: the difference is exactly ten times the size coefficient.
QuizInteractive · disabled in the PDF
On its own, the number of bedrooms has a positive slope for price. Add floor area to the model, and the bedrooms coefficient turns negative. How can that be?
On its own, the number of bedrooms has a positive slope for price. Add floor area to the model, and the bedrooms coefficient turns negative. How can that be?
ProblemInteractive · disabled in the PDF
Use , with price in thousands of euros, the floor area in m² and the age in years. Predict the price of an 85 m² house that is 30 years old. Then find the predicted price of house A (100 m², 10 years old) minus that of house B (90 m², 40 years old).
thousand €
thousand €
Statistics187 / 246
Module 16 · Multiple and logistic regression
Categories enter as 0 or 1
A predictor like "has a garage" is not a number, but you can code it as one: an indicator (or dummy) variable that is 1 for houses with a garage and 0 for those without. Its coefficient is the predicted difference between the two groups at the same size. With three neighbourhoods, North, Centre and South, use two indicators, for Centre and for South; North is the baseline, and each coefficient compares a neighbourhood with North.
No garage
Garage
Garage minus no garage, at any size15
Price against size with an indicator for a garage: two parallel lines. Drag the garage coefficient to move them apart.
Fill the blanksInteractive · disabled in the PDF
Code a house in South for a model whose baseline neighbourhood is North.
Interactions let one slope depend on another variable
Parallel lines assume a garage adds the same amount to a small house and a big one. If you think its effect grows with size, add an interaction: the product of the two predictors as a new predictor. Its coefficient changes the slope of size for houses with a garage.
Without a garage the slope is 1.8; with one it is .
No garage
Garage
Slope with a garage2.1
Drag the interaction: at 0 the lines are parallel; otherwise they fan apart.
QuizInteractive · disabled in the PDF
With and , how much more is a 120 m² house with a garage predicted to cost than one without?
With and , how much more is a 120 m² house with a garage predicted to cost than one without?
Statistics189 / 246
Module 16 · Multiple and logistic regression
Predictors that move together blur each other
Multicollinearity is when predictors are strongly correlated with each other: floor area and number of rooms, or height in centimetres and in inches. The model can still predict well, but it cannot tell which predictor deserves the credit, so their coefficients become unstable: large standard errors, signs that flip from sample to sample. The variance inflation factor measures it for predictor , using , the of regressing on the other predictors.
A VIF of 10 means the variance of is 10 times what it would be with uncorrelated predictors, so its standard error is times larger.
QuizInteractive · disabled in the PDF
A model has both "height in cm" and "height in inches" as predictors. What happens, and what is the fix?
A model has both "height in cm" and "height in inches" as predictors. What happens, and what is the fix?
Statistics190 / 246
Module 16 · Multiple and logistic regression
More predictors always fit better, and that is the trap
Add any predictor, even random noise, and goes up or stays the same: least squares can always use it a little. A model with as many coefficients as data points fits perfectly and predicts new data badly. That is overfitting: learning the noise of this sample instead of the pattern. Adjusted charges for each predictor, and falls when a predictor adds less than chance would.
On the fitting data
On new data
An illustration: error on the data used to fit keeps falling as the model grows; error on new data falls, then rises.
QuizInteractive · disabled in the PDF
You add a column of random numbers to a regression. What happens to and to adjusted ?
You add a column of random numbers to a regression. What happens to and to adjusted ?
Statistics191 / 246
Module 16 · Multiple and logistic regression
Logistic regression predicts a probability
Will a visitor to an online shop buy something? The outcome is yes (1) or no (0). A straight line would predict values below 0 and above 1, which no probability can be. Logistic regression puts the line through the logistic (sigmoid) function, which squeezes any number into the range from 0 to 1.
Logistic curve
p = 0.5
Visits for a 50% chance6
The chance of buying against the number of visits. Drag the slope to make the S steeper, and the intercept to slide it sideways.
Fitted by likelihood, not least squares. Logistic coefficients are chosen to make the observed yeses and noes as probable as possible: maximum likelihood, which the final module (20) explains. There is no formula like ; the computer searches for them, step by step.
Statistics192 / 246
Module 16 · Multiple and logistic regression
Coefficients act on the log odds
The odds of an event are : a probability of 0.8 is odds of 4 to 1. Logistic regression is a straight line for the logarithm of the odds, the log odds or logit. So is the change in log odds per unit of , and is the odds ratio: the odds are multiplied by it for each extra unit.
Each extra visit multiplies the odds of buying by about 1.65, whatever the starting point.
QuizInteractive · disabled in the PDF
With , what does one more visit do?
With , what does one more visit do?
Code challengeInteractive · disabled in the PDF
Write sigmoid(z), ; probability(b0, b1, x), the logistic model’s ; and oddsRatio(b1), .
A logistic model for passing a driving test gives , where is the number of practice drives. What is the probability of passing after 5 drives, and after 7? By what factor does each extra drive multiply the odds?
Statistics193 / 246
Module 16 · Multiple and logistic regression
Gradient descent walks downhill to the best fit
When there is no formula, a computer can still find the best coefficients by gradient descent. Picture the error as a landscape over the coefficients. Start anywhere, work out which way is downhill (the gradient: the derivatives of the error), take a small step that way, and repeat. The size of each step is the gradient times the learning rate.
(eta) is the learning rate. The minus sign means "go against the slope", downhill.
SSE(b₁)
Next slope4.65
The study data from the last module, intercept fixed at 44: SSE against the slope. Drag the current slope and the learning rate. Past about 0.018 the step overshoots more than it gains, and descent diverges.
QuizInteractive · disabled in the PDF
Gradient descent’s error grows bigger on every step instead of shrinking. What is the likely cause?
Gradient descent’s error grows bigger on every step instead of shrinking. What is the likely cause?
Going deeper
For the SSE of a line the landscape is a bowl with one bottom (it is convex), so descent cannot get stuck. Logistic regression’s negative log-likelihood is convex too. Neural networks are not, which is why their training is harder. Real libraries use refinements such as Newton’s method (for logistic regression, as iteratively reweighted least squares) or stochastic gradient descent on small batches of data.
Statistics194 / 246
Module 16 · Multiple and logistic regression
Fitting a line by gradient descent
Use the mean squared error, , so the step size does not depend on how many points there are. Its derivatives are for the intercept and for the slope. Update both at once, from the same old values.
Code challengeInteractive · disabled in the PDF
Write descend(xs, ys, rate, steps): start at intercept 0 and slope 0, take steps gradient descent steps on the mean squared error, and return the Line.
C++
1#include<vector>23structLine{4double intercept;5double slope;6};78Linedescend(const std::vector<double>& xs,9const std::vector<double>& ys,double rate,int steps){10double intercept =0;11double slope =0;12 // TODO: repeat steps times: the two gradients, then a step13return{intercept, slope};14}
PlaygroundInteractive · disabled in the PDF
C++
1#include<iostream>2#include<vector>34intmain(){5 std::vector<double> xs ={1,2,3,4,5};6 std::vector<double> ys ={51,54,62,70,73};7double rate =0.05; // try 0.01, then 0.18int n = xs.size();9double b0 =0, b1 =0;10for(int k =1; k <=3000; k++){11double g0 =0, g1 =0;12for(int i =0; i < n; i++){13double miss = b0 + b1 * xs[i]- ys[i];14 g0 +=2.0/ n * miss;15 g1 +=2.0/ n * miss * xs[i];16}17 b0 -= rate * g0;18 b1 -= rate * g1;19if(k %500==0)20 std::cout << k <<" "<< b0 <<" "<< b1 <<"\n";21}22}
Run it, then change the learning rate: 0.01 crawls, 0.1 blows up.
Statistics195 / 246
Module 16 · Multiple and logistic regression
Practice problems
Work these on paper, then type your answers. A calculator with and helps for the logistic ones, or type the exact form, such as exp(0.8).
ProblemInteractive · disabled in the PDF
A model with predictors fitted to observations has . Find its adjusted . A fifth predictor lifts to 0.61: what is the new adjusted ?
ProblemInteractive · disabled in the PDF
Regressing floor area on the other predictors of a house-price model gives . What is the VIF of floor area, and by what factor is the standard error of its coefficient inflated? What would give a VIF of 5?
ProblemInteractive · disabled in the PDF
A model is , with price in thousands of euros, size in m², and garage 1 or 0. How much more is a house with a garage predicted to cost than one without, at 80 m²? At 120 m²? What is the slope of size for houses with a garage?
thousand €
thousand €
thousand € per m²
Statistics196 / 246
Module 16 · Multiple and logistic regression
More practice problems
ProblemInteractive · disabled in the PDF
For the shop model , with the number of visits, how many visits give an even chance of buying? How many give a 90% chance?
visits
visits
ProblemInteractive · disabled in the PDF
Fit to the points , and by gradient descent on the mean squared error, starting at with learning rate 0.1. The gradients are for and for . What are and after one step?
Statistics197 / 246
Module 16 · Multiple and logistic regression
Recap
Multiple regression gives each predictor a coefficient, read as its effect with the others held fixed.
A coefficient’s meaning, even its sign, depends on what else is in the model.
Categories become 0/1 indicators, one fewer than the number of categories.
An interaction (a product of predictors) lets one predictor’s slope depend on another.
Correlated predictors make coefficients unstable: check the VIF.
never falls when you add predictors; judge a model on new data.
Logistic regression models the log odds as a line; is the odds ratio.
Gradient descent steps against the gradient; the learning rate must be small enough to converge.
Put in orderInteractive · disabled in the PDF
Put one step of gradient descent in order.
1.Average them into the gradient for each coefficient
2.Work out each residual, prediction minus actual
3.Predict every point with the current coefficients
4.Move every coefficient against its gradient, times the learning rate
FlashcardsInteractive · disabled in the PDF
Holding others fixed
A multiple regression coefficient compares observations that are equal on the other predictors.
Indicator (dummy) variable
A 0/1 column for a category; the left-out category is the baseline.
Interaction
A product of two predictors, letting one’s effect depend on the other.
Multicollinearity
Strongly correlated predictors: good predictions, unstable coefficients.
VIF
: how much correlation with other predictors inflates a coefficient’s variance.
Odds
. A probability of 0.8 is odds of 4.
Odds ratio
: the factor the odds are multiplied by per unit of .
Learning rate
The step size in gradient descent: too big diverges, too small crawls.
Module 17: Simulation, the bootstrap and permutation tests
Statistics198 / 246
Module 17 · Simulation, the bootstrap and permutation tests
When the maths is hard, simulate
Some probabilities are easy to work out on paper and some are not. Monte Carlo simulation skips the paper: play the random process many times on a computer, and count how often the thing you care about happens. The fraction of hits is an estimate of the probability. It is named after the casino, because it runs on chance.
Each run is a yes or no, so the hit count is binomial. The estimate’s standard error shrinks like .
SE of the estimate
SE at N = 10000.0158
SE at N = 40000.0079
Drag p: the error of a simulation falls fast at first, then slowly. Four times the runs only halves it.
QuizInteractive · disabled in the PDF
A simulation with 10 000 runs gives an estimate with a standard error of 0.004. How many runs do you need for a standard error of about 0.001?
A simulation with 10 000 runs gives an estimate with a standard error of 0.004. How many runs do you need for a standard error of about 0.001?
ProblemInteractive · disabled in the PDF
A simulation of 2500 runs gives 900 hits. What is the estimate , and its standard error? Using in place of , how many runs would bring the standard error down to 0.003?
Going deeper
A classic check: the chance that at least two of 23 people share a birthday. The exact answer is . A simulation of 100 000 groups lands within about 0.005 of it, with no algebra at all. For problems with no closed form (queues, card games, a portfolio over 30 years) simulation is often the only practical method.
Statistics199 / 246
Module 17 · Simulation, the bootstrap and permutation tests
Computers fake randomness, on purpose
A computer follows instructions, so it cannot roll a die. A pseudo-random number generator (PRNG) is a formula that turns one number, its state, into the next, scrambling the bits so the outputs look random and pass statistical tests. The starting state is the seed. Same seed, same sequence, every time. That is a feature: a simulation with a fixed seed can be rerun, checked and debugged.
WalkthroughInteractive · disabled in the PDF
C++
1#include<cstdint>2#include<iostream>34std::uint32_t state =42; // the seed56doublemulberry32(){7 state +=0x6D2B79F5;8 std::uint32_t t =(state ^(state >>15))*(state |1);9 t =(t +(t ^(t >>7))*(t |61))^ t;10return(t ^(t >>14))/4294967296.0;11}1213intmain(){14 std::cout <<mulberry32()<<" "<<mulberry32()<<" "15<<mulberry32()<<"\n";16}
Lines 4-6: The generator’s state is one 32-bit unsigned whole number, a std::uint32_t, and it starts as the seed. mulberry32() gives the next number each time it is called; the state lives on between calls.
Lines 7: Move the state on by a fixed odd constant (0x means hexadecimal). Unsigned arithmetic wraps around at by itself, so the state stays a 32-bit whole number.
Lines 8-9: Scramble: shifts (>>), XORs and multiplications mix every bit of the state into every bit of the output. Here ^ really is XOR, the bitwise operation, which is why it is never a power in C++.
Lines 10: Turn the 32-bit result into a number in by dividing by , written 4294967296.0 so that the division is a decimal one.
Lines 13-16: Seed 42 always prints 0.601104 0.448291 0.852466. Run it twice: identical. The rest of the course uses the standard library’s generator, std::mt19937 gen(42): a much bigger state and a better scramble, but the same idea.
QuizInteractive · disabled in the PDF
You run a bootstrap with std::mt19937 gen(7), get an interval, then run it again with a new std::mt19937 gen(7). What happens?
You run a bootstrap with std::mt19937 gen(7), get an interval, then run it again with a new std::mt19937 gen(7). What happens?
Going deeper
Not for secrets. Generators like mulberry32 and std::mt19937 are fine for statistics and games but predictable to an attacker who sees a few outputs (624 outputs of std::mt19937 give away its whole state). For passwords, tokens and keys use a cryptographic generator, from the operating system or a cryptography library; std::random_device asks the system for randomness, but the C++ standard does not promise it is secure. Serious simulation libraries use generators with long periods and good statistical properties, such as PCG or the Mersenne Twister, which is what std::mt19937 is.
Statistics200 / 246
Module 17 · Simulation, the bootstrap and permutation tests
Your first Monte Carlo estimate
Roll two fair dice. What is the chance their sum is 10 or more? The exact answer is easy to check: 6 of the 36 equally likely pairs (4+6, 5+5, 5+6, 6+4, 6+5, 6+6), so . Estimate it by simulation and compare. A die from a uniform number is ; in C++, std::uniform_int_distribution<int> roll(1, 6) does that for you, so roll(gen) is a fair throw.
Code challengeInteractive · disabled in the PDF
Write estimateHighRoll(trials, gen): roll two dice trials times using the generator gen and return the fraction of rolls whose sum is at least 10.
C++
1#include<random>23intdie(std::mt19937& gen){4 std::uniform_int_distribution<int>roll(1,6);5returnroll(gen);6}78doubleestimateHighRoll(int trials, std::mt19937& gen){9 // TODO: roll two dice per trial and count sums of 10 or more10return0;11}
Statistics201 / 246
Module 17 · Simulation, the bootstrap and permutation tests
The bootstrap: the sample stands in for the population
The standard error of a statistic is how much it would vary from sample to sample. Theory gives it for a mean (), but not for a median, a ratio or a 90th percentile. If you could draw many new samples from the population you could just watch it vary, but you have only one. The bootstrap (Efron, 1979) pretends your sample is the population, and draws new samples from it.
Start with the one sample you have, of size .
Draw values from it with replacement: some appear twice, some not at all.
Work out the statistic on this resample.
Repeat times (say 2000) and keep every value.
Their standard deviation estimates the SE; their middle 95% is a confidence interval.
One real sample, thousands of resamples, one spread to read.
Resample
A sample of size drawn with replacement from the original sample.
Bootstrap distribution
The statistic computed on many resamples: a stand-in for its sampling distribution.
Bootstrap SE
The standard deviation of the bootstrap distribution.
QuizInteractive · disabled in the PDF
Why must a bootstrap resample be drawn with replacement?
Why must a bootstrap resample be drawn with replacement?
Statistics202 / 246
Module 17 · Simulation, the bootstrap and permutation tests
Bootstrapping the mean wait at a coffee shop
Ten customers waited 2, 3, 3, 4, 4, 5, 6, 7, 9 and 14 minutes. The mean is minutes. Here are 2000 bootstrap means (seed 1), in bins half a minute wide. The distribution is skewed right, like the data: the one 14-minute wait pulls some resamples up.
The bootstrap distribution of the mean wait. Darker bars hold roughly the middle 95%.The percentile interval: cut 2.5% off each end. 50 is 2.5% of 2000, so 50 means lie below and 50 above .
QuizInteractive · disabled in the PDF
The interval, 3.8 to 7.9 minutes, is not centred on 5.7: it reaches 1.9 below but 2.2 above. Why?
The interval, 3.8 to 7.9 minutes, is not centred on 5.7: it reaches 1.9 below but 2.2 above. Why?
ProblemInteractive · disabled in the PDF
You make bootstrap means and sort them, . For a 90% percentile interval, cut 5% off each end. Which sorted positions are the lower and upper ends?
Going deeper
The formula SE is ; the bootstrap gives about 1.07. The gap is not an error: the bootstrap treats the sample as the population, so it uses a divisor of , not , and . Better intervals exist, such as the BCa (bias-corrected and accelerated) interval, which adjusts the percentiles for bias and skew; most statistics libraries offer it.
Statistics203 / 246
Module 17 · Simulation, the bootstrap and permutation tests
Write the bootstrap
The whole method fits in a dozen lines: a loop over resamples, an inner loop drawing random positions, a mean, then a sort. Picking a position with std::uniform_int_distribution<int> pick(0, n - 1) gives each value the same chance on every draw, which is what “with replacement” means.
Code challengeInteractive · disabled in the PDF
Write bootstrapInterval(data, B, gen): make B resamples of data (with replacement), take each one’s mean, sort the means, and return the pair {sorted[floor(0.025 * B)], sorted[ceil(0.975 * B) - 1]}.
C++
1#include<algorithm>2#include<cmath>3#include<random>4#include<utility>5#include<vector>67std::pair<double,double>bootstrapInterval(8const std::vector<double>& data,int B, std::mt19937& gen){9 std::vector<double> means;10 // TODO: fill means with B bootstrap means11return{0,0};12}
Statistics204 / 246
Module 17 · Simulation, the bootstrap and permutation tests
Where the bootstrap fails
The bootstrap can only show variation that the sample already contains. It works well for smooth statistics (means, medians, correlations, regression slopes) with a sample of a reasonable size, and it fails in a few known ways.
Tiny samples. With 5 values the sample is a poor picture of the population, and the bootstrap copies its flaws.
Extremes. The bootstrap maximum can never exceed the sample maximum, so it badly underestimates how the maximum varies.
Dependent data. Resampling single values breaks time series apart. Resample blocks of neighbours instead (the block bootstrap).
Heavy tails. With rare huge values (insurance claims, file sizes), whether one is in your sample dominates everything.
QuizInteractive · disabled in the PDF
You bootstrap the maximum of 20 sensor readings. What does the bootstrap distribution look like?
You bootstrap the maximum of 20 sensor readings. What does the bootstrap distribution look like?
Statistics205 / 246
Module 17 · Simulation, the bootstrap and permutation tests
Permutation tests: shuffle the labels
Two baristas. Customers of Ana waited 4, 6, 5, 7, 8, 6 minutes; customers of Ben waited 3, 4, 2, 5, 4, 3. The difference in means is minutes. Could that be chance? If the barista made no difference (the null hypothesis), the labels “Ana” and “Ben” are arbitrary: any 6 of the 12 waits could have been Ana’s. So shuffle the labels, recompute the difference, and see how often chance alone gives one as large as 2.5.
All 924 ways to split the 12 waits into two groups of 6. The darker bars are at least as extreme as 2.5 either way.An exact two-sided p-value. With bigger groups there are too many splits to list, so you shuffle at random a few thousand times.
Put in orderInteractive · disabled in the PDF
Put the steps of a permutation test in order.
1.Repeat the shuffle many times
2.Compute the observed statistic on the real groups
3.Report the fraction of shuffles at least as extreme as the observed value
4.Compute the statistic on the shuffled groups
5.Shuffle the pool and split it into groups of the original sizes
6.Pool all the values together
Going deeper
A permutation test assumes only that, under the null, the labels are exchangeable: every rearrangement was equally likely. That holds when the labels were assigned at random, as in an experiment. It needs no normality, so it is a safe check on a t-test, and with large samples the two usually agree.
Statistics206 / 246
Module 17 · Simulation, the bootstrap and permutation tests
Write a permutation test
Shuffling fairly needs care. The Fisher–Yates shuffle walks from the end of the vector, swapping each position with a random one at or before it, so all orders are equally likely. (The standard library’s std::shuffle does exactly this; writing it once shows why it is built that way.)
Find the bugInteractive · disabled in the PDF
This shuffle runs, but some orders come up more often than others. Which line is wrong?
C++
Code challengeInteractive · disabled in the PDF
Write permutationPValue(a, b, shuffles, gen): the two-sided p-value for the difference in means, (count + 1) / (shuffles + 1), where count is how many shuffles give an absolute difference at least the observed one. Use the shuffle and mean given.
C++
1#include<cmath>2#include<random>3#include<utility>4#include<vector>56doublemean(const std::vector<double>& xs){7double sum =0;8for(double x : xs) sum += x;9return sum / xs.size();10}1112voidshuffle(std::vector<double>& xs, std::mt19937& gen){13for(int i = xs.size()-1; i >0; i--){14 std::uniform_int_distribution<int>pick(0, i);15 std::swap(xs[i], xs[pick(gen)]);16}17}1819doublepermutationPValue(const std::vector<double>& a,20const std::vector<double>& b,int shuffles,21 std::mt19937& gen){22 // TODO23return0;24}
Statistics207 / 246
Module 17 · Simulation, the bootstrap and permutation tests
Cross-validation: test on data the model has not seen
A model judged on the data it was fitted to looks better than it is: it has partly learned that data’s noise. Cross-validation gives an honest score by holding data out. In k-fold cross-validation, split the data into equal parts (folds). Fit on folds, measure the error on the one left out, and repeat so that each fold is left out once. Average the errors.
Round
Fold 1
Fold 2
Fold 3
Fold 4
Fold 5
1
test
train
train
train
train
2
train
test
train
train
train
3
train
train
test
train
train
4
train
train
train
test
train
5
train
train
train
train
test
Fill the blanksInteractive · disabled in the PDF
Shuffled data points are dealt into k folds like cards. Complete the line that picks the test points for fold f.
C++
1std::vector<int>indices(data.size());2for(int i =0; i < indices.size(); i++) indices[i]= i;3std::shuffle(indices.begin(), indices.end(), gen);4std::vector<int> test, train;5for(int pos =0; pos < indices.size(); pos++){6if(pos k f) test.push_back(indices[pos]);7if(pos % k f) train.push_back(indices[pos]);8}
QuizInteractive · disabled in the PDF
You pick the 10 best of 1000 predictors using all the data, then run 5-fold cross-validation on a model with those 10. The score is excellent. What is wrong?
You pick the 10 best of 1000 predictors using all the data, then run 5-fold cross-validation on a model with those 10. The score is excellent. What is wrong?
Going deeper
Choices of : 5 or 10 are the usual compromise. (leave-one-out) has little bias but a high-variance estimate and costs fits. For time series, never test on the past using the future: use rolling windows, training on earlier data and testing on the next period.
Statistics208 / 246
Module 17 · Simulation, the bootstrap and permutation tests
Practice problems
Work these on paper, then type your answers. They are the sums a simulation does, done by hand on small cases.
ProblemInteractive · disabled in the PDF
You bootstrap a sample of values. What is the probability that one particular value is left out of a resample? On average, how many of the 10 values appear in a resample at least once?
ProblemInteractive · disabled in the PDF
Group A’s values are 7 and 9; group B’s are 2, 4 and 6. Find the observed difference in means, A minus B. How many ways are there to choose which 2 of the 5 values form group A, and what is the exact two-sided permutation p-value, the share of splits with an absolute difference at least as large as the observed one?
ProblemInteractive · disabled in the PDF
You run 5-fold cross-validation on 103 data points, dealing the shuffled points into folds with pos % 5. How many points are in fold 0, and how many in fold 4? The five folds’ test errors (mean squared errors) are 4.2, 3.8, 5.0, 4.6 and 4.4: what is the cross-validation score?
points
points
ProblemInteractive · disabled in the PDF
A sample of 15 delivery times has standard deviation minutes. What is the formula standard error of the mean, ? A large bootstrap treats the sample as the population, dividing by instead of : about what standard error should it give?
min
min
Statistics209 / 246
Module 17 · Simulation, the bootstrap and permutation tests
Recap
Monte Carlo: simulate many times and count. The error falls like .
Pseudo-random generators are formulas; a fixed seed makes a simulation reproducible.
The bootstrap resamples your data with replacement to see how a statistic varies, giving an SE and a percentile interval.
It fails for tiny samples, extremes, dependent data and heavy tails.
A permutation test shuffles labels to build the null distribution, assuming only exchangeability.
Cross-validation scores a model on held-out folds; every learning step must stay inside the training folds.
FlashcardsInteractive · disabled in the PDF
Monte Carlo simulation
Estimating a quantity by repeating a random process many times.
Seed
The starting state of a pseudo-random generator; the same seed gives the same sequence.
Bootstrap
Resampling the sample with replacement to estimate a statistic’s sampling distribution.
Percentile interval
The middle 95% of the bootstrap distribution: its 2.5th to 97.5th percentiles.
Permutation test
A test that compares the observed statistic with its values over shuffled group labels.
Exchangeable
Every rearrangement of the labels is equally likely under the null.
k-fold cross-validation
Fit on k − 1 folds, test on the one left out, rotate, average.
Data leakage
Information from test data reaching the model, making scores too good.
Module 18: Bayesian statistics
Statistics210 / 246
Module 18 · Bayesian statistics
Probability as a degree of belief
So far a parameter, such as a drug’s true cure rate , has been a fixed unknown number, and probability described only the data. Bayesian statistics also gives the parameter a probability distribution, describing how plausible each value is to you. Before the data that is the prior; after it, the posterior. The data enter through the likelihood: how probable the data you saw are, for each value of . Bayes’ theorem (module 7) joins them.
means “proportional to”. The bottom, , does not depend on : it only makes the posterior add up to 1.
Prior
What you believe about the parameter before seeing this data, as a distribution.
Likelihood
The probability of the observed data, as a function of the parameter. Not a distribution over .
Posterior
The updated distribution of the parameter, given the data.
Evidence
The normalising constant : the likelihood averaged over the prior.
QuizInteractive · disabled in the PDF
If the prior gives every value of the same weight (a flat prior), what shape is the posterior?
If the prior gives every value of the same weight (a flat prior), what shape is the posterior?
Statistics211 / 246
Module 18 · Bayesian statistics
Updating with two possible coins
A friend has two coins in a pocket: a fair one, and a trick one that lands heads 80% of the time. They pull one out at random and flip it 5 times: 4 heads, 1 tail. Which coin is it? With only two possible values of , Bayes’ rule is a small table.
Coin
Prior
Likelihood of 4 heads in 5
Prior × likelihood
Posterior
Fair,
0.5
0.078125
0.276
Trick,
0.5
0.2048
0.724
Total
1
0.282925
1
QuizInteractive · disabled in the PDF
Same data, 4 heads in 5, but now you know that only 1 coin in 10 in the pocket is a trick coin. What is the posterior probability it is the trick coin?
Same data, 4 heads in 5, but now you know that only 1 coin in 10 in the pocket is a trick coin. What is the posterior probability it is the trick coin?
ProblemInteractive · disabled in the PDF
A box holds a fair coin and a bent coin that lands heads only 25% of the time. You pick one at random (prior 0.5 each) and flip it 3 times: 3 tails. Find the likelihood of 3 tails for each coin, and the posterior probability that you picked the bent coin.
Statistics212 / 246
Module 18 · Bayesian statistics
A grid of possible values
Usually could be any number from 0 to 1. A simple trick: try a grid of values, say , and do the two-coin table for each. Say 7 of 10 visitors to a new page signed up. With a flat prior, the weight on each is the likelihood (the binomial coefficient is the same for every , so it cancels), divided by the total.
The grid posterior for the sign-up rate after 7 of 10. Zero at 0 and at 1: you saw both a sign-up and a refusal.
Code challengeInteractive · disabled in the PDF
Write gridPosterior(successes, failures, grid): with a flat prior, return the posterior probability of each value in grid, proportional to std::pow(p, successes) * std::pow(1 - p, failures) and adding up to 1.
C++
1#include<cmath>2#include<vector>34std::vector<double>gridPosterior(int successes,int failures,5const std::vector<double>& grid){6 // TODO: weight each p by its likelihood, then normalise7return std::vector<double>(grid.size(),0.0);8}
Statistics213 / 246
Module 18 · Bayesian statistics
The beta distribution describes a proportion
A smooth prior for a proportion needs a distribution on . The beta distribution has two shape parameters, and , which you can read as “ successes and failures already seen”. is flat; larger values make it narrower.
The factorial form of holds for whole-number and , as on the sliders.
Beta(a, b)
Mean0.286
Standard deviation0.16
Drag a and b. Equal values are symmetric around 0.5; bigger values mean a more confident belief.
QuizInteractive · disabled in the PDF
Which prior says “the rate is probably near 0.25, and I am fairly sure”?
Which prior says “the rate is probably near 0.25, and I am fairly sure”?
Statistics214 / 246
Module 18 · Bayesian statistics
Beta prior plus binomial data gives a beta posterior
Multiply a prior by the binomial likelihood of successes in trials, and the powers simply add: the posterior is another beta. When the posterior is in the same family as the prior, the prior is called conjugate, and updating is just arithmetic.
Prior
Posterior
Prior mean0.5
Data k/n0.7
Posterior mean0.667
A new drug is tried on 20 patients. Drag k, the number cured, and the prior’s a and b: the posterior lands between the prior and the data.The posterior mean is a weighted average of the prior mean and , with weights and .
Fill the blanksInteractive · disabled in the PDF
Complete the conjugate update.
C++
1structBeta{2double a, b;3};45Betaupdate(Beta prior,int k,int n){6return{prior.a +, prior.b +};7}
ProblemInteractive · disabled in the PDF
A designer’s prior for a button’s click rate is . Then 12 of 20 visitors click. Find the posterior’s and , its mean, and the weight the posterior mean puts on the prior mean.
Statistics215 / 246
Module 18 · Bayesian statistics
Credible intervals say what people wish confidence intervals said
A 95% credible interval holds 95% of the posterior’s probability, usually the middle 95% (2.5% cut from each tail). For the drug, gives about . Its meaning is direct: given the prior and the data, there is a 95% probability that the cure rate is in this range. A confidence interval’s 95% is a property of the method over repeated samples (module 12), not a probability about this one interval.
95% confidence interval
The parameter is fixed; the interval is random.
95% of intervals made this way would cover the truth.
No prior needed.
Here (Wald, from 14 of 20): about 0.50 to 0.90.
95% credible interval
The data are fixed; the parameter has a distribution.
A 95% probability the parameter is inside, given the model.
Depends on the prior.
Here (Beta(2, 2) prior): about 0.47 to 0.84.
QuizInteractive · disabled in the PDF
Which sentence about the credible interval is correct?
Which sentence about the credible interval is correct?
Going deeper
The central interval is not the only choice. The highest posterior density (HPD) interval is the narrowest range holding 95%; for a skewed posterior it is shifted toward the peak. With a lot of data and a gentle prior, credible and confidence intervals nearly coincide (the Bernstein–von Mises theorem), which is why the two schools often agree in practice.
Statistics216 / 246
Module 18 · Bayesian statistics
A normal prior for a mean: precisions add
For a mean with known spread , a normal prior is conjugate: the posterior is normal too. It is cleanest in precision, one over the variance. Precisions add, and the posterior mean is the precision-weighted average of the prior mean and .
Coffee waits: a prior belief of 5 minutes, give or take 2, and nine waits averaging 7 minutes with .
Code challengeInteractive · disabled in the PDF
Write normalUpdate(priorMean, priorSd, sigma, n, xbar), returning the Posterior, its mean and sd, for a normal mean with known sigma.
C++
1#include<cmath>23structPosterior{4double mean;5double sd;6};78PosteriornormalUpdate(double priorMean,double priorSd,double sigma,9int n,double xbar){10 // TODO: add the precisions, then weight the means11return{priorMean, priorSd};12}
Statistics217 / 246
Module 18 · Bayesian statistics
Choosing a prior, and how much it matters
The prior is where Bayesian analysis is most criticised and most useful. A weakly informative prior rules out absurd values and little else. An informative prior encodes real knowledge, such as earlier trials. Whatever you pick, the data overwhelm it as grows: the prior counts like observations, and the data like .
Data
Posterior mean, Beta(1, 1) prior
Posterior mean, Beta(20, 20) prior
14 of 20 cured
140 of 200 cured
1400 of 2000 cured
QuizInteractive · disabled in the PDF
A Beta(20, 20) prior and 20 patients. Roughly how much do the prior and the data each weigh in the posterior mean?
A Beta(20, 20) prior and 20 patients. Roughly how much do the prior and the data each weigh in the posterior mean?
Going deeper
Flat is not neutral. A flat prior on is not flat on or on the log-odds . “No information” depends on how you measure the parameter. Jeffreys priors, such as Beta(0.5, 0.5) for a proportion, are built to stay the same under such changes.
Statistics218 / 246
Module 18 · Bayesian statistics
MCMC: sampling a posterior you cannot write down
Most real models have no conjugate prior and too many parameters for a grid. Markov chain Monte Carlo (MCMC) sidesteps both: it produces a long list of draws whose distribution approaches the posterior, needing only likelihood × prior, never . Any summary is then a summary of the draws: the posterior mean is their average, a credible interval their percentiles. The simplest MCMC is the Metropolis algorithm.
Put in orderInteractive · disabled in the PDF
Put one step of the Metropolis algorithm in order.
1.Record the current value as the next draw
2.Start from the current value of the parameter
3.Accept the proposal with probability min(1, ratio), otherwise stay
4.Propose a new value nearby, at random
5.Compute the ratio of likelihood × prior at the proposal to that at the current value
PlaygroundInteractive · disabled in the PDF
C++
1#include<cmath>2#include<iostream>3#include<random>4#include<vector>56// The drug's posterior, Beta(16, 8), up to a constant, on a log scale7doublelogTarget(double p){8if(p <=0|| p >=1)return-INFINITY;9return15* std::log(p)+7* std::log(1- p);10}1112intmain(){13 std::mt19937gen(7);14 std::uniform_real_distribution<double>uniform(0.0,1.0);15double current =0.5;16 std::vector<double> draws;17for(int i =0; i <21000; i++){18double proposal = current +(uniform(gen)-0.5)*0.2;19double logRatio =logTarget(proposal)-logTarget(current);20if(std::log(uniform(gen))< logRatio) current = proposal;21if(i >=1000) draws.push_back(current); // drop the burn-in22}23double mean =0;24for(double d : draws) mean += d / draws.size();25 std::cout <<"MCMC mean "<< mean <<", exact "<<16.0/24<<"\n";26}
Run it: the mean of the draws is close to the exact 0.667. Change the seed, the step size 0.2, or the number of steps, and watch the estimate move.
Going deeper
Working with logs avoids underflow: with thousands of data points, is too small for a floating-point number, but its log is fine. Draws next to each other are correlated, so 20 000 draws carry less information than 20 000 independent ones (the effective sample size). Modern tools such as Stan use Hamiltonian Monte Carlo, which follows the posterior’s gradient, and check convergence by running several chains and comparing them with the statistic.
Statistics219 / 246
Module 18 · Bayesian statistics
Bayesian and frequentist: two questions, often the same answer
Frequentist
Bayesian
Probability means
Long-run frequency
Degree of belief, given information
Parameters are
Fixed unknowns
Uncertain, with distributions
Answers come as
Estimates, CIs, p-values
A posterior distribution
Earlier knowledge
Used informally, in design
Written into the prior
Main risk
Misread p-values and CIs
A prior that dominates without anyone noticing
In practice both are tools. Bayesian methods shine with small samples and good prior knowledge, with many related groups that can share strength (hierarchical models), and when you need a direct probability for a decision. Frequentist methods shine when you need guarantees that hold whatever anyone believes, as regulators often do.
QuizInteractive · disabled in the PDF
A manager asks: “What is the probability that the new page’s sign-up rate is higher than the old one’s?” Which approach answers that question directly?
A manager asks: “What is the probability that the new page’s sign-up rate is higher than the old one’s?” Which approach answers that question directly?
Statistics220 / 246
Module 18 · Bayesian statistics
Practice problems
Work these on paper, then type your answers. Each one is prior × likelihood, then normalise; the conjugate ones turn that into arithmetic.
ProblemInteractive · disabled in the PDF
Your prior for a population mean is . Nine observations with known average . Find the posterior precision, the posterior mean and the posterior standard deviation.
ProblemInteractive · disabled in the PDF
Use a grid of three values, , and , with a flat prior. You see 2 successes in 3 trials. Find the posterior probability of each grid value.
ProblemInteractive · disabled in the PDF
A prior for a recovery rate is . Find its mean and standard deviation. A trial then sees 30 recoveries in 50 patients: what is the posterior mean?
Statistics221 / 246
Module 18 · Bayesian statistics
More practice problems
ProblemInteractive · disabled in the PDF
Before a study, you give a hypothesis probability 0.2. The study’s data are 6 times as probable if is true as if it is false: a Bayes factor of 6. Find the prior odds of , the posterior odds, and the posterior probability of .
ProblemInteractive · disabled in the PDF
A posterior for a mean is normal with mean 108 and standard deviation . Find the central 95% credible interval, using 1.96, and the posterior probability that . Use .
Statistics222 / 246
Module 18 · Bayesian statistics
Recap
Posterior ∝ likelihood × prior. Normalising divides by .
A grid approximation tries many parameter values; it works for one or two parameters.
Beta prior plus binomial data gives : a conjugate update.
For a normal mean, precisions add, and the posterior mean is a precision-weighted average.
A credible interval is a probability statement about the parameter, given the prior and model.
The prior counts like observations; check sensitivity, and expect data to dominate as grows.
MCMC (Metropolis and its descendants) draws from posteriors that have no formula.
FlashcardsInteractive · disabled in the PDF
Prior
The distribution of the parameter before the data.
Likelihood
The probability of the observed data as a function of the parameter.
Posterior
The distribution of the parameter after the data: ∝ likelihood × prior.
Conjugate prior
A prior whose posterior is in the same family, such as beta for binomial data.
Beta(a, b) mean
Credible interval
A range holding a stated probability (say 95%) of the posterior.
Bayes factor
The ratio of the likelihoods of two hypotheses: how much the data favour one.
Metropolis algorithm
Propose a move; accept with probability min(1, ratio of posterior heights).
Module 19: Designing studies: experiments, causation and pitfalls
Statistics223 / 246
Module 19 · Designing studies: experiments, causation and pitfalls
Watching is not the same as intervening
Every method so far assumed the data were already there. Where they came from decides what they can tell you. In an observational study you record what people already do: who drinks coffee, who gets ill. In an experiment you decide who gets what, the treatment, and then measure the outcome. Only an experiment lets you change one thing and watch what follows, which is what "causes" means.
Observational study
You record what happens anyway
Cheap, and often the only ethical option
Shows association: X and Y go together
Cause is hard to prove: something else may drive both
Experiment
You assign the treatment
Costs more, and some treatments cannot be assigned
With randomisation, shows cause
The gold standard: the randomised controlled trial
QuizInteractive · disabled in the PDF
A study follows 10 000 adults for 20 years and finds that those who chose to walk daily had fewer heart attacks. What kind of study is it, and what can it claim?
A study follows 10 000 adults for 20 years and finds that those who chose to walk daily had fewer heart attacks. What kind of study is it, and what can it claim?
Observational study
Data recorded without changing anything: you watch.
Experiment
You assign the treatment to the units, then measure the outcome.
Treatment
What is assigned: a drug, a new page design, a teaching method.
Outcome
What you measure afterwards to see the effect: recovery, sign-ups, scores.
Statistics224 / 246
Module 19 · Designing studies: experiments, causation and pitfalls
A confounder drives both the cause and the effect
Ice cream sales and drownings rise and fall together. Ice cream does not cause drowning: hot weather sends people to buy ice cream and to swim. A confounder is a third variable that affects both the supposed cause and the outcome, making them move together with no link between them. Correlation (module 5) cannot tell these apart, which is why "correlation is not causation".
Hot weather is a common cause. The dashed line is the association you see, not a cause.
In an observational study you can adjust for confounders you measured: compare like with like (only hot days, only cold days), or include them in a regression (module 16). You can never adjust for one you did not think of or could not measure. That gap is what randomisation closes.
QuizInteractive · disabled in the PDF
Children with bigger shoe sizes score higher on reading tests. What is the most likely confounder?
Children with bigger shoe sizes score higher on reading tests. What is the most likely confounder?
Statistics225 / 246
Module 19 · Designing studies: experiments, causation and pitfalls
Randomisation balances what you cannot see
Randomisation means a chance mechanism, such as a coin or a random number generator, decides who gets the treatment. Then nothing about a person, measured or not, can influence their group. Age, health, motivation and things nobody has thought of end up spread evenly between the groups, on average. So any difference in outcome bigger than chance can only come from the treatment.
Randomisation cuts every arrow into the treatment except the coin: confounders can still affect the outcome, but no longer the choice.
Find the bugInteractive · disabled in the PDF
This splits a website’s users into two groups for a test, but the groups are not comparable. Which line is the problem?
C++
Going deeper
Blocking (stratified randomisation) does better than pure chance when you know a strong predictor of the outcome: randomise separately within each block, such as within each age band, so the groups are balanced on it exactly, not only on average. It makes the comparison more precise. "Block what you can, randomise what you cannot."
Statistics226 / 246
Module 19 · Designing studies: experiments, causation and pitfalls
Control groups and blinding
A treatment needs something to be compared with: a control group, which gets no treatment, the usual treatment, or a placebo, a fake treatment that looks the same (a sugar pill). People who believe they are treated often feel better, the placebo effect, so a placebo lets you separate the treatment from the belief. Blinding keeps people from knowing who got what: single-blind, the participants do not know; double-blind, neither they nor the people measuring the outcome know.
Without it
What goes wrong
A control group
People improve anyway (time, natural recovery): you credit the treatment
A placebo
Expecting to get better makes people report feeling better
Blinding the participants
Those who know they got the placebo drop out or report worse
Blinding the assessors
A doctor who knows the group judges a borderline case hopefully
Put in orderInteractive · disabled in the PDF
Put the steps of a randomised controlled trial of a new pain relief tablet in order.
1.Write down the outcome, the sample size and the analysis in advance
2.Measure pain scores at the planned time
3.Unblind and compare the groups as planned
4.Recruit patients who meet the entry criteria
5.Give the tablets, with neither patients nor assessors knowing which
6.Randomly assign each patient to the tablet or an identical placebo
Statistics227 / 246
Module 19 · Designing studies: experiments, causation and pitfalls
An A/B test is an experiment on a website
An A/B test shows each visitor one of two versions of a page, chosen at random, and compares an outcome such as the sign-up rate. It is a randomised experiment, so a real difference is caused by the version. Comparing two proportions is a z-test like the one in module 13, applied to two groups as in module 14: pool the rates under (no difference), then divide the difference by its standard error.
is the number of sign-ups and the number of visitors in each version.Version B’s 6.5% against A’s 5%: a difference this large would be rare if the versions were equal.The sign-up rate per version. 1.5 points looks small, but with 4000 visitors each it is well beyond chance.
Code challengeInteractive · disabled in the PDF
Write twoProportionZ(xA, nA, xB, nB): the z statistic for B’s rate minus A’s, with the pooled standard error above. The counts are ints.
C++
1#include<cmath>23doubletwoProportionZ(int xA,int nA,int xB,int nB){4 // TODO: pooled rate, standard error, then z5return0;6}
ProblemInteractive · disabled in the PDF
An A/B test shows each version of a page to 3000 visitors. Version A gets 150 sign-ups and version B gets 195. Find the pooled sign-up rate, the pooled standard error of the difference, and the z statistic for B minus A.
Going deeper
Do not peek. Checking the p-value every day and stopping the first time it is below 0.05 inflates the false-positive rate far above 5%: with daily looks over a month it can pass 20%. Fix the sample size in advance from a power calculation (module 13), or use a sequential method designed for repeated looks. Also check the split itself: if you planned 50/50 and got 52/48 on a large sample, the assignment is broken (a sample ratio mismatch), and the result cannot be trusted.
Statistics228 / 246
Module 19 · Designing studies: experiments, causation and pitfalls
Selection and survivorship bias
Selection bias happens when the units you get to see are not a fair sample of the ones you care about. Survivorship bias is the special case where only the survivors are left to study. In the Second World War, analysts looked at where returning bombers had bullet holes and proposed armour there. Abraham Wald pointed out that these were the planes that came back: hits on the engines were missing because planes hit there did not return. Armour goes where the holes are not.
Bullet holes per area on returning planes (illustrative). Few holes on the engines means hits there were fatal.
Studying only successful companies to learn what makes companies succeed: the failures did the same things.
Rating a fund on its 10-year return when funds that did badly were closed and dropped from the list.
Surveying people at a gym about how often they exercise: the ones who quit are not there.
Hospital patients: two illnesses can look linked only because having either one gets you admitted.
QuizInteractive · disabled in the PDF
"Old buildings were built better: the ones from 1800 are still standing, but modern ones crack." What is wrong with this argument?
"Old buildings were built better: the ones from 1800 are still standing, but modern ones crack." What is wrong with this argument?
Statistics229 / 246
Module 19 · Designing studies: experiments, causation and pitfalls
Extreme results drift back toward the average
A score is part skill, part luck. Someone who scored very high on one test was probably skilled and lucky; next time the luck is fresh, so they tend to score closer to the average. This is regression to the mean, and it happens whenever two measurements are imperfectly correlated. In standard units (the z-scores of module 4), the predicted second score is the first one times the correlation .
No regression: y = x
Prediction: y = r·x
Expected retest for z = 21
Drag r. Only when r = 1 (no luck at all) does the predicted retest sit on the dashed line y = x. A student 2 standard deviations above the mean is expected to come back toward 0.
QuizInteractive · disabled in the PDF
A flight instructor notices that pilots who are praised after a great landing usually do worse next time, and those shouted at after a bad one usually do better. What does this show?
A flight instructor notices that pilots who are praised after a great landing usually do worse next time, and those shouted at after a bad one usually do better. What does this show?
Code challengeInteractive · disabled in the PDF
Write predictRetest(score, mean, r): the expected second score of someone who got score, when both tests have the same mean and spread and correlate with r.
Two versions of a reasoning test both have mean 100 and standard deviation 15, and scores on them correlate with . A pupil scores 130 on the first. What is their predicted score on the second? And for a pupil who scored 85?
Statistics230 / 246
Module 19 · Designing studies: experiments, causation and pitfalls
Simpson’s paradox: the whole can reverse the parts
A famous study of two treatments for kidney stones found that treatment A worked better for small stones and for large stones, yet B looked better overall. Nothing was miscounted. Doctors gave A, the more invasive treatment, mostly to the hard cases with large stones, and large stones fail more often whatever you do. Stone size is a confounder, and lumping the groups together hides it. This reversal is Simpson’s paradox.
Stones
Treatment A
Treatment B
Small
81 / 87 = 93%
234 / 270 = 87%
Large
192 / 263 = 73%
55 / 80 = 69%
All
273 / 350 = 78%
289 / 350 = 83%
QuizInteractive · disabled in the PDF
A new patient arrives and you know the size of their stone. Which table should guide the choice?
A new patient arrives and you know the size of their stone. Which table should guide the choice?
Statistics231 / 246
Module 19 · Designing studies: experiments, causation and pitfalls
Causal diagrams say what to adjust for
A causal diagram, or DAG (directed acyclic graph), draws variables as boxes and causes as arrows, with no loops. It turns "should I adjust for this?" into a question about the picture. Three shapes cover most cases, and they need opposite treatment.
Shape
Picture
Example
Adjust for the middle one?
Confounder
X ← Z → Y
Age drives shoe size and reading
Yes: that closes the false path through it
Mediator
X → M → Y
Exercise → weight → blood pressure
No, if you want the total effect
Collider
X → C ← Y
Talent → famous ← looks
No: adjusting creates a false link
Coffee and heart disease. Smoking is a confounder: adjust for it. Admission to hospital is a collider: restricting the study to hospital patients would invent a link.
QuizInteractive · disabled in the PDF
Among famous actors, the more talented ones tend to be less good-looking. Suppose fame needs talent or looks, and in the whole population the two are unrelated. What explains the pattern?
Among famous actors, the more talented ones tend to be less good-looking. Suppose fame needs talent or looks, and in the whole population the two are unrelated. What explains the pattern?
Going deeper
Judea Pearl’s backdoor criterion makes this precise: to estimate the effect of X on Y, adjust for a set of variables that blocks every path from X to Y that starts with an arrow into X, without including anything X causes. A confounder sits on such a backdoor path; a mediator is on the causal path itself; a collider blocks a path by itself, and adjusting for it opens the path. The diagram is an assumption you must defend, not something the data prove.
Statistics232 / 246
Module 19 · Designing studies: experiments, causation and pitfalls
Practice problems
Work these on paper, then type your answers. The arithmetic is short; the point is what the numbers say about the design.
ProblemInteractive · disabled in the PDF
Two hospitals treat mild and severe cases. Hospital A: 95 of 100 mild patients survive, and 300 of 400 severe ones. Hospital B: 360 of 400 mild patients survive, and 70 of 100 severe ones. Find each hospital’s overall survival rate, as a percentage.
%
%
ProblemInteractive · disabled in the PDF
An A/B test meant to split 20 000 visitors 50/50 sends 10 300 to A and 9700 to B. If each visitor really had a 0.5 chance of A, what are the expected count in A and the standard deviation of that count? What does 10 300 give?
ProblemInteractive · disabled in the PDF
A trial has 80 smokers among its patients, and each patient is assigned to treatment or control by a fair coin. What is the expected number of smokers in the treatment group, and the standard deviation of that number? How many standard deviations above the expected number would 49 smokers be?
ProblemInteractive · disabled in the PDF
In a randomised trial, 60 of 100 patients on a new tablet improved, against 45 of 100 on placebo. Find the difference in improvement rates, its standard error , and the upper end of the 95% interval for the difference ().
Statistics233 / 246
Module 19 · Designing studies: experiments, causation and pitfalls
Recap
Observational studies show association; randomised experiments can show cause.
A confounder affects both the cause and the outcome. You can adjust only for those you measured.
Randomisation balances every trait, seen or not, on average. Assignment by order or id is not random.
Control groups, placebos and blinding separate the treatment from time, belief and hope.
An A/B test is a randomised experiment: compare two proportions, fix the sample size, do not peek.
Selection and survivorship bias: ask what filter made the data you see.
Extreme results regress toward the mean whenever luck plays a part: the prediction is .
Simpson’s paradox: a lurking variable can reverse a comparison. Causal diagrams say when to adjust: yes for confounders, no for mediators and colliders.
FlashcardsInteractive · disabled in the PDF
Confounder
A variable that causes both the treatment (or exposure) and the outcome.
Randomisation
Assigning treatments by chance, so no trait can influence who gets what.
Placebo
A fake treatment that looks like the real one, given to the control group.
Double-blind
Neither the participants nor those measuring the outcome know who got what.
Survivorship bias
Studying only what got through a filter, and drawing conclusions about everything.
Regression to the mean
Extreme measurements tend to be followed by ones closer to the average.
Simpson’s paradox
A trend in every subgroup reverses when the groups are combined.
Collider
A variable caused by two others. Adjusting for it creates a false link between them.
Module 20: Modelling like an expert
Statistics234 / 246
Module 20 · Modelling like an expert
Likelihood turns probability around
A model with a parameter gives the probability of any data. The likelihood reads the same formula the other way: the data are fixed, because you have seen them, and varies. says how probable your actual data would be for each value of . It is not the probability that is true; that needs a prior (module 18).
For independent observations, the likelihood is the product of each one’s probability (or density).
Likelihood
Likelihood at p0.1172
You flipped a coin 10 times and saw 7 heads. Drag p: the likelihood of exactly that result peaks at p = 0.7.
QuizInteractive · disabled in the PDF
With 7 heads in 10 flips, and . What does this say?
With 7 heads in 10 flips, and . What does this say?
Statistics235 / 246
Module 20 · Modelling like an expert
Maximum likelihood picks the best-explaining value
The maximum likelihood estimate (MLE), , is the value that makes the data most probable. Products of many small numbers are awkward, so you maximise the log-likelihood instead: the logarithm turns the product into a sum, and has its peak in the same place. Set the derivative to zero and solve.
The MLE of a proportion is the sample proportion, as you would hope.
Waiting times at a coffee shop are often modelled as exponential with rate (customers per minute), density . For waits , the log-likelihood is , and the same steps give .
Code challengeInteractive · disabled in the PDF
Write logLik(waits, rate), the exponential log-likelihood above, and bestRate(waits), which tries every rate from 0.001 to 10 in steps of 0.001 and returns the one with the largest logLik.
C++
1#include<cmath>2#include<vector>34doublelogLik(const std::vector<double>& waits,double rate){5return0; // TODO6}78doublebestRate(const std::vector<double>& waits){9 // TODO: search the grid for the largest logLik10return1;11}
ProblemInteractive · disabled in the PDF
Five coffee-shop waits are 1.5, 4, 2.5, 3 and 1 minutes. Modelling them as exponential with rate , find the maximum likelihood estimate and the log-likelihood there, .
per minute
Going deeper
For a normal model the MLEs are and , dividing by , not : maximum likelihood can be biased in small samples. Its strengths are for large : the MLE is consistent, approximately normal, and its standard error comes from the curvature of at the peak (the Fisher information): a sharp peak means a precise estimate. Least squares regression is maximum likelihood when the errors are normal.
Statistics236 / 246
Module 20 · Modelling like an expert
Every model trades bias against variance
A model’s error on new data has three parts. Bias: how far its average prediction is from the truth, because it is too simple (a straight line through a curve). Variance: how much its predictions would change with a different sample, because it is too flexible (it bends to the noise). And noise that no model can remove. More flexibility lowers bias and raises variance; the best model sits in between.
Bias²
Variance
Total error
Best complexity5.2
An illustration with bias² = 4/k and variance = v·k, plus noise 0.5. Drag v down, as if you had more data: the best complexity moves right.
QuizInteractive · disabled in the PDF
A model fits its training data almost perfectly () but predicts new data badly. What is the most likely problem?
A model fits its training data almost perfectly () but predicts new data badly. What is the most likely problem?
Statistics237 / 246
Module 20 · Modelling like an expert
Compare models on what they have not seen
Adding a parameter never lowers the likelihood on the training data, so the biggest model always "wins" if you judge by fit alone. Two fixes. Cross-validation (module 17) scores each model on held-out folds. The Akaike information criterion (AIC) adds a penalty for each parameter: lower is better. AIC estimates how well the model would predict new data from the same source.
is the number of estimated parameters and the maximised likelihood.
Model of house prices
Parameters k
Log-likelihood
AIC
Straight line
3
−120.4
246.8
Quadratic
4
−112.1
232.2
Degree-8 polynomial
10
−109.0
238.0
QuizInteractive · disabled in the PDF
Which model does AIC prefer, and why not the degree-8 one?
Which model does AIC prefer, and why not the degree-8 one?
Fill the blanksInteractive · disabled in the PDF
Complete the function that computes AIC from a model’s maximised log-likelihood.
C++
1doubleaic(double logLik,int k){2return2*-2*;3}
ProblemInteractive · disabled in the PDF
Model A has parameters and maximised log-likelihood ; model B has and . Both are fitted to the same observations. Find each model’s AIC. Then find BIC(B) minus BIC(A), with .
Going deeper
The Bayesian information criterion, , penalises each parameter by instead of 2, so for above 7 it prefers smaller models than AIC. AIC aims at the best predictions; BIC aims at finding the true model, if it is among the candidates. When the two disagree, that is information too: the evidence for the extra terms is modest.
Statistics238 / 246
Module 20 · Modelling like an expert
Regularisation shrinks coefficients toward zero
Regularisation fits a model while charging for large coefficients. Ridge regression minimises the sum of squared residuals plus ; lasso adds . The penalty is chosen by cross-validation. Shrinking adds a little bias but removes a lot of variance, which often improves predictions, especially with many predictors. Lasso also sets some coefficients exactly to zero, choosing the predictors for you.
No penalty
Ridge
Lasso
One coefficient, its predictor scaled so its squares sum to 1: ridge divides the least squares estimate by 1 + λ, lasso subtracts λ/2 and stops at zero. Drag λ.
Code challengeInteractive · disabled in the PDF
For a line through the origin, the ridge slope is the sum of x * y divided by (the sum of x * x plus lambda). Write ridgeSlope(xs, ys, lambda).
In 2015 the Open Science Collaboration repeated 100 published psychology experiments. 97% of the originals had reported a significant result; only 36% of the repeats did, and the effects were on average about half as large. Medicine, economics and other fields have found similar problems. The main causes are statistical: small studies with low power, many tests run with only the "significant" ones reported, and journals preferring surprising positive results.
With no real effects at all, the chance of at least one p below 0.05 among k independent tests: 1 − 0.95^k.
Even honest single tests mislead when real effects are rare. If only a fraction of the ideas a field tests are true, with power and , the share of significant findings that are real is the positive predictive value below: Bayes’ theorem (module 7) again.
PPV
PPV when π = 0.10.64
Drag the power down from 0.8 toward 0.2, the power of many small studies, and watch the readout fall.
QuizInteractive · disabled in the PDF
A field tests ideas of which 10% are true, with power 0.8 and . Of its significant results, what share are real effects?
A field tests ideas of which 10% are true, with power 0.8 and . Of its significant results, what share are real effects?
Statistics240 / 246
Module 20 · Modelling like an expert
Pre-register, then report the uncertainty
The defence against forking paths is to decide before you look. Pre-registration means publishing, before collecting data, the hypothesis, the outcome, the sample size, the exclusions and the analysis. Analyses decided later are still allowed, but labelled exploratory: ideas for the next study, not conclusions. Registered reports go further: the journal accepts the paper on its plan, whatever the result.
Hides the uncertainty
"The new method significantly improved scores (p < 0.05)."
Reports only the outcome that worked
Drops "outliers" after seeing the result
Says "no effect" when p = 0.2
Reports it honestly
"Scores rose 2.6 points (95% CI 1.1 to 4.1, n = 16)."
Reports every pre-registered outcome
States exclusion rules in advance
Says "the data cannot rule out effects from −1 to 5 points"
QuizInteractive · disabled in the PDF
A researcher tries three outcome measures, with and without outliers, and with two sets of control variables, then reports the one analysis with p = 0.03. Why is that p-value misleading?
A researcher tries three outcome measures, with and without outliers, and with two sets of control variables, then reports the one analysis with p = 0.03. Why is that p-value misleading?
Report the size, not just the sign. A good result states an effect size with its interval, the sample size, every analysis tried, and the data and code if possible. "Not significant" is not "no effect": give the interval, which says which effects the data rule out. And a significant result from a small study is likely to overstate the effect (the winner’s curse), which is one reason replications find smaller effects.
Statistics241 / 246
Module 20 · Modelling like an expert
Mastery questions
These mix the whole course. Take your time: each one hides a common misunderstanding.
QuizInteractive · disabled in the PDF
A 95% confidence interval for the difference in mean scores between two teaching methods is 1.1 to 4.1 points. Which statements are right?
A 95% confidence interval for the difference in mean scores between two teaching methods is 1.1 to 4.1 points. Which statements are right?
QuizInteractive · disabled in the PDF
A company finds that customers who used its new budgeting feature saved 30% more. It plans to tell all customers the feature makes them save more. What is the biggest problem?
A company finds that customers who used its new budgeting feature saved 30% more. It plans to tell all customers the feature makes them save more. What is the biggest problem?
QuizInteractive · disabled in the PDF
An experiment with 2 million users per group finds a difference in sign-up rate of 0.01 percentage points, with p = 0.001. What follows?
An experiment with 2 million users per group finds a difference in sign-up rate of 0.01 percentage points, with p = 0.001. What follows?
QuizInteractive · disabled in the PDF
What does the bootstrap assume?
What does the bootstrap assume?
Statistics242 / 246
Module 20 · Modelling like an expert
Final challenge: an interval for a difference
Two groups of students learned with different methods. To report the result honestly you want the difference in means, , with an interval. Without assuming equal spreads, the standard error combines each group’s sample variance (with ), and the interval is the difference plus or minus a critical value times it.
With large samples for 95%. With small ones, comes from a t distribution (Welch’s method), a little larger.
Code challengeInteractive · disabled in the PDF
Write diffInterval(a, b, c), returning the pair {low, high} for the mean of b minus the mean of a, using the standard error above and critical value c.
C++
1#include<cmath>2#include<utility>3#include<vector>45std::pair<double,double>diffInterval(const std::vector<double>& a,6const std::vector<double>& b,7double c){8 // TODO: means, sample variances, SE, then the interval9return{0,0};10}
Statistics243 / 246
Module 20 · Modelling like an expert
Practice problems: the whole course
These mix the whole course. Work each on paper, then type your answers; the hints say which modules each one leans on.
ProblemInteractive · disabled in the PDF
In a field, 20% of the hypotheses tested are true. Studies have power 0.5 and use . What share of significant results are real effects? What would it be if the power rose to 0.9?
ProblemInteractive · disabled in the PDF
Two teaching methods were each used with 50 pupils. Method B’s mean score was 72.4 with ; method A’s was 68.1 with . Find the standard error of the difference (B minus A) and the 95% interval for it, with . Does a two-sided test at 0.05 reject “no difference”?
ProblemInteractive · disabled in the PDF
Of 40 patients in a trial, 28 recovered. Find the 95% Wald confidence interval for the recovery rate (), and the posterior mean with a flat prior.
Statistics244 / 246
Module 20 · Modelling like an expert
More practice: the whole course
ProblemInteractive · disabled in the PDF
A regression on points gives slope with standard error 0.8. Find the t statistic for and the lower end of the 95% interval for the slope, using . About what standard error would you expect with four times as many points, spread the same way?
ProblemInteractive · disabled in the PDF
A lab tests 40 hypotheses at . Unknown to it, 10 are real effects, each found with power 0.8, and 30 are true nulls. How many false positives and how many true positives does it expect? What share of its significant results are real?
ProblemInteractive · disabled in the PDF
A coin lands heads 8 times in 10 flips. Find the maximum likelihood estimate of , the likelihood ratio , and the one-sided p-value for a fair coin.
Statistics245 / 246
Module 20 · Modelling like an expert
Where to go next
You now have the core of the subject: describing data, probability, estimation and testing, regression, resampling, Bayesian updating and study design. Each of these roads goes much further.
Field
What it adds
Built on
Causal inference
Effects from observational data: matching, instrumental variables, difference-in-differences
Causal diagrams, regression
Machine learning
Flexible prediction: trees, random forests, neural networks
Bias and variance, cross-validation, regularisation
Bayesian computation
Hierarchical models fitted with MCMC (Stan, PyMC)
Priors, likelihoods, posteriors
Time series
Data in time order: trends, seasonality, forecasting
Regression, dependence
Generalised linear models
Counts, rates and yes/no outcomes in one framework
Likelihood, logistic regression
Keep practising on real data. Pick a public data set you care about, ask one question, write down how you will answer it before you look, and then do it. The code you wrote in this course (means, standard errors, intervals, tests, the bootstrap) is enough to check the answers that statistical software gives you.
Statistics246 / 246
Module 20 · Modelling like an expert
Recap
The likelihood is the probability of the data you saw, as a function of the parameter. It is not the probability of the parameter.
Maximum likelihood picks the that makes the data most probable; maximise by setting its derivative to zero.
Error on new data is bias² + variance + noise. Too simple: high bias. Too flexible: high variance.
Compare models on unseen data: cross-validation, or AIC (lower is better).
Ridge and lasso shrink coefficients, trading a little bias for less variance; lasso sets some to zero.
Many tests, small studies and rare true effects make many published findings false. Pre-register, and label exploration as exploration.
Report effect sizes with intervals, every analysis tried, and what the data cannot rule out.
FlashcardsInteractive · disabled in the PDF
Likelihood
The probability (or density) of the observed data, seen as a function of the parameter.
Maximum likelihood estimate
The parameter value that makes the observed data most probable.
Bias (of a model)
Error from being too simple: its average prediction misses the truth.
Variance (of a model)
Error from being too flexible: its predictions change a lot from sample to sample.
AIC
: fit penalised by the number of parameters. Lower is better.
Ridge and lasso
Regression with a penalty on (ridge) or (lasso).
Pre-registration
Publishing the hypothesis, sample size and analysis before collecting the data.
P-hacking
Trying analyses until one gives p < 0.05, then reporting only that one.
Answer key
1. Data and variables · Variables are categories or numbers · QuizIn the class survey, which variables are categorical?B. Travels by; D. Coffee rating“Travels by” and “Coffee rating” sort people into groups. The rating’s groups have an order, but they are still groups: the gap between “poor” and “fair” is not a measured amount. Age and siblings are numbers you can average: the class is on average 20.2 years old.
1. Data and variables · Variables are categories or numbers · ProblemA café records 8 orders. For each order it writes down the drink (tea, coffee or juice), the cup size (small, medium or large), the price in dollars and the number of items bought. How many observations are there, how many variables, and how many of the variables are categorical?Observations, 8; Variables 4; Categorical variables 2
Each order is one observation, so .
Four things are written down about each order: drink, size, price and number of items. That is 4 variables.
The drink puts each order in a group with no order (nominal), and the size puts it in an ordered group (ordinal): both are categorical. The price and the number of items are amounts you can average, so they are numerical (the price continuous, the items a discrete count).
So 2 of the 4 variables are categorical.
1. Data and variables · Counts are discrete, measurements are continuous · QuizWhich of these is a continuous variable?B. The mass of an apple, in gramsA mass can be 151.3 g or 151.32 g: any value in a range. The emails and pages are counts, so discrete. Shoe sizes are a trap: feet are continuous, but the size is chosen from a fixed list of steps, so the recorded variable is discrete (and some would call it ordinal). What matters is the values that can actually appear in your data.
1. Data and variables · Ordered categories and numbers that are only labels · QuizA team’s shirt numbers are 1, 4, 7, 9, 10 and 23. What kind of variable is the shirt number?D. NominalThe digits only name a player. Number 10 is not “more” than number 9 in any sense the data cares about, and the mean, 9, does not describe anything. It is nominal. The tempting answer, discrete, is about the digits, not about what they mean: always ask what a value stands for.
1. Data and variables · You study a sample to learn about a population · QuizA poll asks 1000 voters and finds 52% plan to vote yes. In the language of statistics, the 52% is…B. A statistic, because it was calculated from a sampleIt comes from 1000 people, a sample, so it is a statistic. The parameter is the share of all voters who plan to vote yes, which nobody knows. Ask another 1000 and you would get a slightly different statistic, perhaps 50% or 54%. Measuring how much it could wobble is a big part of this course.
1. Data and variables · A tidy table has one row per observation · QuizA table of exam results has the columns Student, Maths, Physics, Chemistry, with one mark per cell. To make it tidy for “mark by subject”, which columns should it have?B. Student, Subject, MarkIf the question is about marks across subjects, “subject” is a variable, so it gets its own column, and each row is one student in one subject. The wide table hides the subject in the column names. Which shape is tidy depends on what counts as an observation for your question, so ask that first. Packing values into one cell is never tidy.
1. Data and variables · Every measurement has error · QuizA kitchen scale always reads 15 g too heavy. You weigh a bag of flour 10 times and average the readings. What happens to the 15 g?B. It stays: the average is still about 15 g too heavyThe 15 g is systematic: every reading has it, so the average has it too. Averaging only cancels errors that point in different directions. To fix bias you need a different measurement, such as checking the scale against a known 1 kg weight (calibration). More data of the same biased kind makes you more sure of the wrong answer.
1. Data and variables · Where data comes from shapes what it can tell you · QuizA school wants to know if a new reading app improves reading scores. Which design lets it say the app caused any change?C. Randomly give the app to half the classes, and compare their scores with the other halfOnly the experiment decides who gets the app by chance, so the two groups are alike in every other way on average. Students who choose the app may already be keener readers, so the first comparison mixes up the app with keenness. Opinions and usage logs say nothing about scores without the app. Designing studies has its own module later.
1. Data and variables · A first look at a data set · ProblemFifteen students say how they travel to school: bus, walk, bus, car, bike, bus, walk, bus, bike, car, bus, walk, bus, bike, walk. Find the frequency of “bus” and of “walk”, and the share of the students who travel by bus, as a percentage.Frequency of bus 6; Frequency of walk 4; Share who travel by bus 40 %
Count each group: bus appears 6 times, walk 4 times, bike 3 times and car 2 times.
Check: , the number of students, so nothing was missed or counted twice.
The share by bus is its frequency divided by the number of students:
1. Data and variables · Try it: count and check a column · Code challengeFinish frequencies(values): return a std::map whose keys are the distinct values and whose values are how many times each appears.One solution:
The first time a value is seen, counts[value] adds it to the map with a count of 0, so ++ makes it 1; each later sighting adds one more. (In many languages reading a missing key is an error or a blank, which you must start at 0 yourself.) The counts always add up to the number of observations, a quick check worth doing on real data.
1. Data and variables · Try it: count and check a column · Code challengeFinish cleanHeights(heights): return a new vector without the missing values (std::nullopt) and without any height outside 50 to 250 cm (inclusive), keeping the order.One solution:
Check that there is a value first: h on its own is false for std::nullopt, and *h may only be read once you know a number is there. Asking about the value, not the number, matters: a height of 0 is impossible, but for a variable where 0 can happen, such as siblings, if (*h) would wrongly drop every 0. In real work, write down every value you removed and why: silently dropping data is how analyses go wrong, and a typo like 1755 may be better fixed than dropped.
1. Data and variables · Practice problems · ProblemA column of 10 heights, in cm, reads: 172.4, missing, 165.0, 1680, 158.2, 181.5, missing, 17.3, 169.9, 175.0. Any height outside 50 to 250 cm is impossible. How many values are missing, how many are impossible, and how many usable heights are left?Missing 2; Impossible 2; Usable 6
Two cells are empty: 2 missing values.
1680 cm and 17.3 cm are outside 50 to 250 cm: 2 impossible values. The first looks like 168.0 typed without its point, the second like 173 with the point in the wrong place.
That leaves usable heights: 172.4, 165.0, 158.2, 181.5, 169.9 and 175.0.
Before dropping the two impossible ones, write them down: if the typos are clear, they may be better fixed than removed.
1. Data and variables · Practice problems · ProblemA farm scale is known to read 2 kg too heavy. A sack is weighed five times: 27.1, 26.8, 27.3, 26.9 and 26.9 kg. What is the average of the readings, and what is your best estimate of the sack’s true mass?Average reading 27 kg; True mass 25 kg
Add the readings and divide by how many there are:
The average has cancelled most of the random error, but every reading, and so the average, still carries the 2 kg bias.
Subtract it: the best estimate of the true mass is kg.
1. Data and variables · Practice problems · ProblemA spreadsheet has one row for each of 6 shops, and four columns, 2021, 2022, 2023 and 2024, holding each shop’s sales that year. You make it tidy, with the columns shop, year and sales. How many rows does the tidy table have, and how many columns?Rows 24; Columns 3
The years are values of a variable, year, so they move out of the column names into a column of their own.
Each observation is one shop in one year. There are 6 shops and 4 years, so rows.
The columns are the variables: shop, year and sales, so 3 columns. Check: the wide table held sales figures, and the tidy one has one per row, 24.
1. Data and variables · Practice problems · ProblemA town has 24 000 voters. A poll asks 600 of them, chosen at random, and 255 say they will vote yes. What is the sample size ? What percentage of the population did the poll ask? What percentage of the sample says yes? 600; Share of the population asked 2.5 %; Share of the sample saying yes 42.5 %
The poll asked 600 people, the sample: . It wants to know about all voters, the population.
The share of the population asked is .
The share of the sample saying yes:
This 42.5% is a statistic, worked out from the sample. The share of all 24 000 voters who will vote yes is the parameter: unknown, probably close to 42.5%, but not exactly it.
2. Seeing data: charts and distributions · A frequency table counts each value · QuizUsing the table, what share of the 20 students rated the coffee “fair” or worse?B. 0.35The cumulative frequency at “fair” is 7: the 2 “poor” plus the 5 “fair”. As a share, . The tempting 0.25 is only the “fair” row. Cumulative columns answer “how many at or below this value” in one look, which only makes sense when the values have an order.
2. Seeing data: charts and distributions · A frequency table counts each value · Problem25 people rate a film: 3 say poor, 6 fair, 11 good and 5 excellent. Find the relative frequency of “good” (as a decimal), the cumulative frequency at “good”, and the share of the people who rated the film “good” or worse (as a decimal).Relative frequency of good 11/25 ≈ 0.44; Cumulative frequency at good 20; Share good or worse 20/25 ≈ 0.8
The relative frequency of good is its frequency over the total:
The cumulative frequency at good adds poor, fair and good: .
“Good or worse” is exactly what that cumulative frequency counts, so the share is .
2. Seeing data: charts and distributions · Bar charts show categorical data · QuizYou chart the favourite fruit of 200 people: apple, banana, cherry, mango. How should the bars be arranged?B. From most to least popular, since the fruits have no natural orderFruit is nominal: no order is built in, so sorting by frequency is the order that helps a reader rank them. Alphabetical order is easy to make but hides the ranking. For an ordinal variable such as a rating or a school year, keep the natural order instead: sorting it by height would scramble the scale.
2. Seeing data: charts and distributions · Histograms show numerical data in bins · QuizWith bins , , , which bin holds a commute of exactly 20 minutes?B. [20, 30)The square bracket includes its edge and the round one excludes it, so contains 20 and stops just before it. Every value lands in exactly one bin, so the counts add up to . Counting a boundary value in both bins is a common bug when writing histogram code by hand.
2. Seeing data: charts and distributions · Histograms show numerical data in bins · ProblemTwelve deliveries took these times, in minutes: 8, 12, 15, 20, 21, 9, 30, 18, 25, 10, 14, 29. How many fall in each of the bins , , and ? 2; 5; 4; 1
Put each time in its bin. The values on an edge go to the bin on their right: 10 to , 20 to and 30 to .
: 8 and 9, so 2. : 12, 15, 18, 10 and 14, so 5. : 20, 21, 25 and 29, so 4. : 30, so 1.
Check: , every delivery counted exactly once.
2. Seeing data: charts and distributions · The bin width changes the story · QuizYou draw a histogram of 40 exam marks with 40 bins. What is the most likely problem?B. Most bins hold 0 or 1 value, so the shape is lost in noiseWith about one value per bin, the chart becomes a row of 0s and 1s, and its ups and downs are chance, not shape. More bins show more detail, but detail and truth are not the same with little data. The frequencies still add up to 40 whatever the bins, which is why that answer is wrong.
2. Seeing data: charts and distributions · Dot plots and stem-and-leaf plots keep every value · QuizIn the stem-and-leaf plot of exam marks, how many students scored 80 or more?B. 6The stems 8 and 9 hold the marks from 80 up: four leaves on 8 (81, 83, 84, 88) and two on 9 (90, 95), so 6. Count leaves, not stems. A stem-and-leaf plot answers questions like this exactly, where a histogram with wide bins could only give an estimate.
2. Seeing data: charts and distributions · Shape: symmetric, skewed or bimodal · QuizMost people in a town earn between 20 000 and 50 000 a year, and a handful earn several million. The histogram of incomes is…B. Skewed rightSkew is named after the tail, not the peak. The bulk is on the left and the long thin tail stretches right towards the millions, so it is skewed right. People often get this backwards because the hump is on the left. Incomes, waiting times and file sizes are nearly always skewed right: they cannot go below 0 but can be very large.
2. Seeing data: charts and distributions · A box plot draws five numbers · QuizRoughly what share of the commutes are between 12 and 27 minutes, the two ends of the box?B. 50%By definition the box runs from the lower quartile to the upper quartile, so it holds the middle half of the data, whatever its length. A long box means the middle half is spread out, not that it holds more people. The right whisker is longer than the left, and the median sits left of the box’s centre: both are signs of skew to the right.
2. Seeing data: charts and distributions · Charts can mislead · QuizAn advert’s bar chart shows two brands at 50% and 52%, with the y-axis running from 49% to 53%. How many times taller is the second bar drawn than the first?B. 3 timesBars are drawn from the axis’s bottom, 49%. The first bar is unit tall and the second , so the second looks 3 times taller, while the real ratio is . For a line chart, a zoomed axis can be fine, since the eye reads position, not length; for bars, start at 0.
2. Seeing data: charts and distributions · Try it: count values into bins · Put in orderPut the steps of drawing a histogram by hand in order.1. Find the smallest and largest values 2. Choose a bin width and the first bin’s left edge 3. Count the values in each bin, edges going to the bin on their right 4. Check that the counts add up to n 5. Draw touching bars, one per binYou need the range before choosing bins that cover it, and the bins before you can count. The check that counts add up to catches values counted twice or missed at the edges, so it comes before drawing.
2. Seeing data: charts and distributions · Try it: count values into bins · Code challengeFinish binCounts(values, start, width, bins): return a vector of bins counts, where bin i holds the values v with start + i * width <= v < start + (i + 1) * width. Values outside every bin are ignored.One solution:
Solution
1#include<cmath>2#include<vector>34std::vector<int>binCounts(const std::vector<double>& values,5double start,double width,int bins){6 std::vector<int>counts(bins,0);7for(double v : values){8int i = std::floor((v - start)/ width);9if(i >=0&& i < bins) counts[i]++;10}11return counts;12}
(v - start) / width says how many widths v is past the start, and std::floor turns that into the bin number: 15 with bins of 10 is 1.5 widths in, so bin 1. Flooring is what makes the left edge belong to the bin: 10 is exactly 1.0, so bin 1, not bin 0. Storing the quotient straight into an int would cut the fraction off towards zero, putting −3 (−0.3 widths) in bin 0; std::floor rounds down to −1, which is dropped. Checking i < bins drops values past the last bin; without it, counts[3]++ on a vector of 3 would write past its end, which stops the program here and quietly corrupts memory elsewhere.
2. Seeing data: charts and distributions · Try it: count values into bins · Code challengeFinish relativeFrequencies(counts): return each count divided by the total of all the counts. If the total is 0, return all zeros.One solution:
Solution
1#include<vector>23std::vector<double>relativeFrequencies(4const std::vector<int>& counts){5int total =0;6for(int c : counts) total += c;7 std::vector<double>shares(counts.size(),0.0);8if(total ==0)return shares;9for(std::size_t i =0; i < counts.size(); i++){10 shares[i]=double(counts[i])/ total;11}12return shares;13}
Add up the counts once, then divide each by that total. Both are ints, so counts[i] / total would be integer division: 2 / 20 is 0, and every share but a whole one comes out 0. double(counts[i]) makes the division decimal. A total of 0 would make every share 0.0 / 0, which is nan (and with two ints, a division by zero that stops the program), so that case is handled first. The tests use EXPECT_NEAR because decimals like cannot be stored exactly in binary, so arithmetic on them can land a hair off (0.1 + 0.2 is 0.30000000000000004, and shares may add up to 0.9999999999999999): compare decimals with a tolerance, never with exact equality.
2. Seeing data: charts and distributions · Practice problems · ProblemA stem-and-leaf plot of 15 test marks (key: 6 | 3 means 63) has these rows: 4 | 7 9, 5 | 2 5 8, 6 | 0 3 3 6 9, 7 | 1 4 8 and 8 | 2 5. How many marks are in the 60s, how many are 70 or more, and what is the median mark?Marks in the 60s 5; Marks of 70 or more 5; Median 63
The stem 6 has five leaves, 0 3 3 6 9: the marks 60, 63, 63, 66 and 69. So 5 marks are in the 60s.
Marks of 70 or more sit on the stems 7 and 8: three leaves (71, 74, 78) plus two (82, 85), so 5.
In order the marks are 47, 49, 52, 55, 58, 60, 63, 63, … The middle of 15 values is the 8th, with 7 on each side: the median is 63.
2. Seeing data: charts and distributions · Practice problems · ProblemA bar chart shows this year’s sales, 126, beside last year’s, 120. Its y-axis starts at 110. How many times taller is this year’s bar drawn, and what is the true ratio of the two sales figures?Drawn ratio 1.6; True ratio 1.05
The bars start at the axis’s bottom, 110. This year’s bar is units tall and last year’s .
So it is drawn times taller: it looks like growth of 60%.
The true ratio is : growth of 5%. An axis starting at 0 would show that honestly.
2. Seeing data: charts and distributions · Practice problems · ProblemA box plot of 200 commute times has , median 22 and minutes. About how many of the commutes are under 14 minutes, how many are between 14 and 35 minutes, and how many are over 22 minutes?Under 14 minutes 50; Between 14 and 35 minutes 100; Over 22 minutes 100
About a quarter of the values are below : commutes under 14 minutes.
The box, from to , holds the middle half: about commutes between 14 and 35 minutes.
About half the values are above the median: about 100 commutes over 22 minutes.
These are “about”, because values can tie with a quartile, and methods for quartiles differ a little.
2. Seeing data: charts and distributions · Practice problems · ProblemA poster shows sales growing by 50% by drawing this year’s coin 1.5 times as wide and 1.5 times as tall as last year’s. How many times bigger does the new coin’s area look? By what factor should the width and the height have been scaled, so that the area grew by exactly 50%?Area factor 2.25; Honest scale factor sqrt(1.5) ≈ 1.22474
Scaling the width and the height by 1.5 multiplies the area by : the coin looks 125% bigger, not 50%.
To make the area 1.5 times as big, scale each side by , where :
Better still, draw bars: people judge lengths far more accurately than areas.
3. The centre: mean, median and mode · The mean shares the total out equally · QuizFour parcels have a mean mass of 2 kg. A fifth parcel of 7 kg is added. What is the new mean?B. 3 kgWork with totals: four parcels of mean 2 kg weigh 8 kg together. Add 7 kg and the total is 15 kg over 5 parcels, so kg. The tempting 4.5 kg is the mean of 2 and 7, which treats the four old parcels as if they were one. Converting a mean back into a total, , is the trick behind many mean questions.
3. The centre: mean, median and mode · The mean shares the total out equally · ProblemFive quiz scores have a mean of 72. Four of them are 65, 80, 70 and 74. What is the fifth?The fifth score 71
Five scores with mean 72 add up to .
The four you know add up to .
So the fifth is . Check: .
3. The centre: mean, median and mode · The mean shares the total out equally · Code challengeFinish mean(values): return the sum of the values divided by how many there are.One solution:
Solution
1#include<vector>23doublemean(const std::vector<double>& values){4double sum =0;5for(double v : values) sum += v;6return sum / values.size();7}
Add up in a loop, then divide once at the end. sum is a double, so the division keeps its fraction; an int sum of whole numbers would divide as whole numbers, and the mean of 3, 4, 5, 5 and 7 would come out 4 instead of 4.8. The decimal test is why the tests use EXPECT_NEAR: in binary floating point is 0.6000000000000001, so its mean is not exactly 0.2. An empty vector gives 0.0 / 0, which is nan (not a number): the mean of nothing is undefined, and returning nan says so.
3. The centre: mean, median and mode · The median is the middle value · QuizWhat is the median of 12, 7, 3, 9, 15, 4?B. 8Sort first: 3, 4, 7, 9, 12, 15. There are 6 values, so the two middle ones are the 3rd and 4th, 7 and 9, and the median is . Taking the middle of the list as given, 3 and 9, is the classic mistake: the median is about order, so sorting comes first, always.
3. The centre: mean, median and mode · The median is the middle value · ProblemFind the median of 14, 3, 9, 21, 6, 11, 8, 17. Then a ninth value, 2, is added: what is the median now?Median of the 8 values 10; Median with 2 added 9
Sorted: 3, 6, 8, 9, 11, 14, 17, 21. With 8 values, the two middle ones are the 4th and 5th, 9 and 11:
With 2 added: 2, 3, 6, 8, 9, 11, 14, 17, 21. Now , and the median is at position : the value 9.
One new small value moved the median only from 10 to 9.
3. The centre: mean, median and mode · Computing the median in code · Find the bugThis median of whole numbers works for {3, 5, 4}, but returns 8 for {10, 9, 2, 8} instead of 8.5, and 1 for {1, 2} instead of 1.5. Which line is wrong?Line 6: return (sorted[mid - 1] + sorted[mid]) / 2.0;The two middle values are ints, so their sum, 17, is an int, and 17 / 2 is integer division: 8, with the half cut off. The function returns a double, but the conversion only happens after the damage is done. Dividing by 2.0 makes the division decimal. Line 4’s sorted.size() / 2 is integer division too, and there it is exactly right: 5 values give mid 2, the middle index. The copy on line 2 is right as well: a median should not reorder its caller’s data.
3. The centre: mean, median and mode · Computing the median in code · Code challengeFinish median(values): sort a copy of the values, then return the middle one, or the mean of the two middle ones when there is an even number. Do not change the vector you are given.One solution:
For 6 values, mid is 3, so the two middle ones are at indexes 2 and 3 (vectors count from 0). For 5 values, mid is 2, because 5 / 2 between whole numbers drops the half: the third value, exactly the middle. The values themselves are doubles, so halving their sum keeps its fraction. values is const, so the function cannot sort it; copying it into sorted keeps the caller’s data in its order. Sorting is the slow part, about steps; there are cleverer ways to find a median without a full sort (std::nth_element), but this is the clear one.
3. The centre: mean, median and mode · The mode is the most common value · QuizA shoe shop wants to know which size to reorder most of. Last month it sold sizes 38, 39, 39, 40, 41, 41, 41, 42, 44, 46. Which measure answers its question, and what is it?C. The mode, 41The shop needs the size people buy most often: the mode, 41, which sold three pairs. The mean happens to be close here, , but it can be a size nobody wears, and with a wider spread of sizes it could easily land on a size that sells little. The median is also 41 here; it is the mode that answers “which one most often”.
3. The centre: mean, median and mode · One extreme value drags the mean · QuizA data set of nine heights has median 171 cm and mean 172 cm. One height of 180 cm was mistyped as 1800 cm. Which measure is badly wrong?B. Only the meanThe typo adds cm to the total, so the mean jumps by cm, to about 352 cm, an impossible average height. The median depends only on which value is in the middle: 180 cm and 1800 cm are both above 171 cm, so the middle value does not change. This is also why a mean far from the median is a hint to look for errors.
3. The centre: mean, median and mode · Skew pulls the mean towards the tail · QuizA news report says the mean house price in a city is 450 000 and the median is 310 000. What does that suggest?B. The prices are skewed right: a few very expensive housesThe mean is well above the median, so something is pulling it up: a tail of expensive houses, a right skew. The median says a typical house costs about 310 000; the mean is what you would get if all the money spent were shared out equally, which no buyer pays. This is why official statistics on prices and incomes quote the median.
3. The centre: mean, median and mode · A weighted mean lets some values count more · Code challengeFinish weightedMean(values, weights): multiply each value by the weight at the same index, add those up, and divide by the sum of the weights.One solution:
Solution
1#include<vector>23doubleweightedMean(const std::vector<double>& values,4const std::vector<double>& weights){5double total =0;6double weightSum =0;7for(std::size_t i =0; i < values.size(); i++){8 total += values[i]* weights[i];9 weightSum += weights[i];10}11return total / weightSum;12}
Keep two running totals, the weighted sum and the sum of the weights, and divide once. Dividing by the number of values instead of the weight sum only works when the weights add up to the count; with the class sizes it would give . Weights that already add up to 1, like percentages, make the division by 1 harmless.
3. The centre: mean, median and mode · A trimmed mean drops the extremes · Fill the blanksFinish trimmedMean, which drops k values from each end of the sorted data.1: begin(), 2: k, 3: k, 4: size()std::sort(values.begin(), values.end()) sorts the whole vector, from its first value to its end. kept(values.begin() + k, values.end() - k) copies the values from index k up to, but not including, the k last ones, so k values are dropped at each end. Divide by the number kept, not by values.size(): dividing 38 by 10 would give 3.8, below almost every value. values comes without &, so it is the function’s own copy: sorting it leaves the caller’s data alone.
3. The centre: mean, median and mode · Choosing a measure of centre · QuizA city plans water supply and needs to know how much water its 100 000 homes use in total. Which average of household use is the one to multiply by 100 000?B. The meanOnly the mean is tied to the total: . The few homes with pools really do use that water, and the plan must supply it. The median would describe a typical home better, but multiplying it by 100 000 underestimates the total for right-skewed use. The right measure depends on the question, not only on the shape.
3. The centre: mean, median and mode · Practice problems · ProblemA team scored these numbers of goals in 10 matches: 2, 0, 3, 1, 12, 2, 4, 1, 3, 2. Find the mean, the median and the mode.Mean 3; Median 2; Mode 2
The total is , so the mean is goals.
Sorted: 0, 1, 1, 2, 2, 2, 3, 3, 4, 12. The 5th and 6th values are 2 and 2, so the median is 2.
The value 2 appears three times, more than any other: the mode is 2.
The mean is above the median because of the one 12-goal match. A typical match had about 2 goals.
3. The centre: mean, median and mode · Practice problems · ProblemA course counts homework 25%, a project 25% and the final exam 50%. A student scores 88 on homework, 72 on the project and 65 on the final. What is the course grade? What final-exam mark would have given a grade of exactly 75?Course grade 72.5; Final mark for 75 70
For a grade of 75 with a final mark :
The final carries half the weight, so 5 more marks on it lift the grade by 2.5.
3. The centre: mean, median and mode · Practice problems · ProblemOne class of 12 students has a mean mark of 68; another class of 18 students has a mean of 78. What is the mean mark of all 30 students together?Mean of all 30 74
The totals are and .
Not : the bigger class pulls the combined mean towards its 78. It is a weighted mean, with the class sizes as the weights.
3. The centre: mean, median and mode · Practice problems · ProblemTen delivery times, in minutes: 12, 15, 9, 14, 48, 13, 16, 11, 14, 38. Find the mean, the median and the 20% trimmed mean.Mean 19 min; Median 14 min; 20% trimmed mean 14 min
Sorted: 9, 11, 12, 13, 14, 14, 15, 16, 38, 48. The total is 190, so the mean is minutes.
The 5th and 6th values are 14 and 14, so the median is 14 minutes.
Drop 9 and 11 at the bottom and 38 and 48 at the top. The six values left add up to :
Two slow deliveries lift the mean 5 minutes above the other two summaries: the median or the trimmed mean is the better typical time.
4. Spread: range, variance and standard deviation · The centre is not the whole story · QuizTwo trains both arrive on average exactly on time. Train A is always within 1 minute; train B is often 15 minutes early or late. Which statement is right?B. Train B has the larger spread, and is less reliableReliability is about spread, not centre: both means are zero minutes late, but B’s arrival times vary far more. An average of “on time” can hide early and late trains cancelling out. Whenever you see a mean, ask how spread out the values around it are.
4. Spread: range, variance and standard deviation · The range is simple but fragile · QuizNine students’ reaction times are between 0.21 s and 0.30 s. A tenth student sneezes and records 1.40 s. What happens to the range?B. It goes from 0.09 s to 1.19 sBefore: s. After, the maximum is 1.40 s, so the range is s, more than 13 times bigger, because of one value. The range is not resistant. The measures in the next slides use all the values, or only the middle ones, to avoid this.
4. Spread: range, variance and standard deviation · Quartiles and the interquartile range · QuizWhat is the IQR of 1, 3, 4, 6, 7, 9, 10, 15 using the median-of-halves method?B. 6With 8 values, the halves are 1, 3, 4, 6 and 7, 9, 10, 15. is the median of the lower half, , and , so . 14 is the range. With an even no value is left out: the median, 6.5, falls between the two halves.
4. Spread: range, variance and standard deviation · Quartiles and the interquartile range · ProblemNine values, sorted: 4, 7, 8, 10, 12, 15, 16, 21, 40. Using the median-of-halves method, find , , the IQR and the range. 7.5; 18.5; IQR 11; Range 36
The median is the 5th value, 12. The lower half is 4, 7, 8, 10 and the upper half is 15, 16, 21, 40.
So , and the range is .
The range is more than three times the IQR, and almost all of that comes from the single value 40.
4. Spread: range, variance and standard deviation · The 1.5 × IQR rule flags outliers · Fill the blanksFinish fences, which returns the lower and upper fences for the quartiles q1 and q3.1: q3 - q1, 2: 1.5, 3: q3The IQR is , never negative. The lower fence goes down from and the upper fence up from , each by 1.5 IQRs. Measuring both fences from the median is a common slip: it ignores skew, which the quartiles capture.
4. Spread: range, variance and standard deviation · The 1.5 × IQR rule flags outliers · ProblemFor the nine values 4, 7, 8, 10, 12, 15, 16, 21, 40, with and , find the lower and upper fences, and the value where the upper whisker of the box plot stops.Lower fence -9; Upper fence 35; Upper whisker stops at 21
The IQR is , and .
No value is below −9. The value 40 is above 35, so it is flagged and drawn as a point. The largest value inside the fence is 21, so the upper whisker stops at 21.
4. Spread: range, variance and standard deviation · A sample divides by n − 1 · QuizYou measure 12 apples picked at random from an orchard to estimate how much apple masses vary across the whole orchard. Which do you divide the sum of squared deviations by?B. 11The 12 apples are a sample and the orchard is the population, so divide by . Dividing by 12 would give the variance of these 12 apples exactly, but would underestimate the orchard’s, on average by a factor of . When the data is the whole population, say every employee of a firm, divide by .
4. Spread: range, variance and standard deviation · Try it: the sample standard deviation · Find the bugThis returns 0 for every data set. Which line is wrong?Line 7: for (double v : values) sum += (v - mean) * (v - mean);The deviations from the mean always add up to 0, up to rounding, so without squaring the sum is (close to) 0 for any data. Squaring makes every deviation count positively. C++ has no power operator: square with d * d or std::pow(d, 2), never d ^ 2, which is bitwise XOR (on ints it quietly gives a wrong number; on doubles it does not compile). Using std::abs(v - mean) would also stop the cancelling, but gives the mean absolute deviation, a different measure.
4. Spread: range, variance and standard deviation · Try it: the sample standard deviation · Code challengeFinish sampleSd(values): compute the mean, add up the squared deviations from it, divide by n - 1, and return the square root.One solution:
Solution
1#include<cmath>2#include<vector>34doublesampleSd(const std::vector<double>& values){5int n = values.size();6double mean =0;7for(double v : values) mean += v;8 mean /= n;9double sum =0;10for(double v : values) sum +=(v - mean)*(v - mean);11return std::sqrt(sum /(n -1));12}
For bakery B the deviations are −40, −20, 0, 20, 40, their squares add to 4000, and g. Dividing by n would give : close, but too small. sum is a double, so sum / (n - 1) keeps its fraction even though n - 1 is an int. Forgetting the square root leaves the variance, 1000 square grams, which is the wrong unit as well as the wrong size.
4. Spread: range, variance and standard deviation · A z-score measures distance in standard deviations · Code challengeFinish zScores(values, mean, sd): return each value’s z-score, in the same order.One solution:
Subtract first, then divide: (x - mean) / sd. Without the brackets, x - mean / sd divides only the mean, giving . Turning a whole data set into z-scores is called standardising; the result always has mean 0 and standard deviation 1, which is why many methods standardise first.
4. Spread: range, variance and standard deviation · The 68–95–99.7 rule for bell-shaped data · QuizAdult heights in a country are bell-shaped with mean 170 cm and SD 7 cm. About what share of adults are taller than 184 cm?B. 2.5%184 cm is SDs above the mean. About 95% are within 2 SDs, so 5% are outside, and by symmetry half of that, 2.5%, are above. The tempting 5% counts both tails. Draw the curve and shade the part you want: it prevents most mistakes with the rule.
4. Spread: range, variance and standard deviation · Chebyshev’s inequality works for any shape · QuizDelivery times have mean 30 minutes and SD 5 minutes, and you know nothing about their shape. What can you say for certain about deliveries between 20 and 40 minutes?B. At least 75% of them20 to 40 is 2 SDs either side, so and Chebyshev guarantees at least . The 95% needs a bell shape, which you were not told; delivery times are usually skewed right, so it might not hold. “At least” is the point: the true share is often higher.
4. Spread: range, variance and standard deviation · Practice problems · ProblemA sample of five parcels weighs 6, 8, 9, 11 and 16 kg. Find the mean, the sample variance and the sample standard deviation . Then find the variance you would get if these five parcels were the whole population, dividing by . 10 kg; 14.5 kg²; sqrt(14.5) ≈ 3.80789 kg; 11.6 kg²
The mean is kg. The deviations are −4, −2, −1, 1 and 6 (they add up to 0), and their squares are 16, 4, 1, 1 and 36.
As a whole population, divide by instead: , a little smaller.
4. Spread: range, variance and standard deviation · Practice problems · ProblemIn a running club, 100 m times have mean 13.0 s and SD 0.4 s, and long jumps have mean 5.0 m and SD 0.5 m. Mia runs 100 m in 12.4 s and jumps 5.6 m. Find the z-score of each result. for the run −1.5; for the jump 1.2
Her time is 1.5 SDs below the mean, and in a race a lower time is better. Her jump is 1.2 SDs above the mean.
So the run is the more unusual result: 1.5 SDs better than average, against 1.2 for the jump.
4. Spread: range, variance and standard deviation · Practice problems · ProblemThe weights of bags of flour are bell-shaped, with mean 500 g and SD 10 g. Using the 68–95–99.7 rule, about what percentage of bags weigh between 480 and 520 g? More than 510 g? Between 490 and 520 g?480 to 520 g 95 %; Over 510 g 16 %; 490 to 520 g 81.5 %
480 and 520 g are at and : about 95% of bags.
510 g is at . 68% of bags lie within 1 SD, so lie outside, half of them above: 16%.
From 490 g () to 500 g is half of 68%, 34%; from 500 g to 520 g () is half of 95%, 47.5%:
4. Spread: range, variance and standard deviation · Practice problems · ProblemWaiting times at a clinic have mean 40 minutes and SD 6 minutes, and you know nothing about their shape. What is the smallest percentage of waits that Chebyshev’s inequality guarantees are between 28 and 52 minutes? Between 31 and 49 minutes?28 to 52 minutes 75 %; 31 to 49 minutes 500/9 ≈ 55.5556 %
28 and 52 are SDs either side of 40, so : at least .
31 and 49 are SDs either side, so :
These are guarantees for any shape. If the waits were bell-shaped, the true shares would be about 95% and 87%.
5. Two variables: scatter plots and correlation · A scatter plot shows two numerical variables · QuizYou study whether the outside temperature affects how many ice creams a kiosk sells each day. Which goes on the x-axis?B. TemperatureTemperature is the explanatory variable: the idea is that it drives sales, not the other way round. So it goes across and sales go up. Swapping them does not change the points’ pattern or the correlation, but it does change a fitted line (regression, a later module), and readers expect the cause-like variable on x.
5. Two variables: scatter plots and correlation · Describe direction, form and strength · QuizFor used cars, the older the car, the lower its price, and the points lie close to a gently curving line. How would you describe it?B. Negative, curved, strongPrice falls as age rises: negative. The points follow a curve (cars lose value fast at first, then slowly): curved form. They lie close to it: strong. Direction, form and strength are separate questions; a relationship can be strong and still not linear, which matters because the correlation coefficient only measures straight lines.
5. Two variables: scatter plots and correlation · Covariance: do the deviations agree · QuizMost points of a scatter plot lie above and left of the means, or below and right of them. The covariance is…B. NegativeAbove and left means and : a negative product. Below and right gives positive times negative: negative again. So the sum, and the covariance, is negative, and y tends to fall as x rises. The sign of each product is the sign of “do x and y agree about being above average?”.
5. Two variables: scatter plots and correlation · Covariance: do the deviations agree · ProblemFive points have = 2, 4, 6, 8, 10 and = 5, 9, 7, 13, 11. Find , the sum of the products of deviations , and the sample covariance . 9; Sum of products 32; 8
The means are and .
The deviations of are −4, −2, 0, 2, 4, and of are −4, 0, −2, 4, 2. Their products are 16, 0, 0, 8 and 8.
Positive: the points sit mostly where and are both above, or both below, their means.
5. Two variables: scatter plots and correlation · Correlation is covariance without units · QuizWhich of these are true of Pearson’s ?B. Swapping x and y leaves the same; D. has no unitsThe formula is symmetric in x and y, so swapping them changes nothing, and dividing by both standard deviations cancels every unit: rescaling a variable (metres for centimetres, °F for °C) leaves alone. is not a percentage of points; it is a measure of how tightly the points follow a line. (Its square, 0.64, has a meaning in regression, later.)
5. Two variables: scatter plots and correlation · Correlation is covariance without units · ProblemFive points have = 1, 2, 3, 4, 5 and = 10, 8, 9, 5, 3. Find , , and Pearson’s .Sum of products -17; 34; -17/sqrt(340) ≈ −0.921954
The deviations of are −2, −1, 0, 1, 2, and of are 3, 1, 2, −2, −4.
The products are −6, −1, 0, −2 and −8, which add up to −17. The squared deviations are 9, 1, 4, 4 and 16, which add up to 34.
A strong negative linear relationship: falls as rises, and the points lie close to a line.
5. Two variables: scatter plots and correlation · Correlation only sees straight lines · QuizA report says the correlation between two variables is . What can you conclude?B. There is little or no linear relationship; there could still be a curved one near 0 rules out a straight-line pattern, nothing more. The parabola above has and a perfect relationship. Statisticians say “uncorrelated” for , which is weaker than “independent”. The famous Anscombe’s quartet is four data sets with the same means, SDs and , whose scatter plots look completely different.
5. Two variables: scatter plots and correlation · Try it: compute the correlation · Code challengeFinish correlation(xs, ys): return Pearson’s r, the sum of the products of deviations divided by the square root of the product of the two sums of squared deviations.One solution:
Solution
1#include<cmath>2#include<vector>34doublecorrelation(const std::vector<double>& xs,5const std::vector<double>& ys){6int n = xs.size();7double mx =0, my =0;8for(int i =0; i < n; i++){9 mx += xs[i];10 my += ys[i];11}12 mx /= n;13 my /= n;14double sxy =0, sxx =0, syy =0;15for(int i =0; i < n; i++){16 sxy +=(xs[i]- mx)*(ys[i]- my);17 sxx +=(xs[i]- mx)*(xs[i]- mx);18 syy +=(ys[i]- my)*(ys[i]- my);19}20return sxy / std::sqrt(sxx * syy);21}
One loop builds all three sums. The of the covariance and of both standard deviations cancel, so they never appear. Common slips: dividing by std::sqrt(sxx) * syy (forgetting to root both), or using raw values instead of deviations, which gives a number that changes when you shift the data. If every x is the same, sxx is 0 and r is 0.0 / 0, which is nan: no spread in x, no correlation to speak of.
5. Two variables: scatter plots and correlation · Rank correlation for any rising pattern · Code challengeFinish ranks(values): return the rank of each value, in the original order, where the smallest value has rank 1. You can assume there are no ties.One solution:
Solution
1#include<algorithm>2#include<utility>3#include<vector>45std::vector<int>ranks(const std::vector<double>& values){6 std::vector<std::pair<double,int>> order; // value, index7for(int i =0; i < values.size(); i++){8 order.push_back({values[i], i});9}10 std::sort(order.begin(), order.end());11 std::vector<int>result(values.size());12for(int position =0; position < order.size(); position++){13 result[order[position].second]= position +1;14}15return result;16}
Sort pairs of value and original index (std::sort orders pairs by their first, the value), then give each pair its position plus one, written back at its original index, its second. Sorting the values alone loses track of where each came from. With ties, the usual rule gives tied values the mean of the ranks they share (two values tied for 2nd and 3rd both get 2.5).
5. Two variables: scatter plots and correlation · Two-way tables relate two categorical variables · QuizOf the people who prefer tea, what share are 30 or over?B. 78%Now the group is “prefers tea”, the column, so divide by the column total: . The 58% answers a different question, the share of over-30s who prefer tea (). The two are easy to swap, and swapping them is the root of many famous errors, as the next module on conditional probability shows.
5. Two variables: scatter plots and correlation · Correlation is not causation · QuizAcross towns, the number of fire engines sent to a fire is positively correlated with the damage it does. What best explains this?B. A lurking variable: bigger fires get more engines and do more damageThe size of the fire drives both: big fires need many engines and cause much damage. Sending fewer engines would not reduce damage; it would increase it. Before reading a correlation as cause and effect, always ask what else could move both variables. Only a randomised experiment rules out lurking variables reliably.
5. Two variables: scatter plots and correlation · Simpson’s paradox: the trend can reverse · QuizYou have a kidney stone of unknown size. Based on this data, which treatment should you prefer?B. A, because it is better for each size of stoneWhatever your stone’s size, A did better for that size, so A is the better bet. The overall rate compares unlike groups: B’s patients were mostly easy cases. Simpson’s paradox is not a contradiction; it is a warning that combining groups can mix in a lurking variable. Which way to read the data depends on what causes what, which is why the later module on study design draws causal diagrams.
5. Two variables: scatter plots and correlation · Practice problems · ProblemTwo judges rank five bakers. Judge A ranks them 1, 2, 3, 4, 5, and judge B ranks the same five bakers, in the same order, 2, 1, 4, 3, 5. Find and Spearman’s . 4; 0.8
The differences are , , , and . Their squares add up to .
The judges agree closely: they only swap two pairs of neighbours.
5. Two variables: scatter plots and correlation · Practice problems · ProblemOf 300 shoppers, 120 saw an advert, and 48 of those bought the product. Of the 180 who did not see it, 36 bought it. What percentage of those who saw the advert bought? Of those who did not see it? And what percentage of the buyers had seen the advert?Saw it, and bought 40 %; Did not see it, and bought 20 %; Buyers who saw it 400/7 ≈ 57.1429 %
Of the 120 who saw it, bought; of the 180 who did not, bought. Buying is associated with seeing the advert.
Now the group is the buyers: of them, 48 of whom saw the advert:
An association, not proof that the advert worked: people already keen on the product may be the ones who notice its adverts.
5. Two variables: scatter plots and correlation · Practice problems · ProblemHospital A saves 190 of 200 mild cases and 240 of 400 severe cases. Hospital B saves 360 of 400 mild cases and 110 of 200 severe cases. Find each hospital’s overall survival rate, as a percentage.Hospital A 430/6 ≈ 71.6667 %; Hospital B 470/6 ≈ 78.3333 %
Within each group A does better: 95% against 90% for mild cases, 60% against 55% for severe ones.
Overall, A saves of its 600 patients and B saves of its 600:
B looks better overall only because two thirds of its patients were mild cases, while two thirds of A’s were severe: Simpson’s paradox, with severity as the lurking variable.
5. Two variables: scatter plots and correlation · Practice problems · ProblemFor study time (in hours) and marks, hour-marks, hours and marks. Find . Then study time is measured in minutes instead: find the new covariance and the new . 0.8; Covariance in minute-marks 360; New 0.8
In minutes every deviation is multiplied by 60, so every product is too: minute-marks.
But becomes minutes as well, so , unchanged: the 60s cancel.
6. Probability · Probability puts a number on chance · QuizYou toss a coin twice and record each result. Which is the sample space?B. {HH, HT, TH, TT}Each outcome records both tosses in order, so there are : HH, HT, TH, TT. The number of heads is a summary of the outcome, not the outcome itself, and its three values are not equally likely (one head happens two ways, HT and TH). Listing outcomes so they are equally likely is the key to the next slide.
6. Probability · Equally likely outcomes: count and divide · QuizTwo fair dice are rolled. What is the probability that the total is 10 or more?A. 1/6Count: a total of 10 happens 3 ways, 11 two ways and 12 one way, so 6 outcomes out of 36, and . The tempting treats the 11 possible totals as equally likely, which they are not. Count equally likely outcomes, never the possible values of a summary.
6. Probability · Equally likely outcomes: count and divide · ProblemTwo fair dice are rolled. What is the probability that the total is 8? That both dice show the same number?5/36 ≈ 0.138889; 1/6 ≈ 0.166667
A total of 8 happens 5 ways: (2, 6), (3, 5), (4, 4), (5, 3), (6, 2). So .
The same number happens 6 ways, (1, 1) up to (6, 6), so its chance is .
6. Probability · Three rules every probability obeys · QuizA weather model gives tomorrow: sunny 0.5, cloudy 0.3, rainy 0.3, snowy −0.1. Exactly one of the four will happen. What is wrong?B. A probability is negative, breaking the first ruleThey do add up to , which satisfies the second rule, but no probability can be below 0. Checking both, all non-negative and summing to 1 over disjoint outcomes that cover everything, is how you check any probability model, including one a program outputs.
6. Probability · The complement: one minus the chance · QuizSomeone says: “each roll has a 1/6 chance of a six, so in 6 rolls you are certain to get one.” What is the real chance?B. About 0.67. Adding six times counts the outcomes with two or more sixes several times over; the addition rule only works for disjoint events, and “a six on roll 1” and “a six on roll 2” can both happen. The complement avoids the double counting entirely.
6. Probability · The complement: one minus the chance · ProblemWhat is the probability of at least one head in 5 tosses of a fair coin? Of at least one six in 3 rolls of a fair die?At least one head 31/32 ≈ 0.96875; At least one six 91/216 ≈ 0.421296
The opposite of at least one head is no heads at all: 5 tails, with chance . So:
No six in 3 rolls has chance , so:
6. Probability · The addition rule: or · QuizIn a class, 60% of students play a sport, 30% play an instrument, and 20% do both. What share does at least one of the two?B. 70%. The 90% counts the 20% who do both twice, once with the sport players and once with the musicians. A share above 100% is an alarm bell that something was double counted. And the share who do neither is the complement, .
6. Probability · Independent events multiply · QuizEvents A and B both have probability 0.4, and they are disjoint: they cannot both happen. Are they independent?B. No: if A happens, B becomes impossible, so knowing A changes B’s chanceIndependence needs , but disjoint means . Knowing A happened tells you B did not: the strongest dependence there is. “Disjoint” and “independent” sound alike and are almost opposites; only events with probability 0 can be both.
6. Probability · Counting: arrangements and choices · QuizA club of 10 people picks a committee of 3, with no roles. How many different committees are possible?B. 120Order does not matter, so it is . The 720 is , the count if the three had roles (chair, secretary, treasurer), where each committee is counted in its orders. Ask “does swapping two people give a different result?” to decide.
6. Probability · Try it: choose and the birthday problem · Code challengeFinish choose(n, k): the number of ways to choose k of n things. Return 0 when k < 0 or k > n. Build it up as a product, one factor at a time, rather than computing big factorials.One solution:
Solution
1longlongchoose(int n,int k){2if(k <0|| k > n)return0;3longlong result =1;4for(int i =1; i <= k; i++){5 result = result *(n - k + i)/ i;6}7return result;8}
After step , result is , always a whole number, so the division is exact at every step, and whole numbers can be compared exactly. The order matters: multiply first, then divide. result * ((n - k + i) / i) would divide two ints first and cut off their fraction. Computing first is a bad idea: it is about , far beyond a long long (exact up to about : fits, does not) and beyond the up to which a double holds whole numbers exactly. Multiplying and dividing as you go keeps the numbers small.
6. Probability · Try it: choose and the birthday problem · Code challengeFinish sharedBirthday(n): the probability that at least two of n people share a birthday, using the formula above.One solution:
Solution
1doublesharedBirthday(int n){2double allDifferent =1;3for(int i =0; i < n; i++){4 allDifferent *=(365.0- i)/365;5}6return1- allDifferent;7}
Person i (counting from 0) must avoid the i birthdays already taken, so the factor is ; for i = 365 it is 0, which is why 366 people must share. Write it (365.0 - i) / 365: with (365 - i) / 365 both sides are ints, every factor after the first is 0, and the answer is 1 for any group of two or more. Forgetting the final 1 - returns the chance that everyone is different. The surprise, only 23 people for an even chance, is because there are pairs, each a chance for a match.
6. Probability · When counting is hard, simulate · Put in orderPut the steps of a Monte Carlo estimate in order.1. Write a function that performs the random experiment once 2. Decide how to tell whether the event happened in one run 3. Repeat the experiment many times, counting the runs where it happened 4. Divide the count by the number of runs 5. Run it again with more runs to see how much the estimate wobblesYou need the experiment and a test for the event before you can repeat them. The estimate is the share of hits. The last step matters: one estimate with no idea of its wobble is a number without its uncertainty, which is exactly what statistics tries to avoid.
6. Probability · Practice problems · ProblemOne card is drawn from a standard deck of 52. What is the probability that it is red or a face card (a jack, queen or king)? That it is neither?8/13 ≈ 0.615385; 5/13 ≈ 0.384615
Red: 26 cards. Face cards: 3 in each of the 4 suits, 12. Red face cards: 6, which are counted in both.
Neither is the complement: . Check: the black cards that are not face cards, ace to 10 in two suits, are 20, and .
6. Probability · Practice problems · ProblemA machine works only if all three of its parts work. The parts work independently, with probabilities 0.9, 0.95 and 0.8. What is the probability that the machine works? That at least one part fails? That all three parts fail?The machine works 0.684; At least one part fails 0.316; All three fail 0.001
At least one fails is the complement: .
Each part fails with probability , and the failures are independent too: .
6. Probability · Practice problems · ProblemA door code is 3 letters, each from A to F, and letters may repeat. How many codes are there? How many have three different letters? If a code is chosen at random, what is the chance that its letters are all different?Codes in all 216; All different 120; Probability 5/9 ≈ 0.555556
Each of the 3 positions has 6 choices: codes.
All different: 6 choices for the first letter, 5 for the second, 4 for the third, so , the permutations .
Every code is equally likely, so the chance is .
6. Probability · Practice problems · ProblemA committee of 3 is chosen at random from 6 women and 4 men. How many different committees are possible? How many are all women? What is the probability that the committee is all women?Committees 120; All women 20; Probability 1/6 ≈ 0.166667
Any 3 of the 10 people: committees.
All women means 3 of the 6 women: .
Every committee is equally likely, so the chance is .
7. Conditional probability and Bayes' theorem · Conditional probability: once you know something · QuizUsing the table, what is ?B. 60/110 ≈ 0.55The condition, “coffee”, is what you know, so the world shrinks to the 110 coffee drinkers, of whom 60 are under 30: . The 0.75 is , the condition the other way round. and are different numbers, and confusing them is the theme of this module.
7. Conditional probability and Bayes' theorem · Conditional probability: once you know something · ProblemOf 250 students, 120 are in their first year and 130 in their second. 90 of the first-years and 110 of the second-years passed an exam. Find , and . 0.75; 0.6; 0.8
First-years: 90 passed and 30 failed. Second-years: 110 passed and 20 failed. In all, 200 passed and 50 failed.
Given first year, the world is the 120 first-years: .
Given failed, it is the 50 who failed, 30 of them first-years: .
Overall, . Since , knowing the year changes the chance of passing: they are not independent.
7. Conditional probability and Bayes' theorem · Chances multiply along a chain · QuizA drawer holds 5 black and 3 white socks. You pull out two without looking. What is the chance both are white?B. 3/28: after one white sock, 2 white remain among 7. The is , which treats the draws as independent, as if the first sock were put back. Without replacement, every draw changes the next one’s chances.
7. Conditional probability and Bayes' theorem · Chances multiply along a chain · ProblemA bag holds 4 red and 6 blue counters. You draw two without putting the first back. What is the probability that both are red? That they are one of each colour?Both red 2/15 ≈ 0.133333; One of each 8/15 ≈ 0.533333
Red then blue: . Blue then red: . They are disjoint, so add:
Check: both blue is , and .
7. Conditional probability and Bayes' theorem · Tree diagrams lay out the chain · QuizFrom the tree, what is the probability that a part is fine and came from machine B?B. 0.38Follow the path: 0.4 for machine B, then 0.95 for fine given B, so . The 0.95 is the chance of fine given B, the branch label, not the whole path. A check: the four path ends, , add up to 1.
7. Conditional probability and Bayes' theorem · The law of total probability adds the paths · Code challengeFinish totalProbability(priors, likelihoods): priors[j] is and likelihoods[j] is . Return .One solution:
Solution
1#include<vector>23doubletotalProbability(const std::vector<double>& priors,4const std::vector<double>& likelihoods){5double total =0;6for(std::size_t j =0; j < priors.size(); j++){7 total += priors[j]* likelihoods[j];8}9return total;10}
It is the weighted mean from the module on centre: each conditional chance weighted by how likely its piece is. Averaging the likelihoods without weights, , would wrongly treat the machines as equally busy. The priors must add up to 1, since the pieces cover everything.
7. Conditional probability and Bayes' theorem · Bayes’ theorem turns the condition around · QuizA part is defective. What is the chance it came from machine A?C. 0.375Either directly, , or as the complement of B’s 0.625: a defective part came from exactly one machine. 0.02 is the chance the other way round, , and 0.012 is the path’s chance before you knew the part was defective.
7. Conditional probability and Bayes' theorem · Ignoring the base rate is the classic mistake · QuizAfter a first positive (posterior about 9.2%), you take a second, independent test with the same rates and it is also positive. Which number is your new prior?B. About 9.2%Yesterday’s posterior is today’s prior: you start from 9.2%, and the second positive lifts it to about 50%. Starting again from 1% would throw away the first test. This chaining is the heart of Bayesian thinking, the subject of a later module. (It assumes the two tests’ errors are independent; if both are fooled by the same thing, the second adds little.)
7. Conditional probability and Bayes' theorem · Ignoring the base rate is the classic mistake · Code challengeFinish posterior(prior, sensitivity, falsePositive): the probability of the condition after a positive test, by Bayes’ theorem.One solution:
The denominator is every positive: true positives from the sick plus false positives from the healthy, the law of total probability. The starter returns the sensitivity, which is exactly base rate neglect. Forgetting 1 - prior in the false positives, and using all people instead of the healthy ones, overcounts the false alarms slightly.
7. Conditional probability and Bayes' theorem · The prosecutor’s fallacy · QuizWhat is the prosecutor’s fallacy?B. Treating the chance of the evidence given innocence as the chance of innocence given the evidenceIt is base rate neglect in a courtroom: read as . The posterior depends on the prior, here how many other people could have been the source, and on the rest of the evidence. A defence lawyer can make the opposite error, saying the match is worthless because 10 others match: the match still narrows millions down to about 11, which is strong evidence combined with anything else.
7. Conditional probability and Bayes' theorem · The Monty Hall problem · QuizChange the rules: the host does not know where the car is, opens one of the other two doors at random, and it happens to show a goat. Now what is your chance of winning if you switch?B. 1/2Now a goat appearing is evidence. Of the 2/3 of games where the car is behind an unpicked door, a random host reveals it half the time, and those games are thrown out. What remains: “car behind your pick” (1/3) and “car behind the other closed door” (also 1/3), equally likely, so 1/2. The same door, the same goat, a different answer: probability depends on how the information was produced, not just what you saw.
7. Conditional probability and Bayes' theorem · Practice problems · ProblemA shop buys 50% of its bulbs from supplier A, 30% from B and 20% from C. Of their bulbs, 1%, 3% and 5% are faulty. What share of all the bulbs are faulty? A bulb is faulty: what is the probability that it came from C? From A? 0.024; 5/12 ≈ 0.416667; 5/24 ≈ 0.208333
C supplies only 20% of the bulbs but about 42% of the faulty ones; A supplies half of the bulbs but only about 21% of the faulty ones.
7. Conditional probability and Bayes' theorem · Practice problems · ProblemA condition affects 2% of people. A test for it is positive for 95% of those who have it, and for 5% of those who do not. Out of 10 000 people tested, how many true positives and how many false positives do you expect? What is ?True positives 190; False positives 490; 19/68 ≈ 0.279412
2% of 10 000 is 200 people with the condition, and 9800 without it.
True positives: 95% of 200 is 190. False positives: 5% of 9800 is 490.
Fewer than 3 in 10 positives have the condition: the healthy 98% produce most of the positives.
7. Conditional probability and Bayes' theorem · Practice problems · ProblemTake the same test (positive for 95% of people with the condition and 5% without), where 2% have the condition. Someone tests positive, so their chance is now , and then takes a second, independent test, also positive. What is their chance of having the condition now? And for someone who tests negative once, what is the chance they do not have it?After two positives 361/410 ≈ 0.880488; 931/932 ≈ 0.998927
Start from the prior , so do not have the condition. The $\frac{1}{68}$s cancel:
For one negative, in 10 000 people: 95% of the 9800 without the condition test negative, 9310, and so do 5% of the 200 with it, 10:
A second positive lifts the chance from about 28% to 88%. A negative is very reassuring, because the condition was rare to begin with.
7. Conditional probability and Bayes' theorem · Practice problems · ProblemThe chance of rain today is 0.3. If it rains today, the chance of rain tomorrow is 0.6; if it does not, the chance is 0.2. What is the probability that it rains on both days? That it rains tomorrow? If it rains tomorrow, what is the probability that it also rained today?Rain on both days 0.18; Rain tomorrow 0.32; 0.5625
Both days: .
Rain tomorrow follows a wet day or a dry one: .
Knowing tomorrow is wet raises the chance that today was wet from 0.3 to about 0.56: the two days are not independent.
8. Random variables and expected value · A probability mass function lists the chances · QuizA random variable takes the values 1, 2 and 3 with and . What is , and ?A. 0.3 and 0.8The chances must add up to 1, so . Then , or by the complement, . The values are disjoint events, so adding their chances is allowed.
8. Random variables and expected value · A probability mass function lists the chances · ProblemThe number of children in a household takes the values 0, 1, 2, 3 and 4 with probabilities 0.2, 0.3, 0.25, and 0.1. Find and . 0.15; 0.5
.
, or by the complement, .
8. Random variables and expected value · The expected value is the long-run average · QuizA café sells 0, 1 or 2 cakes an hour with probabilities 0.3, 0.5 and 0.2. How many cakes does it expect to sell in an 8-hour day?B. 7.2Per hour, cakes, and expected values add up over hours (a later slide), so . The answer 1 is the most likely value, the mode, not the expected value. A shop orders stock by the expected value plus a margin for the spread.
8. Random variables and expected value · The variance of a random variable · ProblemThe number of children in a household is 0, 1, 2, 3 or 4, with probabilities 0.2, 0.3, 0.25, 0.15 and 0.1. Find , and the standard deviation . 1.65; 1.5275; sqrt(1.5275) ≈ 1.23592
So a household has 1.65 children on average, give or take about 1.2.
8. Random variables and expected value · Try it: the mean and variance of a distribution · Code challengeFinish expectedValue(values, probs): probs[i] is the probability of values[i]. Return the sum of each value times its probability.One solution:
Solution
1#include<vector>23doubleexpectedValue(const std::vector<double>& values,4const std::vector<double>& probs){5double total =0;6for(std::size_t i =0; i < values.size(); i++){7 total += values[i]* probs[i];8}9return total;10}
It is a weighted mean whose weights already add up to 1, so there is no division. Dividing by values.size() as for a plain mean would only be right if every value were equally likely, and then the probabilities would be anyway. The tests write the probabilities as 1.0 / 8, not 1 / 8: between two ints that is 0.
8. Random variables and expected value · Try it: the mean and variance of a distribution · Find the bugThis variance gives about −2.92 for a fair die. Which line is wrong?Line 8: return meanOfSquares - mean * mean;The shortcut is , the mean of the squares minus the square of the mean. Written the other way round it is the right size with the wrong sign: . A negative variance is impossible, since it is an average of squares: a quick sanity check for any spread you compute.
8. Random variables and expected value · Try it: the mean and variance of a distribution · Code challengeFinish variance(values, probs): the variance of the distribution, using or the shortcut.One solution:
Solution
1#include<vector>23doublevariance(const std::vector<double>& values,4const std::vector<double>& probs){5double mean =0;6for(std::size_t i =0; i < values.size(); i++){7 mean += values[i]* probs[i];8}9double total =0;10for(std::size_t i =0; i < values.size(); i++){11double d = values[i]- mean;12 total += d * d * probs[i];13}14return total;15}
Find the mean first, then weight each squared distance by its probability. For heads in 3 tosses: . The two-pass version is also better numerically: the shortcut subtracts two big, nearly equal numbers when the mean is large, losing precision.
8. Random variables and expected value · Shifting and scaling a random variable · QuizA shop’s daily profit has mean 200 and variance 900 (in coins). Each day 50 coins of rent are paid, and the owner keeps half of what is left: . What are the mean and SD of ?A. 75 and 15. The SD of is ; subtracting 50 leaves it alone and halving halves it, so 15. The 225 is the new variance, . Working with SDs is easier: they scale like the data, while variances scale by the square.
8. Random variables and expected value · Expected values always add · QuizYou roll 10 dice. What is the expected number of sixes?B. 10/6 ≈ 1.67Let if die shows a six: . By linearity, the expected count is . No need for the distribution of the count (that is the binomial, next module). Indicator variables plus linearity solve problems that look hopeless any other way.
8. Random variables and expected value · Variances add for independent variables · QuizTwo independent machines fill bags: one with SD 3 g, the other with SD 4 g. What is the SD of the difference between a bag from each?B. 5 gVariances add, even for a difference: , so the SD is g. The tempting 1 g subtracts the SDs, as if the errors cancelled; they are independent, so they are just as likely to pile up. 7 g adds SDs, which is only right if the two always err together. 25 is the variance.
8. Random variables and expected value · Games and fair bets · QuizA game: roll a die, and you are paid as many coins as the number shown. What is the fair price to play?B. 3.5 coinsThe payout’s expected value is 3.5 coins, so paying 3.5 makes your net expected winnings 0: fair. At 3 coins you gain 0.5 per game on average; at 4 you lose 0.5. The fair price of any gamble is its expected payout, which is how insurers and lotteries start their pricing, before adding their own edge.
8. Random variables and expected value · Expected value is not the whole story · QuizA lottery ticket costs 2 coins and its expected payout is 0.9 coins. Which statement is right?B. Over very many tickets, buyers get back about 45% of what they spendThe expected value is a long-run average: per ticket, comes back, and the expected net is coins. Almost every single ticket pays 0; a rare few pay a lot. Buying more tickets multiplies the expected loss: linearity of expectation says 10 tickets expect to lose 11 coins.
8. Random variables and expected value · Practice problems · ProblemA random variable has mean 12 and standard deviation 3. Let . Find , the standard deviation of , and . 40; 15; 225
.
, and , which is .
8. Random variables and expected value · Practice problems · ProblemA gift box holds 4 jars of jam. Each jar’s mass has mean 150 g and SD 6 g, independently of the others, and the empty box weighs exactly 80 g. Find the mean and the SD of the full box’s mass. Then find the SD of the difference in mass between two single jars.Mean of the full box 680 g; SD of the full box 12 g; SD of the difference sqrt(72) ≈ 8.48528 g
Mean: g.
Variance: , and the box adds none. So the SD is g, not g.
For the difference of two jars, the variances add again: , so the SD is g.
8. Random variables and expected value · Practice problems · ProblemA game costs 4 coins. You roll a fair die: a 6 pays 12 coins, a 4 or a 5 pays 3 coins, and anything else pays nothing. Find the expected payout, your expected net winnings per game, and the fair price to play.Expected payout 3 coins; Expected net winnings -1 coins; Fair price 3 coins
You pay 4, so the expected net winnings are coin a game.
A fair price makes the expected net winnings 0, so it is the expected payout: 3 coins.
8. Random variables and expected value · Practice problems · ProblemA quiz has 12 questions, each with 4 options, and you guess every answer at random. What is the expected number of right answers? If each right answer scores and each wrong one , what is your expected score?Expected number right 3; Expected score 0
Each question is right with probability , so by linearity the expected number right is .
One question’s expected score:
So the expected total is : the penalty is set so that blind guessing gains nothing on average.
9. Binomial, geometric and Poisson · A Bernoulli trial: success or failure · QuizA website visitor buys something with probability 0.1. What is the SD of the Bernoulli variable “buys”?C. 0.3The variance is , and the SD is its square root, . 0.09 is the variance, not the SD. The SD of a 0-or-1 variable is large compared with its mean of 0.1, which is why measuring a small rate precisely takes many visitors.
9. Binomial, geometric and Poisson · The binomial counts successes in n trials · QuizWhich of these counts are binomial?A. The number of sixes in 12 rolls of a die; D. The number of 20 randomly chosen voters, from a country of millions, who support a policyTwelve rolls: binary (six or not), independent, fixed , same . The voters are drawn without replacement, but from millions, so each draw barely changes the chances: binomial is an excellent model. The rolls until a six has no fixed (that is the geometric, later). The cards are drawn without replacement from just 52, so the chance of an ace changes noticeably after each card: not binomial.
9. Binomial, geometric and Poisson · The binomial formula · QuizA fair coin is tossed 10 times. Which is ?B. “At most 2” is 0, 1 or 2 heads, disjoint events, so add their chances: . With , every sequence has probability , so only the counts of sequences differ. The first option is “exactly 2”. Adding up the pmf up to gives the cumulative distribution function, .
9. Binomial, geometric and Poisson · The binomial formula · ProblemEach seed sprouts with probability 0.8, independently of the others. You plant 6. What is the probability that exactly 5 sprout? That all 6 sprout? That at least 5 sprout?6*0.8^5*0.2 ≈ 0.393216; 0.8^6 ≈ 0.262144; 6*0.8^5*0.2 + 0.8^6 ≈ 0.65536
The two are disjoint, so .
9. Binomial, geometric and Poisson · Mean np, variance np(1 − p) · QuizA basketball player makes 80% of free throws, independently. In 10 throws, what are the mean and SD of the number made?B. 8 and about 1.26, and the variance is , so the SD is . 1.6 is the variance. Making 6 or fewer would be about 1.6 SDs below the mean: unusual but not shocking, which matters before calling a player “in a slump”.
9. Binomial, geometric and Poisson · Try it: the binomial pmf and cdf · Code challengeFinish binomialPmf(n, k, p): the chance of exactly k successes in n trials. A choose function is given.One solution:
Solution
1#include<cmath>23doublechoose(int n,int k){4if(k <0|| k > n)return0;5double r =1;6for(int i =1; i <= k; i++) r = r *(n - k + i)/ i;7return r;8}910doublebinomialPmf(int n,int k,double p){11returnchoose(n, k)* std::pow(p, k)* std::pow(1- p, n - k);12}
Three factors: the number of sequences, the chance of the successes, and the chance of the failures. Forgetting gives the chance of one particular sequence, such as SSFFF, which is 10 times too small here. std::pow(p, k) is : C++ has no power operator, and p ^ k is not one (it does not even compile on a double). The “adds up to 1” test is a good habit for any pmf you code.
9. Binomial, geometric and Poisson · Try it: the binomial pmf and cdf · Code challengeFinish binomialCdf(n, k, p): the chance of at mostk successes, . binomialPmf is given.One solution:
Solution
1#include<algorithm>2#include<cmath>34doublebinomialPmf(int n,int k,double p){5double c =1;6for(int i =1; i <= k; i++) c = c *(n - k + i)/ i;7return c * std::pow(p, k)* std::pow(1- p, n - k);8}910doublebinomialCdf(int n,int k,double p){11double total =0;12for(int j =0; j <= std::min(k, n); j++){13 total +=binomialPmf(n, j, p);14}15return total;16}
Add the pmf from 0 up to and including k: the loop’s <= matters, since < would leave out exactly . For “at least ”, use the complement, : an easy off-by-one to get wrong, so write down which values are in the event before coding it.
9. Binomial, geometric and Poisson · The geometric distribution: waiting for a success · QuizYou have rolled a die 10 times without a six. What is the expected number of further rolls until the first six?A. 6The rolls are independent, so the past does not matter: the wait starts again, with mean 6. The geometric is memoryless: . “Overdue” is the gambler’s fallacy again. Memorylessness is a strong assumption: a light bulb that has burned for years is more likely to fail soon, so its lifetime is not geometric.
9. Binomial, geometric and Poisson · The Poisson distribution counts rare events · QuizA help desk gets on average 3 calls a minute. What is the chance of a minute with no calls?B. About 0.05. About one minute in 20 is quiet. 0.22 is . The rate scales with the interval: in half a minute, ; in an hour, . Getting the interval and the rate to match is the first step of any Poisson problem.
9. Binomial, geometric and Poisson · The Poisson distribution counts rare events · ProblemA shop gets 4 complaints a week on average, at random and independently. What is the probability of exactly 2 complaints in a week? Of no complaints in half a week?2 in a week 8*exp(-4) ≈ 0.146525; None in half a week exp(-2) ≈ 0.135335
In half a week, :
9. Binomial, geometric and Poisson · The Poisson is the binomial for rare events · QuizA chip has a 1 in 1000 chance of a defect, independently. In a batch of 2000 chips, what is the Poisson approximation to the chance that none are defective?A. , and . The exact binomial, , agrees to three decimal places. is the chance of exactly one defect. With in the exact formula, the Poisson is also much easier to compute.
9. Binomial, geometric and Poisson · Try it: the Poisson pmf · Code challengeFinish poissonPmf(k, lambda): . Build the terms up in a loop, rather than computing and separately, so large k does not overflow.One solution:
Solution
1#include<cmath>23doublepoissonPmf(int k,double lambda){4double term = std::exp(-lambda);5for(int i =1; i <= k; i++) term *= lambda / i;6return term;7}
Each term is the previous one times : . Computing std::pow(180, 200) directly gives inf (too big for a double) and does too, so their ratio is inf / inf, which is nan, though the answer is an ordinary 0.0097. Watch out for one more trap: itself underflows to 0 for above about 745, and then statisticians work with logarithms of probabilities instead.
9. Binomial, geometric and Poisson · Which distribution fits · QuizA quality inspector tests bulbs from a production line, one after another, until she finds the first faulty one. Which distribution models the number of bulbs tested?B. GeometricThe number of trials is not fixed; it is what is being counted, up to and including the first “success” (a faulty bulb). That is geometric. Binomial needs a fixed number of bulbs, such as “how many of 50 are faulty”. Poisson counts events in a fixed interval of time or space, with no trials at all.
9. Binomial, geometric and Poisson · Practice problems · ProblemA test has 20 multiple-choice questions with 5 options each, and a student guesses every answer. Find the mean and the SD of the number of right answers, and the probability of getting none right.Mean 4; SD sqrt(3.2) ≈ 1.78885; 0.8^20 ≈ 0.0115292
The number right is , with mean .
Its variance is , so its SD is .
9. Binomial, geometric and Poisson · Practice problems · ProblemAt a fair, each throw lands a ring on the peg with probability 0.25, independently. What is the probability that the first success comes on the 3rd throw? That you need more than 4 throws? What is the expected number of throws up to and including the first success?9/64 ≈ 0.140625; 81/256 ≈ 0.316406; 4
throws.
9. Binomial, geometric and Poisson · Practice problems · ProblemEach letter a firm sends has a 1 in 500 chance of being lost, independently. It sends 1500 letters. Using the Poisson approximation, what is the probability that none are lost? That at most one is lost?None lost exp(-3) ≈ 0.0497871; At most one lost 4*exp(-3) ≈ 0.199148
.
. The exact binomial gives 0.0496 and 0.199: very close.
9. Binomial, geometric and Poisson · Practice problems · ProblemA machine makes 10% defective items, independently. In a sample of 10 items, what is the probability of no defective items? Of exactly one? Of at least two?0.9^10 ≈ 0.348678; 0.9^9 ≈ 0.38742; 1 - 0.9^10 - 0.9^9 ≈ 0.263901
The complement of “at least two” is “0 or 1”:
10. Continuous distributions and the normal curve · For continuous variables, probability is area · QuizA density curve has height 1.5 at . What does that mean?B. Values near 2 are relatively likely: the chance of a small interval around 2 is about 1.5 times its widthA density is not a probability: it is probability per unit of , so it can exceed 1 as long as the total area is 1. The chance of landing in is about . And is exactly 0 for any continuous variable, which is also why and give the same probabilities.
10. Continuous distributions and the normal curve · The uniform distribution: flat · QuizFor the bus wait, uniform on minutes, what are the mean and the SD?A. 5 and about 2.89The mean is the midpoint, . The variance is , so the SD is minutes. 8.33 is the variance. std::uniform_real_distribution<double>(0.0, 1.0) gives numbers uniform on , with mean 0.5 and SD , which is the raw material for simulating every other distribution.
10. Continuous distributions and the normal curve · The uniform distribution: flat · ProblemA train comes every 15 minutes and you arrive at a random moment, so your wait is uniform on minutes. What is the probability that you wait more than 10 minutes? What are the mean and the SD of the wait?1/3 ≈ 0.333333; Mean 7.5 min; SD 15/sqrt(12) ≈ 4.33013 min
The density is on . The area from 10 to 15 is a rectangle: .
The mean is the midpoint, minutes.
10. Continuous distributions and the normal curve · The exponential distribution: waiting for the next event · QuizCustomers arrive at a rate of 2 per minute (a Poisson process). What is the chance the gap between two customers is more than 1 minute?A. . Equivalently, the gap is longer than a minute exactly when a minute passes with no arrivals, a Poisson count of 0 with mean 2: again. is the chance the gap is shorter. The two views, counts per interval and gaps between events, describe the same random process.
10. Continuous distributions and the normal curve · The standard normal and its table · QuizThe table only lists positive . How do you find ?B. The curve is symmetric about 0, so the area left of equals the area right of , which is . A probability is never negative. 0.3413 is the area between 0 and 1. Sketching the curve and shading the area you want is the surest way through any normal calculation.
10. Continuous distributions and the normal curve · Normal calculations: standardise, then look up · QuizExam marks are normal with mean 60 and SD 12. A grade A goes to marks above 84. About what share of students get an A?A. 2.3%, and , about 2.3%. 97.7% is the share below 84: always check which side of the cut-off the question wants. The empirical rule gives the same estimate: 95% within 2 SDs, so 2.5% above.
10. Continuous distributions and the normal curve · Normal calculations: standardise, then look up · ProblemBottles are filled with a volume that is normal with mean 500 ml and SD 4 ml. Using the table of , what share of bottles (as a decimal) hold less than 508 ml? Between 498 and 504 ml? Above what volume are the fullest 5% of bottles?Below 508 ml 0.9772; 498 to 504 ml 0.5328; The fullest 5% are above 506.58 ml
508 ml is , so .
498 ml is and 504 ml is :
The fullest 5% are above the 95th percentile, and :
10. Continuous distributions and the normal curve · Try it: normal probabilities in code · Code challengeFinish normalBetween(a, b, mu, sigma): the probability that a normal variable with mean mu and SD sigma lands between a and b. phi(z), the standard normal cdf, is given.One solution:
Solution
1#include<cmath>23// The standard normal cdf, from <cmath>'s error function.4doublephi(double z){5return0.5*(1+ std::erf(z / std::sqrt(2.0)));6}78doublenormalBetween(double a,double b,double mu,double sigma){9returnphi((b - mu)/ sigma)-phi((a - mu)/ sigma);10}
Standardise both ends with the same mu and sigma, then subtract the two areas: everything left of b minus everything left of a. The starter forgets to standardise, which happens to work for the standard normal, so the first test passes and the others do not. -INFINITY (from <cmath>) works because phi of it is 0, a nice way to write “below 180”. phi is one line because <cmath> has the error function, std::erf, and .
10. Continuous distributions and the normal curve · Try it: normal probabilities in code · Code challengeFinish area(f, a, b, n): approximate the area under f from a to b with the trapezoid rule: split the interval into n equal strips of width h, and add up h * (f(left) + f(right)) / 2 for each strip.One solution:
Solution
1#include<functional>23doublearea(const std::function<double(double)>& f,4double a,double b,int n){5double h =(b - a)/ n;6double total =0;7for(int i =0; i < n; i++){8double left = a + i * h;9 total += h *(f(left)+f(left + h))/2;10}11return total;12}
Each strip is a trapezoid: its width h times the mean of its two side heights. With 1000 strips the error is tiny, about times the curve’s bendiness. This is how you check a cdf formula, or compute a probability for a density nobody has tabulated. Computing left from a + i * h each time, rather than adding h repeatedly, avoids piling up rounding errors. f is a std::function<double(double)>, any function from a double to a double: the tests pass a named function, normalPdf, and lambdas such as [](double x) { return 0.5 * std::exp(-0.5 * x); }.
10. Continuous distributions and the normal curve · The normal approximation to the binomial · QuizWith the continuity correction, which normal probability approximates for ?B. The event includes 60, whose interval is , so the area starts at 59.5. Starting at 60.5 would leave out itself. Ask “which whole numbers are in the event?”, then widen by half a unit at each end. Here .
10. Continuous distributions and the normal curve · Checking normality with a QQ plot · QuizIn a QQ plot, the points follow the line in the middle, but at the right end they rise far above it, and at the left end they sit above it too, bunched up. What does that suggest?B. The data is skewed right: a long upper tail and a short lower oneThe largest values are much bigger than a normal sample would give, a long right tail, and the smallest are not as small as normal ones would be, a short left tail: right skew, like the exponential above. A plot that bends below the line on the left and above it on the right (an S-shape) signals heavy tails in both directions instead. In practice, small wiggles are normal; look for clear bends.
10. Continuous distributions and the normal curve · Practice problems · ProblemCalls reach a help line at random, at a rate of 4 an hour. What is the probability of waiting more than 30 minutes for the next call? What is the mean wait, in minutes? What is the probability that the next call comes within 15 minutes?Wait over 30 minutes exp(-2) ≈ 0.135335; Mean wait 15 min; Within 15 minutes 1 - exp(-1) ≈ 0.632121
The mean wait is of an hour: 15 minutes.
More than half of the waits are shorter than the mean: the exponential is skewed right, with a long tail of long waits.
10. Continuous distributions and the normal curve · Practice problems · ProblemTest scores are normal with mean 100 and SD 15. Above what score are the top 2.5%? What share of people (as a decimal) score above 130? Between 85 and 115?The top 2.5% score above 129.4; Above 130 0.0228; 85 to 115 0.6826
The top 2.5% lie above the with , which is 1.96: .
130 is , so .
85 and 115 are and : , the 68% of the empirical rule.
10. Continuous distributions and the normal curve · Practice problems · ProblemA fair coin is tossed 100 times. Using the normal approximation with the continuity correction, find the probability of at most 52 heads, and of between 48 and 52 heads (both included). 0.6915; 0.383
and .
From 48 to 52 heads, both included, the area runs from 47.5 to 52.5, which is to :
The exact binomial answers are 0.6914 and 0.3827: very close.
10. Continuous distributions and the normal curve · Practice problems · ProblemA random variable has the density for , and 0 elsewhere: a triangle. Find , , and the median , the value with .1/4 ≈ 0.25; 0.4375; sqrt(2) ≈ 1.41421
The whole triangle has base 2 and height , so its area is , as a density’s must be.
The area from 0 to is a smaller triangle, with base and height : .
, and .
For the median, , so and : above the middle of the range, 1, because more of the area is on the right.
11. Sampling and the central limit theorem · You study a sample to learn about a population · QuizA school has 2000 pupils. You pick 50 of them and find their mean exam score is 68. Which is the parameter?B. The mean score of all 2000 pupilsA parameter belongs to the population: the mean of all 2000 pupils, which you don’t know. The 68 is a statistic, , computed from the sample; a different 50 pupils would give a different number. Mixing up the two is the root of most confusion in this module.
11. Sampling and the central limit theorem · Random sampling gives every member a fair chance · QuizA city picks 12 of its 300 bus routes at random and surveys every passenger on those 12 routes one morning. What design is this?C. Cluster sampleThe routes are clusters: ready-made groups, chosen at random, with everyone inside measured. A stratified sample would instead take some passengers from every route. Clusters are cheap, but passengers on the same route are alike, so 12 routes tell you less than the same number of passengers spread over all 300.
11. Sampling and the central limit theorem · A biased method misses the same way every time · QuizA magazine asks readers to mail in their opinion and gets 50 000 replies. A pollster asks 1000 people chosen at random. Which estimate of national opinion should you trust more?B. The pollster: a random sample avoids the bias of self-selectionReaders who choose to reply differ from everyone else, and 50 000 of them only pins down their opinion precisely. In 1936 the Literary Digest mailed 10 million ballots, got 2.4 million back, and predicted the wrong US president; George Gallup’s far smaller but more carefully chosen sample got it right. Randomness beats size when the method is biased.
11. Sampling and the central limit theorem · A statistic has a distribution of its own · QuizWhat is the mean of this sampling distribution, the average of all 36 possible two-roll means?B. 3.5The distribution is symmetric about 3.5, so its mean is 3.5, the population mean. This is true in general: the mean of the sampling distribution of is . That is what it means to say is an unbiased estimator. One sample can miss; on average it doesn’t.
11. Sampling and the central limit theorem · The standard error measures how much a statistic wobbles · Fill the blanksComplete the standard error of a mean, given the population standard deviation sigma and sample size n.1: sqrt, 2: nThe SE divides by the square root of , not by . That is why precision is expensive: to halve the SE you need four times the data, and to cut it to a tenth you need a hundred times.
11. Sampling and the central limit theorem · The standard error measures how much a statistic wobbles · ProblemResting heart rates of adults have a standard deviation of beats per minute. What is the standard error of the mean of a random sample of 16 adults? How many adults would you need for a standard error of 1.5 beats per minute?SE with 3 beats per minute; Sample size for an SE of 1.5 64 adults
Divide the spread of single values by the square root of the sample size:
For a standard error of 1.5, solve for :
Halving the standard error, from 3 to 1.5, takes four times the data: 64 adults instead of 16.
11. Sampling and the central limit theorem · The law of large numbers: averages settle down · QuizA fair coin has come up heads 8 times in a row. By the law of large numbers, what is the chance the next flip is tails?B. Exactly 1/2The coin has no memory: each flip is still 1/2. The law of large numbers does not work by correcting past results; it works by swamping them. Eight extra heads matter a lot after 10 flips and almost nothing after 10 000. Believing tails is “due” is the gambler’s fallacy.
11. Sampling and the central limit theorem · The law of large numbers: averages settle down · Code challengeWrite runningMeans(xs), which returns the mean of the first 1, 2, 3, … values of xs, so you can watch an average settle down. For {4, 2, 6, 0} it returns {4, 3, 4, 3}.One solution:
Solution
1#include<vector>23std::vector<double>runningMeans(const std::vector<double>& xs){4 std::vector<double> means;5double total =0;6for(int i =0; i < xs.size(); i++){7 total += xs[i];8 means.push_back(total /(i +1));9}10return means;11}
A running total makes this one pass: after adding the -th value, divide by (that is i + 1, since vectors count from 0). Recomputing each mean from scratch also works but does additions. The usual slip is dividing by i, which is off by one and divides by zero on the first value (4.0 / 0 is inf).
11. Sampling and the central limit theorem · The central limit theorem: means become normal · QuizYou take one sample of 100 waits from this skewed population. What does the CLT say is roughly normal?C. The distribution of over many possible samples of 100The CLT is about the sampling distribution of the mean, not about the data. Your 100 waits still look skewed, like the population they came from. It is their average that would vary in a bell shape if you repeated the sampling. Expecting the data themselves to turn normal is the classic misreading.
11. Sampling and the central limit theorem · The central limit theorem: means become normal · ProblemCoffee-shop waits are skewed, with mean minutes and minutes. You time a random sample of 64 customers. What is the standard error of their mean wait, and roughly what is the probability that the mean wait is more than 2.5 minutes? Use .SE 0.25 min; 0.0228
The standard error of the mean:
By the central limit theorem, is approximately , even though single waits are skewed. Standardise 2.5:
A single wait over 2.5 minutes is common (with the skewed waits of the graph, about 29% of customers wait that long), but a mean of 64 waits above 2.5 happens only about 2% of the time.
11. Sampling and the central limit theorem · Simulating a sampling distribution · Put in orderPut the steps of simulating the sampling distribution of a mean in order.1. Choose a population to draw from and a sample size 2. Draw a random sample of values 3. Work out the sample mean and keep it 4. Repeat the draw-and-average many thousands of times 5. Summarise the kept means: their average, SD and shapeEach repetition makes one sample mean; the sampling distribution only appears once you have thousands of them. A common mistake is to draw one huge sample and look at its histogram: that shows the population’s shape, not how the mean varies.
11. Sampling and the central limit theorem · Simulating a sampling distribution · Code challengeIn practice you don’t know , so you estimate the SE from the sample: , where is the sample standard deviation (dividing by ). Write standardError(xs).One solution:
Solution
1#include<cmath>2#include<vector>34doublestandardError(const std::vector<double>& xs){5int n = xs.size();6double mean =0;7for(double x : xs) mean += x;8 mean /= n;9double ss =0;10for(double x : xs) ss +=(x - mean)*(x - mean);11double s = std::sqrt(ss /(n -1));12return s / std::sqrt(n);13}
Two steps: the sample SD with (for {10, 12}, ), then divide by (here ), giving 1. Dividing by in gives 0.7071 for the second test’s data instead of 0.7559, a small bias that matters for small samples. Dividing by instead of is the other common slip.
11. Sampling and the central limit theorem · When the normal approximation can be trusted · QuizWhich sample is the CLT least likely to describe well, for the sampling distribution of the mean?C. 15 random households’ incomes, a strongly right-skewed populationSmall and strong skew is the bad combination: a few very rich households can drag a mean of 15 around, so the sampling distribution is still skewed. Heights are symmetric, so even 12 is fine, and 200 waits is plenty despite the skew.
11. Sampling and the central limit theorem · Practice problems · ProblemRoll a fair die twice and take the mean of the two rolls. Using the 36 equally likely pairs, what is the probability that the mean is at least 4.5? What is the probability that it is exactly 3.5?5/18 ≈ 0.277778; 1/6 ≈ 0.166667
The mean is the total divided by 2, so means a total of at least 9. Count the pairs:
That is pairs of 36, so .
A mean of exactly 3.5 is a total of 7: (1,6), (2,5), (3,4), (4,3), (5,2) and (6,1), 6 pairs. So , the tallest bar of the sampling distribution.
11. Sampling and the central limit theorem · Practice problems · ProblemFive tomato plants measure 4, 7, 7, 9 and 13 cm. Find the sample mean, the sample standard deviation (dividing by ) and the estimated standard error of the mean, . 8 cm; sqrt(11) ≈ 3.31662 cm; SE sqrt(11/5) ≈ 1.48324 cm
The mean: cm.
The deviations from 8 are . Square and add them:
The estimated standard error:
Single plants vary by about 3.3 cm; the mean of five plants would typically miss by about 1.5 cm.
11. Sampling and the central limit theorem · Practice problems · ProblemOne roll of a fair die has mean and variance . You roll it 105 times and take the mean. What is the standard error of that mean? Between which two values do about 95% of such means fall, using ?SE 1/6 ≈ 0.166667; Lower end 19/6 ≈ 3.16667; Upper end 23/6 ≈ 3.83333
The variance of the mean of 105 rolls is :
The band is :
A single roll can be anything from 1 to 6, but about 95% of the time the mean of 105 rolls lands within a third of a point of 3.5.
11. Sampling and the central limit theorem · Practice problems · ProblemA lift’s sign says 12 people or 960 kg. Adult weights have mean 75 kg and standard deviation 12 kg. Twelve adults chosen at random get in. Find the standard error of their mean weight, the -score of the mean weight that makes the total exactly 960 kg, and the probability that the total is over 960 kg. Treat the mean as normal and use .SE of the mean sqrt(12) ≈ 3.4641 kg; 5/sqrt(12) ≈ 1.44338; P(total > 960 kg) 0.0749
A total of 960 kg for 12 people is a mean of kg, so this is a question about :
Standardise a mean of 80 kg:
About 7.5% of random groups of 12 adults would be over the limit, which is why lifts are built with a safety margin. With only 12 people, the normal shape relies on adult weights being roughly bell-shaped to begin with.
12. Estimating: confidence intervals · A point estimate is one best guess · QuizWhich estimator of the population variance is unbiased, for a simple random sample of size ?B. The sum of squared deviations from , divided by Values sit a little closer to their own mean than to the true , so squared deviations from run small. Dividing by instead of exactly makes up for it on average. (The square root, , is still slightly biased for , but much less so, and nobody minds.)
12. Estimating: confidence intervals · An interval is the estimate plus or minus a margin · ProblemA machine fills bags of flour, and from long experience the fill weights have g. A random sample of 16 bags has mean g. Find the standard error, the margin of error and the 95% confidence interval for the mean fill , with .SE 2 g; Margin of error 3.92 g; Lower end 999.08 g; Upper end 1006.92 g
The label’s 1000 g is inside the interval, so it is one of the plausible values for : these 16 bags give no clear sign that the machine’s mean is off.
12. Estimating: confidence intervals · More confidence costs a wider interval · QuizFrom the same sample of plants, a 95% interval is (40.04, 43.96) cm. What would the 99% interval be?C. (39.42, 44.58)Same centre and SE, but : . Being surer you’ve caught needs a wider net. (40.36, 43.64) is the 90% interval, with 1.645.
12. Estimating: confidence intervals · Ninety-five per cent is about the method, not this interval · QuizA 95% confidence interval for the mean wait at a coffee shop is (3.35, 5.05) minutes. Which statements are correct?C. If we sampled again and again, about 95% of intervals made this way would contain ; D. It is a range of plausible values for the mean wait, from a method that catches the true mean 95% of the timeBoth right answers describe the method. The first is the most common mistake: in this (frequentist) view is fixed, so it is either in this interval or not; the 95% belongs to the procedure. The Bayesian module later gives intervals that do carry that probability. The second confuses the mean with single customers, whose waits vary far more widely.
12. Estimating: confidence intervals · When sigma is unknown, use the t distribution · QuizWhy is bigger than 1.96 for a 95% interval from a small sample?B. Using instead of adds uncertainty, so you go out further to keep 95% coverageWith few values, can come out well below by chance, and then a -interval would be too narrow and miss more than 5% of the time. The t distribution’s heavier tails build that risk in. With df = 4 the 95% is 2.776, so the interval is about 40% wider than a -interval.
12. Estimating: confidence intervals · The t interval for a mean · Find the bugThis margin of error comes out far too small. Which line is wrong?Line 9: return tStar * s / std::sqrt(n);The standard error is , not . Dividing by makes the margin times too small (4 times for 16 values), so the interval would miss far more often than 5% of the time. The on line 8 is right: it is the sample standard deviation.
12. Estimating: confidence intervals · The t interval for a mean · Code challengeWrite tInterval(xs, tStar), which returns the confidence interval for the mean as a pair {low, high}: , with dividing by . The caller looks up tStar.One solution:
Solution
1#include<cmath>2#include<utility>3#include<vector>45std::pair<double,double>tInterval(const std::vector<double>& xs,6double tStar){7int n = xs.size();8double mean =0;9for(double x : xs) mean += x;10 mean /= n;11double ss =0;12for(double x : xs) ss +=(x - mean)*(x - mean);13double se = std::sqrt(ss /(n -1))/ std::sqrt(n);14return{mean - tStar * se, mean + tStar * se};15}
For eight values: , , SE , and . The two-value test shows why tiny samples are nearly useless: with df = 1, and the interval runs from below 0 to nearly 24. Using 1.96 there would claim far more precision than two values can give. auto [low, high] = … unpacks the pair into two named values.
12. Estimating: confidence intervals · The t interval for a mean · ProblemNine phone batteries last a mean of hours, with standard deviation hours. How many degrees of freedom does the t interval use? Find the 95% confidence interval for the mean battery life, using .Degrees of freedom 8; Lower end 38.894 hours; Upper end 43.506 hours
With there are degrees of freedom, so : bigger than 1.96, because is only an estimate of .
About 38.9 to 43.5 hours. Using 1.96 instead would give a narrower interval, 39.2 to 43.2, which would miss the true mean more than 5% of the time.
12. Estimating: confidence intervals · An interval for a proportion · Code challengeWrite proportionInterval(successes, n, zStar), returning the pair {low, high} for .One solution:
Solution
1#include<cmath>2#include<utility>34std::pair<double,double>proportionInterval(int successes,int n,5double zStar){6double p =double(successes)/ n;7double se = std::sqrt(p *(1- p)/ n);8return{p - zStar * se, p + zStar * se};9}
For 50 of 100: , SE , margin . A frequent slip is forgetting to divide by inside the square root, or taking the root of the numerator only. In C++ there is one more: successes / n divides two ints, so 50 / 100 is 0, and the interval is ; double(successes) / n gives 0.5. Note the SE is largest at and shrinks towards 0 and 1.
12. Estimating: confidence intervals · What makes the margin of error shrink · QuizA survey of 400 people has a margin of error of 4.9 percentage points. What would it be with 1600 people?B. 2.45 pointsFour times the sample is times the precision, so the margin halves: . Expecting a quarter (1.2 points) is the usual mistake: the margin shrinks with , not .
12. Estimating: confidence intervals · Choosing the sample size before you collect · Code challengeWrite sampleSize(sigma, margin, zStar): the smallest whole with , that is rounded up.One solution:
Solution
1#include<cmath>23intsampleSize(double sigma,double margin,double zStar){4double root = zStar * sigma / margin; // that is √n5return std::ceil(root * root);6}
, and 138 people would give a margin just over 2, so it must be 139: std::ceil, never std::round. Note how halving the margin quadruples : precision is bought with the square of effort.
12. Estimating: confidence intervals · How confidence intervals are misread · QuizTwenty independent research teams each compute a correct 95% confidence interval for the same . How many intervals do you expect to miss ?B. About 1Each misses with probability 0.05, so you expect miss, and no team can tell whether theirs is the one. This is why a single surprising result deserves caution, and it leads straight to the problem of many tests in the next modules.
12. Estimating: confidence intervals · Practice problems · ProblemIn a random sample of 400 shoppers, 240 say they prefer paying by card. Find the sample proportion, its standard error, and the 95% confidence interval for the proportion of all shoppers who prefer card (). 0.6; SE sqrt(0.6*0.4/400) ≈ 0.0244949; Lower end 0.552; Upper end 0.648
. There are 240 successes and 160 failures, both well over 10, so the normal approximation is fine.
Between about 55% and 65% of all shoppers prefer card. A majority looks likely: the whole interval is above 0.5.
12. Estimating: confidence intervals · Practice problems · ProblemYou want to estimate the mean commuting time in a city to within minutes. A pilot survey suggests minutes. How many commuters do you need for 95% confidence ()? And for 99% ()?For 95% 217 commuters; For 99% 374 commuters
Both round up: 216 commuters would give a margin slightly over 2 minutes. Going from 95% to 99% confidence costs about 70% more people, since .
12. Estimating: confidence intervals · Practice problems · ProblemA pollster wants a margin of error of 2 percentage points () at 95% confidence (). How many people must she ask if she plans with ? A past poll suggests is near 0.2: how many would she need then?Planning with 2401 people; Planning with 1537 people
With , :
With , :
Planning with 0.5 is the safe choice: if the guess of 0.2 were wrong and were near 0.5, 1537 people would give a margin of about 2.5 points instead of 2.
12. Estimating: confidence intervals · More practice problems · ProblemA report gives a 95% confidence interval for a mean of 12.4 to 15.6 kg, made with . What are the sample mean and the standard error? What is the 90% interval from the same data ()? 14 kg; SE 1.6/1.96 ≈ 0.816327 kg; 90% lower end 14 - 1.645*1.6/1.96 ≈ 12.6571 kg; 90% upper end 14 + 1.645*1.6/1.96 ≈ 15.3429 kg
The centre is the estimate, and half the width is the margin:
Same estimate and standard error, smaller critical value:
The 90% interval is narrower because it claims less: its method misses about 1 time in 10 instead of 1 in 20.
12. Estimating: confidence intervals · More practice problems · ProblemFifty independent studies each make a correct 90% confidence interval for their own parameter. How many of the intervals do you expect to miss their parameter? What is the probability that all fifty contain it?Expected misses 5; P(all fifty contain it) 0.9^50 ≈ 0.00515378
Each interval misses with probability , so the number of misses is binomial with and :
The intervals are independent, so multiply:
With fifty 90% intervals it is almost certain that some miss, about 5 of them, and nobody can tell which.
13. Hypothesis tests and p-values · A test asks whether chance alone could explain the data · Put in orderPut the steps of a hypothesis test in order.1. State the null and alternative hypotheses 2. Choose a significance level, such as 0.05 3. Collect the data 4. Compute a test statistic from the data 5. Find the p-value: how likely a result this extreme is if the null is true 6. Compare the p-value with the significance level and decideThe hypotheses and the significance level come before you look at the data. Choosing them afterwards, once you know what the data say, lets you tilt the test towards the answer you want, which is one of the misuses at the end of this module.
13. Hypothesis tests and p-values · The null hypothesis is the boring explanation · QuizA website changes its sign-up button. Its old sign-up rate was 10%. You want to know whether the new button changes the rate. Which is the null hypothesis?A. The null is "no change": the true rate is still 0.10. is the alternative. is the sample proportion, which you can just look at: hypotheses are about the unknown population value, not about the data.
13. Hypothesis tests and p-values · A test statistic measures distance in standard errors · Fill the blanksComplete the z statistic for a sample mean xBar against the null value mu0.1: sigma, 2: n, 3: mu0, 4: seThe standard error is , not itself: averages of many values wobble much less than single values. Dividing by instead is the usual slip, and it makes every difference look small.
13. Hypothesis tests and p-values · A test statistic measures distance in standard errors · ProblemA machine should fill bottles with a mean of 500 ml, and its fills have ml. A random sample of 25 bottles has mean ml. Testing , find the standard error and the statistic.SE 0.8 ml; -2
The sample mean is 2 standard errors below the claimed 500 ml. The sign says which way; how surprising that is, is the p-value’s job.
13. Hypothesis tests and p-values · The p-value is how surprising the data would be under the null · QuizThe coffee shop test gives . Which sentence is right?B. If the true mean were 4 minutes, a sample mean of 4.6 or more would happen in about 0.82% of samples.A p-value is computed assuming is true, so it cannot be the probability that is true. It is a statement about the data given the hypothesis, not the hypothesis given the data. Reading it backwards (options one and three) is the most common mistake in all of statistics. Probabilities of hypotheses need Bayesian methods, later in the course.
13. Hypothesis tests and p-values · The significance level is the line you draw in advance · QuizA test at gives . What do you conclude?B. Fail to reject : the data are not strong enough evidence against it0.08 is above 0.05, so the evidence does not reach the bar you set. That is all it says: the null survives, it is not proven. A bigger sample might well find the effect.
13. Hypothesis tests and p-values · One-sided and two-sided tests · Code challengeWrite zTest(xBar, mu0, sigma, n), returning a ZResult with the z statistic and the two-sided p-value. normalCdf(z) is written for you: it gives .One solution:
Solution
1#include<cmath>23doublenormalCdf(double z){4return0.5*(1+ std::erf(z / std::sqrt(2.0)));5}67structZResult{8double z;9double p;10};1112ZResultzTest(double xBar,double mu0,double sigma,int n){13double z =(xBar - mu0)/(sigma / std::sqrt(n));14double p =2*(1-normalCdf(std::abs(z)));15return{z, p};16}
The two-sided p-value is both tails: . The std::abs matters: without it, a negative gives , which is not even a probability. A quick sanity check for any p-value code: it must land between 0 and 1, and equal 1 when the data match the null exactly.
13. Hypothesis tests and p-values · When sigma is unknown, the t-test takes its place · Code challengeWrite tStatistic(xs, mu0): the one-sample t statistic of the data xs against mu0. Use the sample standard deviation, dividing by .One solution:
Solution
1#include<cmath>2#include<vector>34doubletStatistic(const std::vector<double>& xs,double mu0){5int n = xs.size();6double mean =0;7for(double x : xs) mean += x;8 mean /= n;9double squares =0;10for(double x : xs) squares +=(x - mean)*(x - mean);11double s = std::sqrt(squares /(n -1));12return(mean - mu0)/(s / std::sqrt(n));13}
The mean of the eight waits is 4.7 and , so . Dividing the squares by instead of makes a little too small and a little too big: with 8 values, about 7% too big. With 7 degrees of freedom, gives a two-sided .
13. Hypothesis tests and p-values · When sigma is unknown, the t-test takes its place · ProblemA battery maker claims a mean life of 1200 hours. You test 36 batteries: hours and hours. Find the standard error, the t statistic and its degrees of freedom. (The two-sided critical value at for those degrees of freedom is 2.030.)SE 15 hours; −2.8; Degrees of freedom 35
is beyond the critical value 2.030, so at you reject the claim of a 1200-hour mean: the batteries seem to last less. (The two-sided p-value is about 0.008.)
13. Hypothesis tests and p-values · Two ways to be wrong · QuizA smoke alarm’s null hypothesis is "there is no fire". It stays silent while the kitchen burns. Which error is that?B. Type II errorThe null ("no fire") was false and the alarm failed to reject it: a missed effect, Type II. Going off over burnt toast would be a Type I error, a false alarm. Making an alarm more sensitive cuts Type II errors and adds Type I ones: for a fixed amount of data, lowering one raises the other.
13. Hypothesis tests and p-values · Power is the chance of finding an effect that is there · QuizWhich of these raise the power of a test? Pick all that do.A. A larger sample; B. A larger true effect; D. Less noisy measurements (smaller )More data, a bigger effect and less noise all push the alternative’s curve further from the null’s. A smaller moves the critical line right, so fewer real effects pass it: fewer false alarms, but less power. Studies are planned to have about 80% power; needs for that here.
13. Hypothesis tests and p-values · Tests and confidence intervals tell the same story · QuizA 95% confidence interval for a website’s mean session length is 3.2 to 5.8 minutes. A two-sided test of at …B. fails to reject 5 is inside the interval, so it is one of the values the data find plausible at the 95% level, and the matching test fails to reject. Being off-centre does not matter: every value inside the interval survives the test.
13. Hypothesis tests and p-values · Run enough tests and something will be significant · QuizA team tests whether 20 colours of sweets cause headaches. Only green gives , and the headline is "Green sweets cause headaches". What is the best response?B. With 20 tests, one significant result is about what chance alone would give: test green again on new dataWith 20 true nulls you expect one p-value below 0.05 on average. The honest moves are to correct for the number of tests (next module) or to treat green as a lead and replicate. Results found by searching are hypotheses, not conclusions.
13. Hypothesis tests and p-values · Practice problems · ProblemA test of gives . Find the p-value against , and against . Use .One-sided 0.0047; Two-sided 0.0094
Against , only small values count as extreme:
Against , both tails count:
Both are below 0.01. Each is the chance of a result this extreme if , not the chance that .
13. Hypothesis tests and p-values · Practice problems · ProblemFor the coffee shop, minutes, minutes and , and the two-sided test of gave . Find the 99% confidence interval for (). Does a two-sided test at reject ?Lower end 3.956 min; Upper end 5.244 min
4 is inside the 99% interval, so the test at does not reject. That matches the p-value: 0.0164 is below 0.05 but above 0.01. The same data can be significant at one level and not at a stricter one, which is why the level is fixed in advance.
13. Hypothesis tests and p-values · Practice problems · ProblemA one-sided z-test at rejects when . The true effect is standard deviations and . Where is the statistic centred when the effect is real, and what is the power? What is the power with ? Use and .Centre 2.4; Power with 0.775; Power with 0.94
With the centre moves to :
With 36 people a real effect of this size is missed about 22% of the time; 64 people bring that down to 6%.
13. Hypothesis tests and p-values · More practice problems · ProblemA lab runs 8 independent tests at , and in fact every null hypothesis is true. What is the probability of at least one significant result? How many false alarms does it expect? What significance level for each test would make the chance of any false alarm exactly 0.05?P(at least one) 1 - 0.95^8 ≈ 0.33658; Expected false alarms 0.4; Level for each test 1 - 0.95^(1/8) ≈ 0.00639115
Each test is a false alarm with probability 0.05, so the expected number is .
For an overall rate of exactly 0.05, each test needs a level with:
That is very close to , the simpler Bonferroni correction of the next module.
13. Hypothesis tests and p-values · More practice problems · ProblemA screening programme runs 250 tests at . In 200 of them the null hypothesis is true; in the other 50 there is a real effect, and each of those tests has power 0.9. How many Type I errors and how many Type II errors do you expect? What share of the significant results are real effects?Type I errors 10; Type II errors 5; Share of significant results that are real 45/55 ≈ 0.818182
Type I errors come from the 200 true nulls: expected.
Type II errors come from the 50 real effects: each is missed with probability , so .
The significant results are the 10 false alarms plus the real effects found:
About 18% of the “discoveries” are false alarms, far more than the 5% that might suggest. The final module returns to this.
14. Comparing groups: t-tests, chi-squared and ANOVA · A difference in means is only convincing next to the spread · QuizWhich result is the strongest evidence that the fertiliser works?C. A gap of 3 cm, standard deviations of 2 cm, 50 plants per groupEvidence depends on the gap compared with its standard error, and the standard error shrinks with less spread and with more data. The third has both. The gap alone says nothing: a 3 cm gap among plants that vary by 10 cm, with 5 of each, could easily be luck.
14. Comparing groups: t-tests, chi-squared and ANOVA · The two-sample t-test · Code challengeWrite welchT(a, b): Welch’s t statistic for the mean of a minus the mean of b. Use sample variances (divide by ).One solution:
Solution
1#include<cmath>2#include<vector>34doublemean(const std::vector<double>& xs){5double sum =0;6for(double x : xs) sum += x;7return sum / xs.size();8}910doublevariance(const std::vector<double>& xs){11double m =mean(xs), squares =0;12for(double x : xs) squares +=(x - m)*(x - m);13return squares /(xs.size()-1);14}1516doublewelchT(const std::vector<double>& a,17const std::vector<double>& b){18double se = std::sqrt(variance(a)/ a.size()+19variance(b)/ b.size());20return(mean(a)-mean(b))/ se;21}
Each group contributes its own , and the two add under the square root. Adding the standard errors themselves, , is the usual slip: it overstates the uncertainty and hides real differences. The sign of only says which group is bigger.
14. Comparing groups: t-tests, chi-squared and ANOVA · The two-sample t-test · ProblemTwo classes sat the same test. Class 1: , , . Class 2: , , . Find the standard error of the difference in means and Welch’s t statistic for class 1 minus class 2.SE sqrt(8) ≈ 2.82843; 6/sqrt(8) ≈ 2.12132
Adding the two standard errors instead, , would give and hide much of the evidence. With Welch’s degrees of freedom (about 37 here) the two-sided p-value is about 0.04.
14. Comparing groups: t-tests, chi-squared and ANOVA · Paired data: test the differences · QuizTreating the same scores as two independent groups gives and . Why is the paired test so much stronger?B. It removes the big differences between students, leaving only each student’s changeThe scores range from 55 to 85 because the students differ, and an independent test counts all that as noise ( to ). The differences vary far less (), because each student is compared with themself. Pairing is only right when the data really are paired: using it on unrelated groups is wrong, and so is ignoring a pairing that exists.
14. Comparing groups: t-tests, chi-squared and ANOVA · Chi-squared compares counts with what you expected · QuizA goodness-of-fit test has degrees of freedom, for categories. With and a critical value of 11.07 at , what do you conclude?A. 5 degrees of freedom; reject: the die looks unfair ()Six faces, but the counts must add up to 60, so once five are known the sixth is fixed: degrees of freedom. The statistic passes the critical value, so reject. Notice that one face, 6, gives 10 of the 13.4: always look at which cells drive the result.
14. Comparing groups: t-tests, chi-squared and ANOVA · Chi-squared compares counts with what you expected · ProblemA sweet maker says its four colours are equally common. A bag of 200 has 62 red, 45 green, 38 yellow and 55 blue. Find the expected count of each colour, the chi-squared statistic and its degrees of freedom. (The critical value at is 7.81.)Expected count 50; 6.76; Degrees of freedom 3
Each colour is expected times.
Four colours give degrees of freedom. , so you fail to reject: gaps this size are ordinary chance in a bag of 200 (the p-value is about 0.08).
14. Comparing groups: t-tests, chi-squared and ANOVA · The chi-squared distribution · Code challengeWrite chiSquared(observed, expected): the sum over the categories of .One solution:
Solution
1#include<vector>23doublechiSquared(const std::vector<double>& observed,4const std::vector<double>& expected){5double total =0;6for(std::size_t i =0; i < observed.size(); i++){7double gap = observed[i]- expected[i];8 total += gap * gap / expected[i];9}10return total;11}
Squaring makes gaps above and below count alike; dividing by scales each gap to what is normal for that cell, since a count around 1000 naturally wobbles more than one around 10. Dividing by instead is a common slip, and it blows up when a cell is observed 0 times.
14. Comparing groups: t-tests, chi-squared and ANOVA · Chi-squared for independence in a table · Find the bugThis works out the expected counts, but they come out wrong. Which line?Line 15: expected[i][j] = rows[i] * cols[j] / total;Expected counts are row total × column total ÷ grand total. Dividing by the row total just gives the column totals back (100 and 300), which do not even add up to the 200 visitors in the row. A good check: the expected counts in each row and column add up to the same totals as the observed ones.
14. Comparing groups: t-tests, chi-squared and ANOVA · ANOVA compares the spread between groups with the spread within · QuizWhy use one ANOVA instead of t-tests on every pair of the three groups?A. Three t-tests at 0.05 each give more than a 5% chance of a false alarm in totalThree tests give about chance of at least one false alarm when all means are equal. ANOVA asks one question at one . It does not say which group differs: a significant only says "not all equal", and finding which needs follow-up comparisons with a correction (the last slide before the recap). It assumes roughly normal groups with similar spreads.
14. Comparing groups: t-tests, chi-squared and ANOVA · Computing the F statistic · Code challengeWrite fStatistic(groups): the one-way ANOVA F statistic for a list of groups, each a std::vector<double>. mean is written for you.One solution:
Solution
1#include<vector>23doublemean(const std::vector<double>& xs){4double sum =0;5for(double x : xs) sum += x;6return sum / xs.size();7}89doublefStatistic(const std::vector<std::vector<double>>& groups){10int k = groups.size();11 std::vector<double> all;12for(const std::vector<double>& group : groups)13for(double x : group) all.push_back(x);14int n = all.size();15double grand =mean(all);16double between =0; // sum of n_j * (group mean - grand)^217double within =0; // sum of (x - group mean)^218for(const std::vector<double>& group : groups){19double m =mean(group);20 between += group.size()*(m - grand)*(m - grand);21for(double x : group) within +=(x - m)*(x - m);22}23return between /(k -1)/(within /(n - k));24}
Each sum is divided by its own degrees of freedom: for between, for within. Forgetting to weight each squared gap by the group’s size goes unnoticed when the groups are equal, and gives the wrong answer in the third test, where they are not. With two groups, is exactly the square of the pooled two-sample .
14. Comparing groups: t-tests, chi-squared and ANOVA · Significant is not the same as large · QuizStudy A: 100,000 per group, , . Study B: 20 per group, , . Which found the larger effect?B. Study B, because its effect size is much largerThe p-value is smaller in A only because A is enormous. measures the effect itself, and B’s is almost 40 times bigger. B’s estimate is less precise, though: its confidence interval for is wide, which is the honest way to say so.
14. Comparing groups: t-tests, chi-squared and ANOVA · Many comparisons need a stricter bar · QuizYou compare 4 groups pairwise (6 pairs), using Bonferroni at an overall . One pair gives . Is it significant?B. No: each pair is tested at , and 0.012 is above itSix comparisons share the 0.05, so each gets . Equivalently, multiply the p-value by 6: . Bonferroni is simple and always valid, but it is conservative: with many tests it loses a lot of power.
14. Comparing groups: t-tests, chi-squared and ANOVA · Many comparisons need a stricter bar · Put in orderPut a careful comparison of several fertilisers in order.1. Decide the groups, the outcome and the tests before growing anything 2. Grow the plants and measure them 3. Run one ANOVA on all the groups 4. If it is significant, compare pairs with a correction such as Bonferroni 5. Report effect sizes and confidence intervals for the differencesPlanning first stops you choosing tests to fit the data. ANOVA guards the overall question, corrected pairwise tests answer "which", and effect sizes say whether the differences matter.
14. Comparing groups: t-tests, chi-squared and ANOVA · Practice problems · ProblemFive runners each ran 400 m before and after a training plan. Times in seconds, before: 62, 58, 65, 60, 70; after: 59, 53, 64, 56, 68. Using the improvements (before minus after), find the mean improvement , its standard deviation and the paired t statistic. 3 s; sqrt(2.5) ≈ 1.58114 s; 3/(sqrt(2.5)/sqrt(5)) ≈ 4.24264
The improvements are , with mean s.
The two-sided critical value for 4 degrees of freedom is 2.776, so the improvement is significant at 0.05 (). Treated as two independent groups, the big differences between runners would swamp it: would be only about 0.88.
14. Comparing groups: t-tests, chi-squared and ANOVA · Practice problems · Problem100 patients with back pain were split at random: 50 did a stretching programme and 30 of them improved; 50 had usual care and 20 of them improved. If improving is independent of the group, what is the expected number of improved patients in the stretching group? Find the chi-squared statistic and its degrees of freedom.Expected (stretching, improved) 25; 4; Degrees of freedom 1
The table: stretching, 30 improved and 20 not; usual care, 20 improved and 30 not. In all, 50 improved and 50 did not.
Every expected count is 25, and every observed count is 5 away from it:
4 is above the critical value 3.84, so improving and the programme look related (). Because the groups were randomised, this points to the stretching itself, not to who chose it.
14. Comparing groups: t-tests, chi-squared and ANOVA · Practice problems · ProblemThree fertilisers were each given to 4 plants. Growth in cm, A: 3, 5, 4, 4; B: 6, 7, 5, 6; C: 8, 7, 9, 8. Find the mean square between groups (MSB), the mean square within groups (MSW) and .MSB 16; MSW 2/3 ≈ 0.666667; 24
Group means: , , ; grand mean .
Within each group, the squared deviations from its own mean add to (A), (B) and (C):
An of 24 is far above 1: the fertilisers clearly differ (). ANOVA does not say which pairs differ; that needs corrected follow-up comparisons.
14. Comparing groups: t-tests, chi-squared and ANOVA · More practice problems · ProblemTwo groups of 10 pupils learned with different methods. Group 1 scored a mean of 52 with ; group 2 scored a mean of 47 with . Find the pooled standard deviation and Cohen’s .sqrt(50) ≈ 7.07107; 5/sqrt(50) ≈ 0.707107
A medium-to-large effect by the rough guide (0.5 medium, 0.8 large). With only 10 per group its confidence interval is wide, so the true effect could be much smaller or larger.
14. Comparing groups: t-tests, chi-squared and ANOVA · More practice problems · ProblemAfter a significant ANOVA on 6 groups, you compare every pair, using Bonferroni at an overall . How many comparisons are there, and at what level is each tested? One pair gives : what is its Bonferroni-adjusted p-value (the p-value times the number of comparisons)?Comparisons 15; Level for each 0.05/15 ≈ 0.00333333; Adjusted p-value 0.06
The pair with is above 0.00333, so it is not significant after the correction. Equivalently, its adjusted p-value is .
Uncorrected it would look significant, but with 15 comparisons and no real differences, the chance that at least one p-value falls as low as 0.004 is about 6%.
15. Linear regression · The best line makes the squared misses smallest · QuizWhy add up the squared residuals instead of the residuals themselves?B. Positive and negative residuals would cancel, so a terrible line could score 0A line far too high on the left and far too low on the right can have residuals that add to exactly 0. Squaring makes every miss count as a positive amount. It also makes big misses count more (a miss of 4 costs 16, a miss of 2 only 4), which is why one wild point can pull a least squares line a long way, as you will see later.
15. Linear regression · The least squares formulas · Fill the blanksFinish the last two lines: the slope, then the intercept from the means.1: /, 2: meanY, 3: meanXThe slope is . The intercept comes from making the line pass through : , so . A common slip is swapping the means, which gives , a nonsense intercept.
15. Linear regression · The least squares formulas · ProblemA small shop ran online adverts for 1, 2, 3, 4 and 5 hours on five days () and sold 3, 7, 5, 11 and 9 items (). Find the least squares slope and intercept . 1.6 items per hour; 2.2 items
The means are and . The deviations of are and of are .
The line is : each extra hour of adverts goes with 1.6 more items sold, on average.
15. Linear regression · Fitting the line in code · Code challengeWrite fitLine(xs, ys), returning the Line (its intercept and slope) of the least squares line. Use and .One solution:
Centring on the means first keeps the sums small and accurate. The shortcut formula gives the same answer on paper but can lose precision on a computer when the numbers are large and close together, because it subtracts two huge, nearly equal values. If every is the same, and the slope is undefined: no line can be fitted through a vertical stack of points.
15. Linear regression · Reading the slope and the intercept · QuizA fit of weekly sales (in units) on advertising spend (in thousands of euros) gives . Which reading is right?A. Each extra thousand euros of advertising goes with about 35 more units sold per week, on averageThe slope is in units of per unit of : units sold per thousand euros. It is an average association. Calling it a cause needs an experiment (later in the course), the intercept is a prediction with uncertainty, not a certainty, and a slope in a linear model is an amount, not a percentage.
15. Linear regression · R squared: the share of the variation the line explains · QuizIn a regression with one predictor, the correlation between and is . What is ?B. 0.36With a single predictor, : the line explains 36% of the variation in . is never negative for a least squares fit with an intercept, so the sign of the relationship lives in the slope, not in . Here is the correlation of the study data.
15. Linear regression · R squared: the share of the variation the line explains · ProblemFor the shop data ( = 1, 2, 3, 4, 5 and = 3, 7, 5, 11, 9), the least squares line is . Find SSE, SST and .SSE 14.4; SST 40; 0.64
Residuals, actual minus fitted: , , , , .
The line explains 64% of the variation in sales. With one predictor , so the correlation is , positive like the slope.
15. Linear regression · Residual plots show what the line missed · QuizThe residual plot for house price against floor area is narrow for small houses and much wider for big ones. What does it tell you?B. The spread of prices grows with size, so predictions for big houses are less preciseA fan shape means the variance is not constant (statisticians say heteroscedastic). The slope may still be fine, but the standard errors that assume equal spread are wrong. Common fixes are modelling the logarithm of price, or using standard errors that allow for unequal spread. Deleting data because it is inconvenient is never the answer.
15. Linear regression · Outliers and leverage: some points pull harder · QuizAt 10 hours with a score of 60, the new student drags the slope from 6 down to about 0.95. What makes this point so influential?B. It is far from the other points in , and its is far from where the line predicted (104)The line predicted , so the point misses by 44, and it sits 5 hours beyond the other data, where it has leverage. Place it at 10 hours with a score of 104 and the slope stays 6: high leverage alone does not change the fit if the point agrees with the line. Always plot the data and refit without suspicious points to see how much rides on them.
15. Linear regression · Predicting inside the data, not beyond it · QuizA line fitted to children aged 2 to 10 says height grows 6 cm a year. What does it predict for age 40, and should you trust it?B. About 3.2 m: do not trust it, growth stops in the late teensThe arithmetic still works (about 1.4 m at age 10, plus thirty years at 6 cm a year, is about 3.2 m), but the line only describes the ages it saw. A model is a summary of the data you have; outside that range it is a guess. This is the most common misuse of regression.
15. Linear regression · Is the slope real? Inference on the slope · Code challengeWrite slopeTest(xs, ys), returning a SlopeResult: the least squares slope, its standard error se, with , and t, .One solution:
Solution
1#include<cmath>2#include<vector>34structSlopeResult{5double slope, se, t;6};78doublemean(const std::vector<double>& v){9double sum =0;10for(double x : v) sum += x;11return sum / v.size();12}1314SlopeResultslopeTest(const std::vector<double>& xs,15const std::vector<double>& ys){16int n = xs.size();17double mx =mean(xs), my =mean(ys), sxy =0, sxx =0;18for(int i =0; i < n; i++){19 sxy +=(xs[i]- mx)*(ys[i]- my);20 sxx +=(xs[i]- mx)*(xs[i]- mx);21}22double slope = sxy / sxx;23double intercept = my - slope * mx, sse =0;24for(int i =0; i < n; i++){25double residual = ys[i]- intercept - slope * xs[i];26 sse += residual * residual;27}28double se = std::sqrt(sse /(n -2))/ std::sqrt(sxx);29return{slope, se, slope / se};30}
The divisor is , not : a line uses two estimated numbers, so only residuals are free to vary. Dividing by or is the usual slip, and it makes the standard error too small and the test too eager to find an effect.
15. Linear regression · Practice problems · ProblemStill with the shop data: , , and . Find , the standard error of the slope and the t statistic for . (The two-sided 5% critical value for 3 degrees of freedom is 3.182.)sqrt(4.8) ≈ 2.19089; sqrt(4.8)/sqrt(10) ≈ 0.69282; 1.6/sqrt(0.48) ≈ 2.3094
, so the slope is not significant at 0.05, even though . Five points are too few: the 95% interval for the slope, , runs from about to and includes 0.
15. Linear regression · Practice problems · ProblemFor a group of students, hours of revision have mean 10 and standard deviation 5, exam scores have mean 60 and standard deviation 12, and the correlation is . Find the least squares slope and intercept for predicting score from hours, and the predicted score for 15 hours. 1.44 points per hour; 45.6 points; at 15 hours 67.2 points
15 hours is one standard deviation above the mean, and the prediction is only of a standard deviation above the mean score: . That shrinking by is regression to the mean, which module 19 returns to.
15. Linear regression · Practice problems · ProblemA fit of fuel use (, litres per 100 km) on car mass (, in hundreds of kg) gives , with correlation . A car of 1400 kg uses 9.1 litres per 100 km. Find its predicted fuel use, its residual and the of the fit.Predicted 8.8 L/100 km; Residual 0.3 L/100 km; 0.81
The residual is litres per 100 km: this car uses a little more than the line predicts for its mass.
With one predictor, : mass explains 81% of the variation in fuel use.
Putting in instead of 14 is the trap here: always use the units the model was fitted in.
15. Linear regression · Practice problems · ProblemThe study data of this module are = 1, 2, 3, 4, 5 hours and = 51, 54, 62, 70, 73 points, fitted by . A sixth student studied 8 hours and scored 50. What did the line predict for them, what is their residual, and what is the slope refitted to all six? For the six, , , and .Prediction at 8 hours 92 points; Residual -42 points; New slope 10/(119 - 23^2/6) ≈ 0.324324 points per hour
The old line predicts points, so the residual is .
Refit with all six. The means are and :
One student, far out in and far below the line, drags the slope from 6 down to about 0.32 points per hour. Before believing either line, look at that point: is it a typing error, or a different kind of student?
15. Linear regression · Recap · Put in orderPut a regression analysis in a sensible order.1. Draw a scatter plot of the data 2. Fit the least squares line 3. Look at the residual plot for curves, fans and outliers 4. Report the slope with its confidence interval and 5. Predict only within the range of the dataPlot first: a scatter plot can show in a second that a line is the wrong model. Fit, then check the residuals before believing any number, because standard errors and p-values rely on the conditions you check there. Only then report, and predict where the data supports it.
16. Multiple and logistic regression · Each coefficient holds the others fixed · QuizOn its own, the number of bedrooms has a positive slope for price. Add floor area to the model, and the bedrooms coefficient turns negative. How can that be?B. Among houses of the same size, more bedrooms means smaller rooms, which buyers value lessAlone, bedrooms stand in for size: big houses have more bedrooms and cost more. With size in the model, the bedrooms coefficient answers a different question, "same floor area, one more bedroom", and cutting the same space into more rooms can lower the price. A coefficient’s meaning depends on what else is in the model, so always say what was held fixed.
16. Multiple and logistic regression · Each coefficient holds the others fixed · ProblemUse , with price in thousands of euros, the floor area in m² and the age in years. Predict the price of an 85 m² house that is 30 years old. Then find the predicted price of house A (100 m², 10 years old) minus that of house B (90 m², 40 years old).85 m², 30 years old 176 thousand €; A minus B 45 thousand €
For the difference, only the gaps in each predictor matter:
House A is predicted to cost 45 thousand euros more: 18 for being 10 m² bigger, and 27 for being 30 years newer.
16. Multiple and logistic regression · Categories enter as 0 or 1 · Fill the blanksCode a house in South for a model whose baseline neighbourhood is North.1: 0, 2: 1, 3: 0, 4: 0A South house has isSouth = 1 and isCentre = 0; the baseline, North, is 0 on both. Using three indicators, one per neighbourhood, plus an intercept is the classic mistake (the dummy variable trap): the three always add up to 1, the same as the intercept column, so the coefficients cannot be pinned down.
16. Multiple and logistic regression · Interactions let one slope depend on another variable · QuizWith and , how much more is a 120 m² house with a garage predicted to cost than one without?C. 36 thousandThe garage’s effect is thousand euros. With an interaction there is no single "garage effect": it depends on size. Reading alone as the garage effect is the usual mistake; here it is the effect at size 0, which no house has.
16. Multiple and logistic regression · Predictors that move together blur each other · QuizA model has both "height in cm" and "height in inches" as predictors. What happens, and what is the fix?B. They are perfectly correlated, so the coefficients cannot be separated; drop one of themInches are centimetres divided by 2.54, so and the VIF is infinite: any split of the effect between the two fits equally well. Drop one, or combine correlated predictors into one. Note that the predictions are fine; only the individual coefficients are meaningless.
16. Multiple and logistic regression · More predictors always fit better, and that is the trap · QuizYou add a column of random numbers to a regression. What happens to and to adjusted ?B. goes up a little (or stays); adjusted usually goes downLeast squares can only reduce SSE with an extra column, so cannot fall. Adjusted divides by , so a predictor that adds only chance-sized improvement lowers it. The honest test of a model is how well it predicts data it did not see: cross-validation (a later module) does exactly that.
16. Multiple and logistic regression · Coefficients act on the log odds · QuizWith , what does one more visit do?B. Multiplies the odds of buying by about 1.65The model is linear in log odds, so the effect is multiplicative on the odds: . The change in probability is not constant: from 2 to 3 visits it goes from 0.119 to 0.182, while from 10 to 11 visits it goes from 0.881 to 0.924. Reading a coefficient as a change in probability is the common mistake.
16. Multiple and logistic regression · Coefficients act on the log odds · Code challengeWrite sigmoid(z), ; probability(b0, b1, x), the logistic model’s ; and oddsRatio(b1), .One solution:
The sign in the exponent matters: std::exp(z) instead of std::exp(-z) gives , a curve that falls as visits rise. Writing probability through sigmoid keeps the model in one place. The odds ratio is , not : a coefficient of 0.5 is not "50% more likely".
16. Multiple and logistic regression · Coefficients act on the log odds · ProblemA logistic model for passing a driving test gives , where is the number of practice drives. What is the probability of passing after 5 drives, and after 7? By what factor does each extra drive multiply the odds? after 5 drives 0.5; after 7 drives 1/(1 + exp(-1.6)) ≈ 0.832018; Odds ratio exp(0.8) ≈ 2.22554
After 5 drives the log odds are , so the odds are and .
Two more drives multiply the odds by , taking them from 1 to about 4.95, while the probability rises from 0.5 to 0.83: odds change by a fixed factor, probabilities by no fixed amount.
16. Multiple and logistic regression · Gradient descent walks downhill to the best fit · QuizGradient descent’s error grows bigger on every step instead of shrinking. What is the likely cause?A. The learning rate is too large, so each step jumps past the minimum to a higher pointWith too big a step you land on the far side of the valley, higher than where you started, and the next step is bigger still. Too small a rate is the opposite problem: it does converge, just very slowly. A common remedy is to start with a modest rate and halve it whenever the error goes up.
16. Multiple and logistic regression · Fitting a line by gradient descent · Code challengeWrite descend(xs, ys, rate, steps): start at intercept 0 and slope 0, take steps gradient descent steps on the mean squared error, and return the Line.One solution:
Solution
1#include<vector>23structLine{4double intercept;5double slope;6};78Linedescend(const std::vector<double>& xs,9const std::vector<double>& ys,double rate,int steps){10int n = xs.size();11double intercept =0;12double slope =0;13for(int k =0; k < steps; k++){14double g0 =0, g1 =0;15for(int i =0; i < n; i++){16double miss = intercept + slope * xs[i]- ys[i];17 g0 +=2.0/ n * miss;18 g1 +=2.0/ n * miss * xs[i];19}20 intercept -= rate * g0;21 slope -= rate * g1;22}23return{intercept, slope};24}
Both gradients are summed with the old coefficients before either changes: updating the intercept first and then using it for the slope’s gradient is a subtle bug: it usually still converges, but it is no longer a true gradient step. Write 2.0 / n, not 2 / n: with an int of 5, 2 / n is 0, and the line never moves. One step from 0 with rate 0.01: the mean of is , so the intercept moves to ; the mean of is , so the slope moves to . Here descent finds the same that the formula gave, which is the point: the method works where no formula exists, as for logistic regression.
16. Multiple and logistic regression · Practice problems · ProblemA model with predictors fitted to observations has . Find its adjusted . A fifth predictor lifts to 0.61: what is the new adjusted ?Adjusted , 4 predictors 0.52; Adjusted , 5 predictors 1 - 0.39*24/19 ≈ 0.507368
went up, as it always does, but adjusted went down: the fifth predictor gained less than a predictor of pure noise would be expected to. Leave it out, or check it with cross-validation.
16. Multiple and logistic regression · Practice problems · ProblemRegressing floor area on the other predictors of a house-price model gives . What is the VIF of floor area, and by what factor is the standard error of its coefficient inflated? What would give a VIF of 5?VIF 4; SE inflated by 2; for a VIF of 5 0.8
The coefficient’s standard error is twice what it would be with uncorrelated predictors. For a VIF of 5:
16. Multiple and logistic regression · Practice problems · ProblemA model is , with price in thousands of euros, size in m², and garage 1 or 0. How much more is a house with a garage predicted to cost than one without, at 80 m²? At 120 m²? What is the slope of size for houses with a garage?At 80 m² 30 thousand €; At 120 m² 40 thousand €; Slope with a garage 2.25 thousand € per m²
With a garage minus without, at the same size :
At 80 m²: . At 120 m²: .
For houses with a garage the size terms add up to , so the slope is 2.25 thousand euros per m², against 2 without. With an interaction there is no single garage effect: it depends on the size.
16. Multiple and logistic regression · More practice problems · ProblemFor the shop model , with the number of visits, how many visits give an even chance of buying? How many give a 90% chance?For 6 visits; For (ln(9) + 3)/0.5 ≈ 10.3944 visits
An even chance is log odds 0: , so visits.
A 90% chance is odds of , so log odds of :
About 10.4 visits, 4.4 more than for an even chance. The curve is symmetric about its middle, so a 10% chance needs 4.4 fewer than 6, about 1.6 visits.
16. Multiple and logistic regression · More practice problems · ProblemFit to the points , and by gradient descent on the mean squared error, starting at with learning rate 0.1. The gradients are for and for . What are and after one step?11/15 ≈ 0.733333; 5/3 ≈ 1.66667
With the misses are .
Both move from the same old values. The least squares line here is , so this first step has already taken the slope past it; later steps pull it back.
16. Multiple and logistic regression · Recap · Put in orderPut one step of gradient descent in order.1. Predict every point with the current coefficients 2. Work out each residual, prediction minus actual 3. Average them into the gradient for each coefficient 4. Move every coefficient against its gradient, times the learning ratePredictions come first because the residuals need them, and the gradient is built from the residuals. All coefficients move together at the end, from the same old values. Then the loop repeats until the coefficients stop changing.
17. Simulation, the bootstrap and permutation tests · When the maths is hard, simulate · QuizA simulation with 10 000 runs gives an estimate with a standard error of 0.004. How many runs do you need for a standard error of about 0.001?C. 160 000The error goes like . To make it 4 times smaller you need times as many runs: 160 000. Guessing 40 000 is the usual slip: it forgets the square root. This is why simulations are cheap for two decimal places and expensive for five.
17. Simulation, the bootstrap and permutation tests · When the maths is hard, simulate · ProblemA simulation of 2500 runs gives 900 hits. What is the estimate , and its standard error? Using in place of , how many runs would bring the standard error down to 0.003? 0.36; SE 0.0096; Runs for an SE of 0.003 25600
To go from 0.0096 to 0.003, the SE must shrink by a factor of , so must grow by :
17. Simulation, the bootstrap and permutation tests · Computers fake randomness, on purpose · QuizYou run a bootstrap with std::mt19937 gen(7), get an interval, then run it again with a new std::mt19937 gen(7). What happens?A. You get exactly the same intervalThe seed fixes the whole sequence, so every resample, and the interval, repeat exactly. To see how much the answer moves because of the simulation itself, change the seed. Reporting the seed is part of making a simulation reproducible.
17. Simulation, the bootstrap and permutation tests · Your first Monte Carlo estimate · Code challengeWrite estimateHighRoll(trials, gen): roll two dice trials times using the generator gen and return the fraction of rolls whose sum is at least 10.One solution:
Solution
1#include<random>23intdie(std::mt19937& gen){4 std::uniform_int_distribution<int>roll(1,6);5returnroll(gen);6}78doubleestimateHighRoll(int trials, std::mt19937& gen){9int hits =0;10for(int i =0; i < trials; i++){11if(die(gen)+die(gen)>=10) hits++;12}13returndouble(hits)/ trials;14}
Count the hits and divide by the number of trials, as a double: hits / trials between two ints is 0. Each die(gen) call draws a fresh number, so the two dice are independent. A common mistake is rolling once and doubling it, 2 * die(gen), which makes the dice always equal (only 5+5 and 6+6 then count, and the estimate heads for 1/3). With 100 000 trials the standard error is about , so the estimate sits well within 0.005 of the truth, whatever the seed. The generator is passed by reference, std::mt19937&: a copy would carry on from the same state, and two copies replay the same rolls.
17. Simulation, the bootstrap and permutation tests · The bootstrap: the sample stands in for the population · QuizWhy must a bootstrap resample be drawn with replacement?A. Without replacement, every resample of size is the original sample reordered, so the statistic never variesTaking all values without replacement just shuffles them: the mean, median and every other statistic stay the same, so the spread you measure is zero. With replacement, each draw is like a fresh draw from a population shaped like your sample, which is exactly the pretence the bootstrap makes.
17. Simulation, the bootstrap and permutation tests · Bootstrapping the mean wait at a coffee shop · QuizThe interval, 3.8 to 7.9 minutes, is not centred on 5.7: it reaches 1.9 below but 2.2 above. Why?A. The data are skewed right, and the bootstrap carries that skew into the distribution of the meanA formula like is symmetric by construction. The percentile interval follows whatever shape the bootstrap distribution has, and with a long right tail in only ten values, high resample means are more likely than very low ones. That asymmetry is honest information a symmetric interval hides.
17. Simulation, the bootstrap and permutation tests · Bootstrapping the mean wait at a coffee shop · ProblemYou make bootstrap means and sort them, . For a 90% percentile interval, cut 5% off each end. Which sorted positions are the lower and upper ends?Lower end : 201; Upper end : 3800
5% of 4000 is 200. Cut 200 values off the bottom, to : the lower end is the next one, .
Cut 200 off the top, to : the upper end is .
In code, counting from 0, these are sorted[200] and sorted[3799]: the same std::floor(0.05 * B) and std::ceil(0.95 * B) - 1 as in the next challenge, with 0.05 and 0.95 for a 90% interval.
17. Simulation, the bootstrap and permutation tests · Write the bootstrap · Code challengeWrite bootstrapInterval(data, B, gen): make B resamples of data (with replacement), take each one’s mean, sort the means, and return the pair {sorted[floor(0.025 * B)], sorted[ceil(0.975 * B) - 1]}.One solution:
Solution
1#include<algorithm>2#include<cmath>3#include<random>4#include<utility>5#include<vector>67std::pair<double,double>bootstrapInterval(8const std::vector<double>& data,int B, std::mt19937& gen){9int n = data.size();10 std::uniform_int_distribution<int>pick(0, n -1);11 std::vector<double> means;12for(int b =0; b < B; b++){13double sum =0;14for(int i =0; i < n; i++) sum += data[pick(gen)];15 means.push_back(sum / n);16}17 std::sort(means.begin(), means.end());18int lower = std::floor(0.025* B);19int upper = std::ceil(0.975* B)-1;20return{means[lower], means[upper]};21}
Two loops: resamples, each of draws, then std::sort puts the means in order. The classic bug here is the distribution’s range: std::uniform_int_distribution<int> pick(0, n - 1) includes both ends, unlike most ranges in C++, so pick(0, n) would sometimes pick position n, one past the end of the data, which stops the program here and quietly reads garbage elsewhere. The percentile positions come from the prompt: index 50 and 1949 for (counting from 0), the and of the last slide. Your generator’s numbers differ from the slide’s, so your interval may differ in the first decimal: that wobble is the simulation’s own error.
17. Simulation, the bootstrap and permutation tests · Where the bootstrap fails · QuizYou bootstrap the maximum of 20 sensor readings. What does the bootstrap distribution look like?B. About 64% of resamples have exactly the sample maximum, and none is ever above itA resample misses the largest value with chance , so about 64% of resamples contain it and have exactly that maximum. No resample can go higher. The true maximum of the population is probably above the sample’s, and the bootstrap cannot see it. Extremes need other tools (extreme value theory).
17. Simulation, the bootstrap and permutation tests · Permutation tests: shuffle the labels · Put in orderPut the steps of a permutation test in order.1. Compute the observed statistic on the real groups 2. Pool all the values together 3. Shuffle the pool and split it into groups of the original sizes 4. Compute the statistic on the shuffled groups 5. Repeat the shuffle many times 6. Report the fraction of shuffles at least as extreme as the observed valueThe observed value comes first, because every shuffle is compared with it. Pooling and shuffling is what “the labels don’t matter” means in code. Keeping the group sizes fixed matters: the null hypothesis is about which values went where, not how many.
17. Simulation, the bootstrap and permutation tests · Write a permutation test · Find the bugThis shuffle runs, but some orders come up more often than others. Which line is wrong?Line 3: std::uniform_int_distribution<int> pick(0, i);Picking j from the whole vector makes equally likely runs, which cannot divide evenly among the orders, so some orders are favoured. Picking j from to gives runs, one per order. The biased version looks random and quietly skews every p-value built on it.
17. Simulation, the bootstrap and permutation tests · Write a permutation test · Code challengeWrite permutationPValue(a, b, shuffles, gen): the two-sided p-value for the difference in means, (count + 1) / (shuffles + 1), where count is how many shuffles give an absolute difference at least the observed one. Use the shuffle and mean given.One solution:
Solution
1#include<cmath>2#include<random>3#include<utility>4#include<vector>56doublemean(const std::vector<double>& xs){7double sum =0;8for(double x : xs) sum += x;9return sum / xs.size();10}1112voidshuffle(std::vector<double>& xs, std::mt19937& gen){13for(int i = xs.size()-1; i >0; i--){14 std::uniform_int_distribution<int>pick(0, i);15 std::swap(xs[i], xs[pick(gen)]);16}17}1819doublepermutationPValue(const std::vector<double>& a,20const std::vector<double>& b,int shuffles,21 std::mt19937& gen){22double observed = std::abs(mean(a)-mean(b));23 std::vector<double> pool = a;24for(double x : b) pool.push_back(x);25int count =0;26for(int k =0; k < shuffles; k++){27shuffle(pool, gen);28 std::vector<double>x(pool.begin(), pool.begin()+ a.size());29 std::vector<double>y(pool.begin()+ a.size(), pool.end());30if(std::abs(mean(x)-mean(y))>= observed -1e-9) count++;31}32return(count +1.0)/(shuffles +1);33}
Compare each shuffled absolute difference with the observed one, then add one to the count and to the total: the real labelling is itself one of the possible arrangements, and this keeps the p-value from ever being 0. Two traps: forgetting std::abs makes it one-sided, and comparing floats exactly can miss ties, because a shuffled mean of 2.5 may come out as 2.4999999999999996. The small tolerance 1e-9 counts them. And one that C++ adds: (count + 1) / (shuffles + 1) divides two ints, which gives 0 for every p-value below 1; count + 1.0 makes it a decimal division.
17. Simulation, the bootstrap and permutation tests · Cross-validation: test on data the model has not seen · Fill the blanksShuffled data points are dealt into k folds like cards. Complete the line that picks the test points for fold f.1: %, 2: ==, 3: !=pos % k deals positions 0, 1, …, k − 1, 0, 1, … so each fold gets every -th point and the folds differ in size by at most one. Shuffling first matters: data are often stored in order (by date, by shop), and unshuffled folds would test on a kind of data the model never trained on.
17. Simulation, the bootstrap and permutation tests · Cross-validation: test on data the model has not seen · QuizYou pick the 10 best of 1000 predictors using all the data, then run 5-fold cross-validation on a model with those 10. The score is excellent. What is wrong?B. The choice of predictors saw the test folds, so the score is optimisticEvery step that learns from data, including choosing predictors, scaling and tuning, must happen inside each training fold. Otherwise information leaks from the test fold into the model. With pure noise and 1000 predictors, this mistake can report impressive accuracy for a model that predicts nothing. Module 20 uses cross-validation to choose between models.
17. Simulation, the bootstrap and permutation tests · Practice problems · ProblemYou bootstrap a sample of values. What is the probability that one particular value is left out of a resample? On average, how many of the 10 values appear in a resample at least once?P(left out) 0.9^10 ≈ 0.348678; Expected number that appear 10*(1 - 0.9^10) ≈ 6.51322
So each value appears with probability . Adding that up over the 10 values (the expected value of a sum is the sum of the expected values):
A typical resample holds only about 6 or 7 of the 10 values, some of them more than once. For large the share tends to , close to the 64% of the bootstrap maximum quiz.
17. Simulation, the bootstrap and permutation tests · Practice problems · ProblemGroup A’s values are 7 and 9; group B’s are 2, 4 and 6. Find the observed difference in means, A minus B. How many ways are there to choose which 2 of the 5 values form group A, and what is the exact two-sided permutation p-value, the share of splits with an absolute difference at least as large as the observed one?Observed difference 4; Number of splits 10; Two-sided 0.2
Observed: .
There are splits. With the sum of the pair in group A, the difference is . The most extreme pairs:
The other six pairs ( = 9, 10, 11, 11, 13, 13) give differences from to . Only and reach an absolute difference of 4, so .
With so few values no result can be very convincing: even the most extreme split, , would give only .
17. Simulation, the bootstrap and permutation tests · Practice problems · ProblemYou run 5-fold cross-validation on 103 data points, dealing the shuffled points into folds with pos % 5. How many points are in fold 0, and how many in fold 4? The five folds’ test errors (mean squared errors) are 4.2, 3.8, 5.0, 4.6 and 4.4: what is the cross-validation score?Fold 0 21 points; Fold 4 20 points; Score 4.4
. Positions 100, 101 and 102 have remainders 0, 1 and 2, so folds 0, 1 and 2 get 21 points and folds 3 and 4 get 20.
Each model was trained on 82 or 83 points and tested on the 20 or 21 it never saw, so 4.4 is an honest estimate of the error on new data.
17. Simulation, the bootstrap and permutation tests · Practice problems · ProblemA sample of 15 delivery times has standard deviation minutes. What is the formula standard error of the mean, ? A large bootstrap treats the sample as the population, dividing by instead of : about what standard error should it give?Formula SE 4.2/sqrt(15) ≈ 1.08444 min; Bootstrap SE, about 4.2/sqrt(15)*sqrt(14/15) ≈ 1.04766 min
Resampling from the 15 values uses their spread with divisor , which is , so the bootstrap SE comes out near:
The bootstrap runs about 3% low here. The gap shrinks as grows, and a real bootstrap adds a little simulation noise on top.
18. Bayesian statistics · Probability as a degree of belief · QuizIf the prior gives every value of the same weight (a flat prior), what shape is the posterior?B. The same shape as the likelihood, rescaled to add up to 1Posterior ∝ likelihood × prior, and a constant prior changes nothing but the scale. So with a flat prior the most plausible value is the one that makes the data most probable: the maximum likelihood estimate of module 20. The posterior is normal only in special or large-sample cases.
18. Bayesian statistics · Updating with two possible coins · QuizSame data, 4 heads in 5, but now you know that only 1 coin in 10 in the pocket is a trick coin. What is the posterior probability it is the trick coin?B. About 0.23Prior × likelihood: trick , fair . The posterior is . The data still favour the trick coin by a factor of (the Bayes factor), but that is not enough to overturn a prior of 9 to 1 against. Ignoring the prior here is the base-rate fallacy from module 7.
18. Bayesian statistics · Updating with two possible coins · ProblemA box holds a fair coin and a bent coin that lands heads only 25% of the time. You pick one at random (prior 0.5 each) and flip it 3 times: 3 tails. Find the likelihood of 3 tails for each coin, and the posterior probability that you picked the bent coin.Likelihood, fair coin 1/8 ≈ 0.125; Likelihood, bent coin 27/64 ≈ 0.421875; P(bent | 3 tails) 27/35 ≈ 0.771429
With :
The data favour the bent coin by a Bayes factor of , which turns even odds into about 77%.
18. Bayesian statistics · A grid of possible values · Code challengeWrite gridPosterior(successes, failures, grid): with a flat prior, return the posterior probability of each value in grid, proportional to std::pow(p, successes) * std::pow(1 - p, failures) and adding up to 1.One solution:
Solution
1#include<cmath>2#include<vector>34std::vector<double>gridPosterior(int successes,int failures,5const std::vector<double>& grid){6 std::vector<double> weights;7double total =0;8for(double p : grid){9double w = std::pow(p, successes)* std::pow(1- p, failures);10 weights.push_back(w);11 total += w;12}13for(std::size_t i =0; i < weights.size(); i++) weights[i]/= total;14return weights;15}
Multiply prior by likelihood (with a flat prior, just the likelihood), then divide by the sum so the weights add up to 1. That division is the of Bayes’ theorem. Forgetting it is the usual slip: the shape is right, but the numbers are not probabilities. Grids work for one or two parameters; with ten parameters and 100 points each you would need grid cells, which is why MCMC exists.
18. Bayesian statistics · The beta distribution describes a proportion · QuizWhich prior says “the rate is probably near 0.25, and I am fairly sure”?B. Beta(25, 75)Both Beta(1, 3) and Beta(25, 75) have mean , but Beta(1, 3) is wide (its standard deviation is about 0.19) while Beta(25, 75) is narrow (about 0.043): it is worth about 100 earlier observations. Beta(75, 25) is centred on 0.75, the mirror image.
18. Bayesian statistics · Beta prior plus binomial data gives a beta posterior · Fill the blanksComplete the conjugate update.1: k, 2: n - kSuccesses add to , failures to . A tempting mistake is adding to : that counts the successes twice, once as successes and once as trials.
18. Bayesian statistics · Beta prior plus binomial data gives a beta posterior · ProblemA designer’s prior for a button’s click rate is . Then 12 of 20 visitors click. Find the posterior’s and , its mean, and the weight the posterior mean puts on the prior mean. 15; 15; Posterior mean 0.5; Weight on the prior mean 1/3 ≈ 0.333333
The weights are on the prior mean, , and on the data, :
The prior expected about 30%, the data said 60%, and the posterior lands at 50%, two thirds of the way toward the data.
18. Bayesian statistics · Credible intervals say what people wish confidence intervals said · QuizWhich sentence about the credible interval is correct?B. Given the Beta(2, 2) prior and the data, the cure rate is between 0.471 and 0.836 with probability 0.95A credible interval is a probability statement about the parameter, conditional on the prior and the model. The first option mixes in the frequentist repeated-sampling idea (and about the wrong quantity). The last confuses a parameter, one cure rate for the drug, with a spread across patients.
18. Bayesian statistics · A normal prior for a mean: precisions add · Code challengeWrite normalUpdate(priorMean, priorSd, sigma, n, xbar), returning the Posterior, its mean and sd, for a normal mean with known sigma.One solution:
Work in precisions: the data contribute because has variance . The common mistake is averaging the standard deviations or the variances; uncertainty combines by adding precisions, which is why the posterior is narrower than both the prior and the data alone. With a huge prior sd, the answer becomes with sd : the frequentist result.
18. Bayesian statistics · Choosing a prior, and how much it matters · QuizA Beta(20, 20) prior and 20 patients. Roughly how much do the prior and the data each weigh in the posterior mean?B. About two thirds the prior, one third the dataThe weight on the prior is . A prior worth 40 patients dominates a trial of 20. That is fine if the 40 are real earlier evidence, and a problem if they are only a hunch. Always report the prior, and check how the answer changes with others (a sensitivity analysis).
18. Bayesian statistics · MCMC: sampling a posterior you cannot write down · Put in orderPut one step of the Metropolis algorithm in order.1. Start from the current value of the parameter 2. Propose a new value nearby, at random 3. Compute the ratio of likelihood × prior at the proposal to that at the current value 4. Accept the proposal with probability min(1, ratio), otherwise stay 5. Record the current value as the next drawUphill moves (ratio above 1) are always taken; downhill moves sometimes. That “sometimes” is what makes the chain visit each region in proportion to its posterior probability, rather than just climbing to the peak. Because only a ratio is used, the unknown normalising constant cancels. When a proposal is rejected, the current value is recorded again: skipping it is a common bug that biases the draws.
18. Bayesian statistics · Bayesian and frequentist: two questions, often the same answer · QuizA manager asks: “What is the probability that the new page’s sign-up rate is higher than the old one’s?” Which approach answers that question directly?B. A Bayesian posterior for the difference in ratesThe question asks for a probability about parameters, which only a posterior gives: count the fraction of posterior draws where the new rate is higher. A p-value is the probability of data at least this extreme if there were no difference, a different quantity, and confusing the two is one of the most common errors in statistics.
18. Bayesian statistics · Practice problems · ProblemYour prior for a population mean is . Nine observations with known average . Find the posterior precision, the posterior mean and the posterior standard deviation.Precision 0.05; Posterior mean 108; Posterior sd sqrt(20) ≈ 4.47214
The data carry four times the prior’s precision, so the mean moves four fifths of the way from 100 to 110. The posterior sd, 4.47, is smaller than both the prior’s 10 and the data’s .
18. Bayesian statistics · Practice problems · ProblemUse a grid of three values, , and , with a flat prior. You see 2 successes in 3 trials. Find the posterior probability of each grid value. 0.15; 0.4; 0.45
Divide by the total: , and .
Two successes in three point toward the higher values, but with only three trials 0.5 is nearly as plausible as 0.75.
18. Bayesian statistics · Practice problems · ProblemA prior for a recovery rate is . Find its mean and standard deviation. A trial then sees 30 recoveries in 50 patients: what is the posterior mean?Prior mean 0.4; Prior sd sqrt(24/1100) ≈ 0.14771; Posterior mean 34/60 ≈ 0.566667
The data said . The prior, worth 10 observations against the data’s 50, pulls the estimate down only a little.
18. Bayesian statistics · More practice problems · ProblemBefore a study, you give a hypothesis probability 0.2. The study’s data are 6 times as probable if is true as if it is false: a Bayes factor of 6. Find the prior odds of , the posterior odds, and the posterior probability of .Prior odds 1/4 ≈ 0.25; Posterior odds 3/2 ≈ 1.5; Posterior probability 0.6
Dividing Bayes’ theorem for by Bayes’ theorem for not-, the evidence cancels:
Evidence of 6 to 1 is solid, yet it only lifts a sceptical 20% to 60%. The same data would take a 50% prior to .
18. Bayesian statistics · More practice problems · ProblemA posterior for a mean is normal with mean 108 and standard deviation . Find the central 95% credible interval, using 1.96, and the posterior probability that . Use .Lower end 108 - 1.96*sqrt(20) ≈ 99.2346; Upper end 108 + 1.96*sqrt(20) ≈ 116.765; 0.9633
Both are direct statements about , given the prior and the data: a 95% probability that it lies between 99.2 and 116.8, and a 96% probability that it is above 100. A confidence interval cannot be read this way.
19. Designing studies: experiments, causation and pitfalls · Watching is not the same as intervening · QuizA study follows 10 000 adults for 20 years and finds that those who chose to walk daily had fewer heart attacks. What kind of study is it, and what can it claim?B. An observational study: walking is associated with fewer heart attacksThe people chose whether to walk; nobody assigned it. That makes it observational, however large and long it is. It can show an association, and with care it can be strong evidence, but walkers may differ in other ways (diet, income, health to begin with). Size does not turn observation into an experiment, and observational studies are far from worthless: smoking was shown to cause cancer mostly with them.
19. Designing studies: experiments, causation and pitfalls · A confounder drives both the cause and the effect · QuizChildren with bigger shoe sizes score higher on reading tests. What is the most likely confounder?B. AgeOlder children have bigger feet and read better. Age causes both, so shoe size and reading move together. Compare children of the same age and the link disappears. When two things are correlated, always ask what could push both of them.
19. Designing studies: experiments, causation and pitfalls · Randomisation balances what you cannot see · Find the bugThis splits a website’s users into two groups for a test, but the groups are not comparable. Which line is the problem?Line 7: groups[users[i]] = uniform(gen) < 0.5 ? 'A' : 'B';The list is in sign-up order, so the first half, the oldest and most loyal users, all get A. Loyalty then confounds the comparison. The random generator is made but never used. Each user must get a group by chance: uniform(gen) < 0.5. Splitting by position, by id parity, or by day of the week is not randomisation, because each can line up with something that matters.
19. Designing studies: experiments, causation and pitfalls · Control groups and blinding · Put in orderPut the steps of a randomised controlled trial of a new pain relief tablet in order.1. Write down the outcome, the sample size and the analysis in advance 2. Recruit patients who meet the entry criteria 3. Randomly assign each patient to the tablet or an identical placebo 4. Give the tablets, with neither patients nor assessors knowing which 5. Measure pain scores at the planned time 6. Unblind and compare the groups as plannedPlan first, so the analysis cannot be bent to fit the data (module 20 calls this pre-registration). Patients are recruited before randomisation, so nobody can steer a patient into a group. Blinding lasts until the outcomes are in; only then is the code broken and the planned comparison made.
19. Designing studies: experiments, causation and pitfalls · An A/B test is an experiment on a website · Code challengeWrite twoProportionZ(xA, nA, xB, nB): the z statistic for B’s rate minus A’s, with the pooled standard error above. The counts are ints.One solution:
Solution
1#include<cmath>23doubletwoProportionZ(int xA,int nA,int xB,int nB){4double pA =double(xA)/ nA;5double pB =double(xB)/ nB;6double pooled =double(xA + xB)/(nA + nB);7double se =8 std::sqrt(pooled *(1- pooled)*(1.0/ nA +1.0/ nB));9return(pB - pA)/ se;10}
Under both versions share one rate, so the best estimate of it pools all the sign-ups: . Averaging the two rates instead is wrong when the groups differ in size. The usual slip is forgetting that the standard error has a term for each group, . In C++ every one of these divisions has two ints in it, so each needs a double on one side: xA / nA is 0, and so is 1 / nA, which would make the standard error 0.
19. Designing studies: experiments, causation and pitfalls · An A/B test is an experiment on a website · ProblemAn A/B test shows each version of a page to 3000 visitors. Version A gets 150 sign-ups and version B gets 195. Find the pooled sign-up rate, the pooled standard error of the difference, and the z statistic for B minus A.Pooled rate 0.0575; SE sqrt(0.0575*0.9425*2/3000) ≈ 0.00601075; 0.015/sqrt(0.0575*0.9425*2/3000) ≈ 2.49553
The rates are and . Under they share one rate:
The same 1.5-point gap as the worked example, with fewer visitors per version: falls from 2.88 to 2.50, but it is still beyond 1.96 (two-sided ).
19. Designing studies: experiments, causation and pitfalls · Selection and survivorship bias · Quiz"Old buildings were built better: the ones from 1800 are still standing, but modern ones crack." What is wrong with this argument?B. It only sees the 1800 buildings that survived; the badly built ones fell down or were demolishedThis is survivorship bias. Most buildings of 1800 are gone, and the poorly built ones went first, so the ones you can still visit are the best of their time. Modern buildings have not been through that filter yet. Whenever a sample has been through a filter, ask what the filter removed.
19. Designing studies: experiments, causation and pitfalls · Extreme results drift back toward the average · QuizA flight instructor notices that pilots who are praised after a great landing usually do worse next time, and those shouted at after a bad one usually do better. What does this show?B. Probably nothing about praise: extreme landings are followed by more typical ones either wayThis is Daniel Kahneman’s famous example. A great landing had good luck in it, so the next one is likely to be more ordinary, whatever the instructor says; the same in reverse for a bad one. Regression to the mean alone produces exactly this pattern. The fix is a control group: compare praised pilots with similar pilots who got no feedback.
19. Designing studies: experiments, causation and pitfalls · Extreme results drift back toward the average · Code challengeWrite predictRetest(score, mean, r): the expected second score of someone who got score, when both tests have the same mean and spread and correlate with r.One solution:
Solution
1doublepredictRetest(double score,double mean,double r){2return mean + r *(score - mean);3}
The distance from the mean, , shrinks by the factor . With , a score 20 above the mean is expected to come back only 12 above it: 82. With (pure luck), everyone is expected back at the mean. A common mistake is to think regression means scores become more alike over time; the spread stays the same, because new extreme scorers appear as old ones return.
19. Designing studies: experiments, causation and pitfalls · Extreme results drift back toward the average · ProblemTwo versions of a reasoning test both have mean 100 and standard deviation 15, and scores on them correlate with . A pupil scores 130 on the first. What is their predicted score on the second? And for a pupil who scored 85?After 130 121; After 85 89.5
Both are pulled toward 100: the high scorer is predicted 9 points lower, the low scorer 4.5 points higher, with no change in either pupil. In -scores, becomes and becomes .
19. Designing studies: experiments, causation and pitfalls · Simpson’s paradox: the whole can reverse the parts · QuizA new patient arrives and you know the size of their stone. Which table should guide the choice?B. The row for their stone size: compare like with likeWithin each size the patients are comparable, and A wins in both. The overall row mixes a different blend of easy and hard cases into each treatment, so it compares A’s hard cases with B’s easy ones. But do not make "always split the data" a rule: whether to split depends on the causal story. Splitting by a confounder is right; splitting by something the treatment itself causes can create a false difference.
19. Designing studies: experiments, causation and pitfalls · Causal diagrams say what to adjust for · QuizAmong famous actors, the more talented ones tend to be less good-looking. Suppose fame needs talent or looks, and in the whole population the two are unrelated. What explains the pattern?B. Fame is a collider: among the famous, lacking one trait means you must have had the otherTalent → fame ← looks. Looking only at the famous is adjusting for the collider. An actor who is not very good-looking must be talented to have made it, so within the famous group the two traits look negatively related, though they are not in general. This is collider bias (or Berkson’s paradox), and it is why "control for everything" is bad advice.
19. Designing studies: experiments, causation and pitfalls · Practice problems · ProblemTwo hospitals treat mild and severe cases. Hospital A: 95 of 100 mild patients survive, and 300 of 400 severe ones. Hospital B: 360 of 400 mild patients survive, and 70 of 100 severe ones. Find each hospital’s overall survival rate, as a percentage.Hospital A 79 %; Hospital B 86 %
Overall, B looks better. But within each kind of case A does better: 95% against 90% for mild cases, and 75% against 70% for severe ones.
A treats mostly severe cases (400 of its 500), and severe cases die more often anywhere. Severity is a confounder, and lumping the cases together reverses the comparison: Simpson’s paradox. To choose a hospital for a patient, compare like with like.
19. Designing studies: experiments, causation and pitfalls · Practice problems · ProblemAn A/B test meant to split 20 000 visitors 50/50 sends 10 300 to A and 9700 to B. If each visitor really had a 0.5 chance of A, what are the expected count in A and the standard deviation of that count? What does 10 300 give?Expected count 10000; SD of the count sqrt(5000) ≈ 70.7107; 300/sqrt(5000) ≈ 4.24264
A 52/48 split sounds harmless, but with 20 000 visitors it is over 4 standard deviations from 50/50: chance almost never does that. The assignment is broken (a sample ratio mismatch), so the test’s results cannot be trusted until the cause is found.
19. Designing studies: experiments, causation and pitfalls · Practice problems · ProblemA trial has 80 smokers among its patients, and each patient is assigned to treatment or control by a fair coin. What is the expected number of smokers in the treatment group, and the standard deviation of that number? How many standard deviations above the expected number would 49 smokers be?Expected 40; SD sqrt(20) ≈ 4.47214; for 49 9/sqrt(20) ≈ 2.01246
Randomisation balances smoking on average, and a split as uneven as 49 to 31 happens in only about 3% of trials. When a strong predictor like smoking is known in advance, blocking on it (randomising separately among smokers and non-smokers) balances it exactly.
19. Designing studies: experiments, causation and pitfalls · Practice problems · ProblemIn a randomised trial, 60 of 100 patients on a new tablet improved, against 45 of 100 on placebo. Find the difference in improvement rates, its standard error , and the upper end of the 95% interval for the difference ().Difference 0.15; SE sqrt(0.6*0.4/100 + 0.45*0.55/100) ≈ 0.0698212; Upper end 0.15 + 1.96*sqrt(0.004875) ≈ 0.28685
The tablet raises the improvement rate by somewhere between about 1 and 29 percentage points. The interval excludes 0, so the effect is significant at 5%, but its size is very uncertain: report the interval, not just “it works”.
A test of no difference uses the pooled SE of the A/B slide, because under the rates are equal; an interval lets each group keep its own rate.
20. Modelling like an expert · Likelihood turns probability around · QuizWith 7 heads in 10 flips, and . What does this say?B. The observed data are about 2.3 times as probable if p = 0.7 as if p = 0.5Likelihoods compare values of the parameter on the same data: . They do not add up to 1 over , so they are not probabilities of . A ratio of 2.3 is weak evidence; a fair coin gives 7 or more heads in 10 about 17% of the time.
20. Modelling like an expert · Maximum likelihood picks the best-explaining value · Code challengeWrite logLik(waits, rate), the exponential log-likelihood above, and bestRate(waits), which tries every rate from 0.001 to 10 in steps of 0.001 and returns the one with the largest logLik.One solution:
Solution
1#include<cmath>2#include<vector>34doublelogLik(const std::vector<double>& waits,double rate){5double total =0;6for(double x : waits) total += x;7return waits.size()* std::log(rate)- rate * total;8}910doublebestRate(const std::vector<double>& waits){11double best =0.001;12for(int i =1; i <=10000; i++){13double rate = i /1000.0;14if(logLik(waits, rate)>logLik(waits, best)) best = rate;15}16return best;17}
The sum of logs is , and the exponents add to . The search agrees with calculus: . Building the grid as i / 1000.0 avoids the drift you get from adding 0.001 ten thousand times; i / 1000, between two ints, would make every rate a whole number, and 0 for the first 999. Real software climbs the log-likelihood with Newton’s method or gradient ascent instead of a grid, but the idea is the same.
20. Modelling like an expert · Maximum likelihood picks the best-explaining value · ProblemFive coffee-shop waits are 1.5, 4, 2.5, 3 and 1 minutes. Modelling them as exponential with rate , find the maximum likelihood estimate and the log-likelihood there, .5/12 ≈ 0.416667 per minute; 5*ln(5/12) - 5 ≈ −9.37734
The waits add to , so minutes and per minute.
Check with calculus: setting the derivative to zero gives .
Every other rate gives a lower log-likelihood. The fitted model’s mean wait, minutes, is the sample mean.
20. Modelling like an expert · Every model trades bias against variance · QuizA model fits its training data almost perfectly () but predicts new data badly. What is the most likely problem?B. High variance: it has fitted the noise in the training dataA near-perfect training fit with poor new predictions is overfitting: the model has memorised the sample’s noise, which will not repeat. A model with high bias does badly on both training and new data. The fixes are a simpler model, regularisation, or more data, and judging the model on data it did not see.
20. Modelling like an expert · Compare models on what they have not seen · QuizWhich model does AIC prefer, and why not the degree-8 one?B. The quadratic: its fit is much better than the line’s, and the extra 6 parameters of degree 8 buy only 3.1 of log-likelihoodGoing from the line to the quadratic gains 8.3 in log-likelihood for one parameter: worth it. Going on to degree 8 gains 3.1 for six more parameters, each costing 1 in log-likelihood terms (2 in AIC). Differences in AIC above about 4 are usually taken as clear; 5.8 here. AIC only compares models fitted to the same data; its absolute value means nothing.
20. Modelling like an expert · Compare models on what they have not seen · Fill the blanksComplete the function that computes AIC from a model’s maximised log-likelihood.1: k, 2: logLikTwice the parameter count is the penalty; minus twice the log-likelihood is the misfit. A common slip is to use the likelihood itself instead of its logarithm, or to forget the minus sign and end up preferring the worst fit.
20. Modelling like an expert · Compare models on what they have not seen · ProblemModel A has parameters and maximised log-likelihood ; model B has and . Both are fitted to the same observations. Find each model’s AIC. Then find BIC(B) minus BIC(A), with .AIC of A 174.4; AIC of B 173.8; BIC(B) − BIC(A) 2*ln(50) - 4.6 ≈ 3.22405
AIC prefers B, but only by 0.6: as predictors, the two are about equally good.
BIC charges per parameter instead of 2, so it prefers the smaller model A. When the two criteria disagree, the evidence for the extra parameters is modest.
20. Modelling like an expert · Regularisation shrinks coefficients toward zero · Code challengeFor a line through the origin, the ridge slope is the sum of x * y divided by (the sum of x * x plus lambda). Write ridgeSlope(xs, ys, lambda).One solution:
Least squares through the origin gives . The penalty only enlarges the denominator, so the slope shrinks smoothly toward 0 as grows, but never reaches it: that is ridge’s signature, where lasso would hit 0 exactly. In practice, standardise the predictors first, so the penalty treats them alike, and do not penalise the intercept.
20. Modelling like an expert · The reproducibility crisis · QuizA field tests ideas of which 10% are true, with power 0.8 and . Of its significant results, what share are real effects?C. About 64%Per 1000 ideas: 100 true, of which 80 come out significant; 900 false, of which 45 come out significant by chance. Real ones: . The "95%" comes from confusing with the chance a finding is true, the same mistake as reading a p-value as the probability that is true. With power 0.2, the share falls to about 31%.
20. Modelling like an expert · Pre-register, then report the uncertainty · QuizA researcher tries three outcome measures, with and without outliers, and with two sets of control variables, then reports the one analysis with p = 0.03. Why is that p-value misleading?B. Because it was one of 12 analyses: the chance that at least one reaches p < 0.05 with no real effect is far above 5% paths. They are correlated, so the chance is less than , but still well above 0.05. Each analysis may be correct on its own; choosing among them after seeing the results is what breaks the p-value, because it was computed as if there had been only one. This is p-hacking, and it is often done in good faith.
20. Modelling like an expert · Mastery questions · QuizA 95% confidence interval for the difference in mean scores between two teaching methods is 1.1 to 4.1 points. Which statements are right?A. A two-sided test of "no difference" at would reject it; C. The method that made this interval captures the true difference in 95% of samplesAn interval that excludes 0 corresponds to rejecting at the matching level, and the 95% describes the method across repeated samples. The probability statement about this one interval needs a Bayesian posterior (module 18), which with a flat prior often gives a similar range. Whether 1 to 4 points matters is a question about the subject, not about statistics.
20. Modelling like an expert · Mastery questions · QuizA company finds that customers who used its new budgeting feature saved 30% more. It plans to tell all customers the feature makes them save more. What is the biggest problem?B. Customers chose to use it: careful savers are more likely to try a budgeting toolSelf-selection: the users differ from the non-users before they ever open the feature, so the comparison is confounded by how keen they were on saving. Even a tiny p-value would not fix it. The clean answer is an A/B test: offer the feature to a random half and compare everyone offered it with everyone not offered it (module 19).
20. Modelling like an expert · Mastery questions · QuizAn experiment with 2 million users per group finds a difference in sign-up rate of 0.01 percentage points, with p = 0.001. What follows?B. The effect is very probably real but tiny; whether it is worth anything is a business questionThe standard error shrinks like , so with millions of users even a minute difference is "significant". Significance says the effect is probably not zero, not that it is big. Report the size and its interval and judge it against the cost of the change.
20. Modelling like an expert · Mastery questions · QuizWhat does the bootstrap assume?B. That the sample is a fair stand-in for the population, drawn independentlyResampling from the sample treats it as a small copy of the population, so it needs a sample that represents it (random, independent draws). It does not need normality, which is its strength. It is not assumption-free: a biased sample gives a confident interval around the wrong value, and very small samples give intervals that are too narrow.
20. Modelling like an expert · Final challenge: an interval for a difference · Code challengeWrite diffInterval(a, b, c), returning the pair {low, high} for the mean of b minus the mean of a, using the standard error above and critical value c.One solution:
Solution
1#include<cmath>2#include<utility>3#include<vector>45doublemean(const std::vector<double>& x){6double sum =0;7for(double v : x) sum += v;8return sum / x.size();9}1011doublevariance(const std::vector<double>& x){12double m =mean(x), squares =0;13for(double v : x) squares +=(v - m)*(v - m);14return squares /(x.size()-1);15}1617std::pair<double,double>diffInterval(const std::vector<double>& a,18const std::vector<double>& b,19double c){20double diff =mean(b)-mean(a);21double se = std::sqrt(variance(a)/ a.size()+22variance(b)/ b.size());23return{diff - c * se, diff + c * se};24}
The means are 13.375 and 16, so the difference is 2.625. The sample variances are about 2.839 and 1.714, giving . The usual mistakes: dividing by instead of , adding the standard errors instead of the variances, or subtracting in the wrong order. With 8 per group, Welch’s t critical value is about 2.16, not 1.96, so the honest 95% interval is a little wider than the first two tests give.
20. Modelling like an expert · Practice problems: the whole course · ProblemIn a field, 20% of the hypotheses tested are true. Studies have power 0.5 and use . What share of significant results are real effects? What would it be if the power rose to 0.9?With power 0.5 5/7 ≈ 0.714286; With power 0.9 9/11 ≈ 0.818182
Per 1000 hypotheses: 200 are true and of them come out significant; 800 are false and of them come out significant by chance.
With power 0.9, true effects are found:
Better power helps, but the 40 false alarms from the 800 false hypotheses stay whatever the power. Only testing fewer long shots, or a stricter , cuts those.
20. Modelling like an expert · Practice problems: the whole course · ProblemTwo teaching methods were each used with 50 pupils. Method B’s mean score was 72.4 with ; method A’s was 68.1 with . Find the standard error of the difference (B minus A) and the 95% interval for it, with . Does a two-sided test at 0.05 reject “no difference”?SE sqrt(2.9) ≈ 1.70294; Lower end 4.3 - 1.96*sqrt(2.9) ≈ 0.96224; Upper end 4.3 + 1.96*sqrt(2.9) ≈ 7.63776
The interval leaves out 0, so the test rejects “no difference” at 0.05 (). But the effect could be anywhere from about 1 to 7.6 points: report the interval, not just “significant”.
20. Modelling like an expert · Practice problems: the whole course · ProblemOf 40 patients in a trial, 28 recovered. Find the 95% Wald confidence interval for the recovery rate (), and the posterior mean with a flat prior.Lower end 0.7 - 1.96*sqrt(0.21/40) ≈ 0.557985; Upper end 0.7 + 1.96*sqrt(0.21/40) ≈ 0.842015; Posterior mean 29/42 ≈ 0.690476
The two approaches nearly agree on the numbers, but not on the meaning: the interval’s 95% is the method’s hit rate over repeated samples, while the posterior gives probabilities for the recovery rate itself.
20. Modelling like an expert · More practice: the whole course · ProblemA regression on points gives slope with standard error 0.8. Find the t statistic for and the lower end of the 95% interval for the slope, using . About what standard error would you expect with four times as many points, spread the same way? 3.125; Lower end 0.852; SE with 4 times the points 0.4
Four times the points makes about four times bigger while stays about the same, so halves: about .
20. Modelling like an expert · More practice: the whole course · ProblemA lab tests 40 hypotheses at . Unknown to it, 10 are real effects, each found with power 0.8, and 30 are true nulls. How many false positives and how many true positives does it expect? What share of its significant results are real?False positives 1.5; True positives 8; Share that are real 8/9.5 ≈ 0.842105
False positives: . True positives: .
About 84% of its discoveries are real. With Bonferroni at (module 14) the expected false positives fall to , but the power falls too: every correction trades false alarms for missed effects.
20. Modelling like an expert · More practice: the whole course · ProblemA coin lands heads 8 times in 10 flips. Find the maximum likelihood estimate of , the likelihood ratio , and the one-sided p-value for a fair coin. 0.8; 0.8^8*0.2^2/0.5^10 ≈ 6.87195; 56/1024 ≈ 0.0546875
The MLE of a proportion is .
The data are about 7 times as probable with as with 0.5, yet the one-sided p-value is just above 0.05. They answer different questions: the likelihood ratio compares two values of , while the p-value asks how unusual 8 or more heads would be from a fair coin.