2. Estimation and regression

From observations to fitted predictions

Vadim Sokolov

George Mason University

Probability and Making Decision

The secretary problem: also called the matching or marriage problem.

  • You will see TT items, one at a time, from a distribution of types F(x)F(x).
  • You want the maximum. After you pass, you cannot go back.
  • tt is the slot you are in: t=1,…,Tt=1,\ldots,T.
  • Strategy: skip a prefix, then take the next candidate who is better than everyone you have seen.
  • For large TT the prefix is a fraction 1/e1/e of the list: 1e≈0.368. \frac{1}{e} \approx 0.368.

A Simple Example

Say I have a budget to consider T=10T=10 candidates, and they have the following scores (which I do not know)

    1  7  4  5  3  8  10  3  0  11

I decide to screen 3 candidates before making a decision.

  • My best candidate from the screening pool is 7
  • Next is 5 –> dump
  • Next is 3 –> dump
  • Next is 8 –> accept

Probability and Decision - Strategy

What’s your best strategy?

  • Turns out its insensitive to the choice of distribution.
  • Although there is the random sample i.i.d. assumption lurking.
  • You’ll not doubt get married between 1818 and 6060. Waiting 1e\frac{1}{e} along this sequence gets you to age 3333. Then, pick the next best person!

If you take the best so far at tt

  • TT is the length of the list. Ten candidates, T=10T=10.
  • tt is the slot you are looking at. In the example you accepted at t=6t=6.
  • Best so far at tt means better than the first t−1t-1. Candidate 8, after a screen whose best was 7.
  • The overall best is equally likely to sit in any of the TT positions.
  • Overall best implies best of the first tt, so P(overall best∣best so far at t)=P(overall best)P(best so far at t)=1/T1/t=tT. P(\text{overall best}\mid \text{best so far at }t) = \frac{P(\text{overall best})}{P(\text{best so far at }t)} = \frac{1/T}{1/t} = \frac{t}{T}.
  • Take that candidate and you win with probability t/Tt/T. In the example, 6/106/10.
  • If tt is the overall best, it is automatically the best of the first tt. The earlier ranks do not change the ratio.
  • Being the best of the first tt has probability 1/t1/t.

Success under the rr-rule

  • Reject the first rr. Then take the first later candidate who is the best so far.
  • You win only if you take the overall best. Put that person at slot aa. Probability 1/T1/T.
  • You never take them if a≤ra\le r: still screening.
  • If a>ra>r you still miss them whenever someone in r+1,…,a−1r+1,\ldots,a-1 was the best so far. That happens when the best of the first a−1a-1 sits after rr. You would have taken that person and gone home.

Success under the rr-rule

  • So you need the best of the first a−1a-1 to sit in the skipped prefix. Those a−1a-1 ranks are in random order, so their max is equally likely in any of those a−1a-1 slots: ra−1. \frac{r}{a-1}.
  • In the example, r=3r=3. If the overall best is at a=6a=6, the first five are 1,7,4,5,31,7,4,5,3. Their max is 77, in the prefix. Chance 3/53/5.
  • Denominator a−1a-1, not aa: slot aa is already the overall best. The comparison is among the others. P(success)=1T∑a=r+1Tra−1=rT∑b=rT−11b. P(\text{success}) = \frac{1}{T}\sum_{a=r+1}^{T}\frac{r}{a-1} = \frac{r}{T}\sum_{b=r}^{T-1}\frac{1}{b}.
  • Need r≥1r\ge 1. If r=0r=0 you take the first candidate and win with probability 1/T1/T.
  • If nobody after rr is the best so far, you take the last one. That path never wins.

Then r=T/er=T/e

  • For large TT the harmonic sum is a log: rT∑b=rT−11b≈rTlogTr. \frac{r}{T}\sum_{b=r}^{T-1}\frac{1}{b} \approx \frac{r}{T}\log\frac{T}{r}.
  • Differentiate in rr and set the derivative to zero: 1TlogTr−1T=0⇒r=Te. \frac{1}{T}\log\frac{T}{r}-\frac{1}{T}=0 \qquad\Rightarrow\qquad r=\frac{T}{e}.
  • Plug back in: P(success)≈1eloge=1e. P(\text{success})\approx\frac{1}{e}\log e=\frac{1}{e}.
  • About 3737 percent for large TT, approached from above.
  • This rr is best among skip-then-take-the-next-best-so-far rules. The Bellman step says the optimum is of that form.
  • The distribution of the scores never entered. Only the random order of the ranks.

Bellman check

  • p*(xt−1=0)p^*(x_{t-1}=0): chance of eventual success if you have not hired by t−1t-1.
  • At tt the candidate is the best so far with probability 1/t1/t. Take them if t/Tt/T beats the value of continuing.
  • Continuing after you pass on a best-so-far has the same value as continuing after a weaker candidate: the remaining permutation is still uniform. $$ p^(x_{t-1}=0) = ,p^(x_t=0)
  • (t/T,,p^*(x_t=0)). $$
  • Once t/Tt/T wins the max it keeps winning: the hire payoff rises, continuation falls.
  • The recursion telescopes from the end, p*(xT=0)=0p^*(x_T=0)=0, to p*(xt−1=0)=t−1T∑τ=t−1T−11τ, p^*(x_{t-1}=0)=\frac{t-1}{T}\sum_{\tau=t-1}^{T-1}\frac{1}{\tau},
  • That is the success probability of the rule that starts accepting at t−1t-1. Same rr.
  • Bellman: after the first decision the rest of the policy is still optimal.

1/e1/e in a sample of 10001000

The peak is near T/eT/e and height 1/e1/e (Monte Carlo, so the top wiggles).

  • Average quality, not shown, peaks much earlier.
  • Maximizing the chance of the absolute best is not the same as maximizing expected rank.

Decision Trees

Decision Tree

Catastrophe Modeling

You live in a house that is somewhat prone to mud slides.

  • Each rainy season there is a 1% chance of a mud slide occurring.
  • You estimate that a mud slide would do $1 million in damage.
  • You have the option of building a retaining wall that would help reduce the chance of a devastating mud slide. The wall costs $40,000 to build, and if the slide occurs, the wall will hold with a 95% probability.
  • You also have the option of a Geologist’s opinion.

Should you build the wall? Should you use the Geologist’s Test and Bayes Rule?

Decision Tree Setup

Let’s formally solve this as follows:

  • Build a decision tree.
  • The tree will list the probabilities at each node. It will also list any costs there are you going down a particular branch.
  • Finally, it will list the expected cost of going down each branch, so we can see which one has the better risk/reward characteristics.

There’s also the possibility of a further test to see if the wall will hold.

Decision Tree

Mudslide Decision Tree

Testing Option

Let’s include the testing option

  • You also have the option of having a test done to determine whether or not a slide will occur in your location.
  • The test costs $3000 and has the following accuracies. P(T∣Slide)=0.90andP(T‾∣No Slide)=0.85P(T \mid \text{Slide}) = 0.90 \quad \text{and} \quad P(\bar{T} \mid \text{No Slide}) = 0.85

If you choose the test, then should you build the wall?

Bayes Rule for Testing

Bayes Rule is as follows:

  • The initial prior probabilities are P(Slide)=0.01andP(No Slide)=0.99P(\text{Slide}) = 0.01 \quad \text{and} \quad P(\text{No Slide}) = 0.99
  • Therefore P(T)=P(T∣Slide)P(Slide)+P(T∣No Slide)P(No Slide)P(T)=0.90×0.01+0.15×0.99=0.1575\begin{align*} P(T) &= P(T \mid \text{Slide}) P(\text{Slide}) + P(T \mid \text{No Slide}) P(\text{No Slide}) \\ P(T)&= 0.90 \times 0.01 + 0.15 \times 0.99 = 0.1575 \end{align*}

We’ll use this to find our optimal course of action.

Bayes Probabilities - Positive Test

The Bayes probability given a positive test is P(Slide∣T)=P(T∣Slide)P(Slide)P(T)=0.90×0.010.1575=0.0571\begin{align*} P(\text{Slide} \mid T) &= \frac{P(T \mid \text{Slide}) P(\text{Slide})}{P(T)} \\ &= \frac{0.90 \times 0.01}{0.1575} = 0.0571 \end{align*}

Bayes Probabilities - Negative Test

The Bayes probability given a negative test is P(Slide∣T‾)=P(T‾∣Slide)P(Slide)P(T‾)=0.1×0.010.8425=0.001187\begin{align*} P(\text{Slide} \mid \bar{T}) &= \frac{P(\bar{T} \mid \text{Slide}) P(\text{Slide})}{P(\bar{T})} \\ &= \frac{0.1 \times 0.01}{0.8425} \\ &=0.001187 \end{align*}

Compare this to the initial base rate of a 11% chance of having a mud slide.

Probability Lose Everything - Without Testing

You build the wall without testing, what’s the probability that you lose everything?

With the given situation, there is one path (or sequence of events and decisions) that leads to losing everything:

  1. Build without testing (given)
  2. Slide (0.010.01)
  3. Doesn’t hold (0.050.05)

P(losing everything∣build w/o testing)=0.01×0.05=0.0005P(\text{losing everything} \mid \text{build w/o testing}) = 0.01 \times 0.05 = 0.0005

Probability Lose Everything - With Testing

You choose the test, what’s the probability that you’ll lose everything?

There are two paths that lead to losing everything:

  1. First Path: There are three things that have to happen to lose everything Test +ve (P=0.1575P=0.1575), Build, Slide (P=0.0571P= 0.0571), Doesn’t Hold (P=0.05P=0.05)
  2. Second Path: Now you lose everything if Test -ve (P=0.8425P=0.8425), Don’t Build, Slide given negative (P=0.001187P=0.001187)

Conditional Probabilities

For the first path P(first path)=0.1575×0.0571×0.05=0.00045P(\text{first path}) = 0.1575 \times 0.0571 \times 0.05 = 0.00045

For the second path P(second path)=0.8425×0.001187=0.00101P(\text{second path}) = 0.8425 \times 0.001187 = 0.00101

Hence putting it all together P(losing everything∣testing)=0.00045+0.00101=0.00146P(\text{losing everything} \mid \text{testing}) = 0.00045 + 0.00101 = 0.00146

Risk and Reward

Risk-Return Trade-off

Choice Expected Cost Risk P
Don’t Build $10,000 0.01 1 in 100
Build w/o testing $40,500 0.0005 1 in 2000
Test $10,760 0.00146 1 in 700

Expected Cost: Fee + Build + Loss

Expected cost: 3+40×0.1575+1000×0.001463 + 40\times 0.1575+ 1000\times 0.00146 or $10,760

What do you choose?

Estimation

Three situations

Map for the hour

    1. No data
  • No sample. You post a price.
  • Coin, a bet, coherence.
  • Secretary. Mudslide prior.
    1. Good data
  • n/N you can trust.
  • More of the same sample, tighter around the right number.
  • Alpha particles: the worked example.
    1. Bad data
  • Looks like 2. Most dangerous.
  • Tiny interval, wrong sample.
  • Literary Digest, WHI, Spirit.
  • The trap is mixing 2 and 3. The machine sounds like 2.

1. No data

  • No sample from the process you will decide for.
  • Probability is a language for uncertainty. Usually lack of information, not a property of the coin.
  • Operational answer: a price you would bet at.
  • The number has to cohere. Otherwise someone books you.

How many coins in my pocket?

Probability is a property of what you know.

Probability as a bet

  • Ramsey and de Finetti: your probability is the odds at which you will bet.
  • de Finetti: “Probability does not exist.” Uncertainty is personal. It is not mass.
  • Different news, a trade, a price.
  • 2016: bookmakers posting prices on the same event. Those prices are probabilities.
  • This course uses both languages. Frequency is how we talk about data. The organizing view is belief, updated by evidence.

Presidential odds, 2016

The coin is risk

  • Most people agree on P(Heads)=1/2P(\text{Heads})=1/2. We elicit that number as a willingness to play.
  • Will you pay $1 to receive $2 if the coin lands tails, and $0 if it lands heads? If you are indifferent, your P(Tails)P(\text{Tails}) is 1/21/2.
  • Probability and payoff arrive together. You cannot separate them.
  • Litowitz asks the same question, then raises the payoff. Pay $1 for a fair coin that pays $2 on heads. Most people pause. Make it $3 on heads. Almost everyone says yes.
  • We know the possibilities and we know the odds, fifty-fifty. That is risk.
  • The mudslide tree was the same object: 0.010.01 from historical seasons, 0.950.95 treated as known.

The odds are not posted

  • Often you will decide on something that does not look like a coin. A career, which model to ship, whether the merger closes.
  • You know the possibilities and not the probabilities. That is ambiguity, not risk: Ellsberg’s second urn.
  • Knight called the same contrast uncertainty. That is the word Litowitz used.
  • Sometimes you do not even know the possibilities. Then you are past Ellsberg.
  • The tools for the coin do not transfer.
  • Three bad moves: freeze, pretend the odds are knowable, or hand the decision to a machine that sounds sure.
  • The machine is superb at the coin. The rest stay yours.
  • The move that still works: a strong provisional view, name what would change your mind, run the cheapest experiment, update.
  • Stay the author of the decision. That is Bayes as a habit, not a formula.

Litowitz, Fortune, 15 September 2026. Opening of The Adaptability Quotient.

Dutch book

  • If you set P(A)=0.7P(A)=0.7 and P(A‾)=0.2P(\bar A)=0.2, someone can lock in a loss against you.
  • Pay $0.70 on AA and $0.20 on A‾\bar A. You pay $0.90 and receive $1 either way.

  • Coherence means no Dutch book exists. In finance that is no-arbitrage.
  • The leak is P(A)+P(A‾)=0.9≠1P(A)+P(\bar A)=0.9\neq 1.

Kolmogorov’s axioms

Coherence forces the same rules Kolmogorov wrote down.

  1. Non-negativity: P(A)≥0P(A)\ge 0
  2. Normalization: P(Ω)=1P(\Omega)=1
  3. Additivity: if AA and BB cannot both happen, P(A or B)=P(A)+P(B)P(A\text{ or }B)=P(A)+P(B)

The complement rule P(A)+P(A‾)=1P(A)+P(\bar A)=1 is 2 and 3 together. Violate any of them and someone can lock in a loss.

How do we estimate a probability?

  • Assigning the number is the hard part.
  • No data: a price you would bet at.
  • Good data: a long-run frequency from the process you will decide for.
  • Bad data: same plot, wrong process. Looks trustworthy. That is the dangerous one.

2. Good data

  • A sample from the process you will decide for.
  • Then you estimate: n/N, a mean, a Poisson λ\lambda.
  • Trust in the usual sense: more good data, smaller variance around the right number.
  • Frequency, then a sampling distribution. Alpha particles after the warning.

Frequency

  • Event AA is heads.
  • Each grey path is one sequence of tosses. The blue path is one of them. The red line is 1/21/2.

As NN grows, n/Nn/N settles near 1/21/2.

  • That is the law of large numbers.
  • von Mises wrote the limit as the definition: P(Heads)=limN→∞nN. P(\text{Heads}) = \lim_{N \to \infty} \frac{n}{N}.

Fitting a probability law

  • Fit a Poisson or a Normal to observed data.
  • Most laws depend on a few parameters: λ\lambda, or μ\mu and σ\sigma.
  • Estimate those from the sample. Then the distribution is specified.
  • Then ask whether the fit is any good. Later.

3. Bad data

  • Same shape as 2: rows, a histogram, a tight number.
  • Blue is the sample. Orange is the law you fit. They already miss.
  • The red target is the population you will decide for.
  • Most dangerous because it looks like good data. Tiny interval, wrong sample.

  • Bias, not variance. We name this after sampling distributions: Literary Digest, WHI.
  • Wrong law is the same trap: a tight Normal on the sample, a crash the model called impossible.

The 1987 crash

  • October 1987: S&P 500 dropped −21.76%-21.76\%.
  • Prior monthly returns: mean 1.2%1.2\%, volatility 4.3%4.3\%.
  • The model fitted to earlier months: X∼N(0.012,0.0432)X \sim N(0.012, 0.043^2).
  • Standardize: Z=−0.2176−0.0120.043=−5.34. Z = \frac{-0.2176 - 0.012}{0.043} = -5.34.
  • A 5-sigma month. Under that Normal, P(Z<−5.34)≈4.6×10−8P(Z < -5.34) \approx 4.6 \times 10^{-8}.

The 1987 crash: the model

  • We assumed returns are Normal. The middle of the histogram looks like 2.
  • The tails are not. Extreme months happen. The crash is one of them.
  • Same picture as the orange curve: a law fitted to the sample, a target the law cannot see.
  • Week 1 computed the z-score. The lesson here is the assumption.

S&P 500 returns vs Normal

The limit is not always a method

  • Same plot as 2: n/Nn/N settling toward a number. That is what makes 3 dangerous.
  • The von Mises limit needs an infinite sequence of repeatable trials. You never observe it.
  • Ville pointed this out. Bernoulli’s workable version is the finite ratio n/Nn/N in the experiment you actually ran.
  • It requires the same conditions. Change the coin, and the number changes.
  • Blue is fair. Orange is P(Heads)=0.7P(\text{Heads})=0.7. Same NN. Two different samples. Two different limits.

Data-driven AI

  • Modern AI is data-driven. The rest of the course is this approach: estimate from samples, then predict.
  • A model trained on a limited sample is a frequency from that sample. The interval can be tiny around the wrong number.
  • Very common in modern AI: confident when it should not be. The machine sounds sure. The sample was not the population.

Data is a currency

  • Self-driving is sold as a data race: the fleet that logs the most miles trains the better driver. Tesla’s pitch. Waymo’s counter: unsupervised miles are not the same as a human still in the seat.
  • Data sells. Spirit Airlines, in bankruptcy in 2026, auctioned an operational archive. Google’s bid was $10 million: emails, chats, operations, for AI.
  • The named passenger list was carved out of that Google deal. The estate kept the right to sell it to travel buyers.
  • Ars Technica, September 2026.

From posting a price to estimating one

  • Whenever we have a sample we should estimate from it.
  • First a pattern with no named law: correlation. Two series, one number rr.
  • Then a law with a named parameter. The alpha counts: we estimate λ\lambda in the open.
  • Good data if the sample is from the process you will decide for. Bad data is the standing risk: same formulas, wrong population.
  • The mudslide 0.010.01 was a frequency from historical data, then treated as known.
  • Working mechanism after the pattern: frequency. n/Nn/N, likelihood, sampling distributions.

Unsupervised patterns

Why Pattern Matching?

  • Traditional approach: estimating parameters when functional form is known
    • Linear relationships (Earth-shape example)
    • Multiplicative relationships (Newton’s F=maF=ma)
  • Modern challenge: relationship itself is unknown
    • Human behavior, natural language
    • Complex, non-mathematical relationships
  • Pattern matching: identifying recurring sequences, relationships, or structures
    • Like finding puzzle pieces that complete a picture

Early Example: Mammography

Albert Solomon (1913)

  • German surgeon, pioneer of X-ray imaging
  • “Contributions to the Pathology and Clinic of Breast Cancers”
  • First to recognize calcium deposits-cancer association

Challenges

  • Subjective visual assessment
  • Prone to errors in dense breasts
  • Subtle abnormalities easily missed

Pattern recognition

  • Dense tissue areas (masses)
  • Small white calcium deposits (microcalcifications)

Impact

  • Foundation for mammography screening
  • Saved countless lives
  • Molecular mechanisms still not fully understood

Feynman on Pattern Matching

Chess Analogy

“Let’s say a chess game. And you don’t know the rules… you try to figure out what the rules are… You might discover that when there’s only one bishop around on the board, that the bishop maintains its color. Later on you might discover the law for the bishop is that it moves on a diagonal…”

  • Experts develop pattern recognition abilities
  • Chess players don’t calculate every move
  • They recognize advantageous patterns
  • Skill transfers to other domains

Machine vs Human Intelligence

Feynman on AI

“When we make a bird, the airplanes don’t fly like a bird… It’s different, right? So, there’s no question that the later machines are not going to think like people think… they’re not going to do arithmetic the same way as we do arithmetic, but they’ll do it better.”

Evolution in Chess:

  • 1996: Computers stronger than grandmasters
  • AlphaZero: Self-learning through competition
  • Neural networks learn features vs human heuristics
  • Preference for initiative, speed, momentum over material

Correlations: Simplest Pattern Matching

Correlation coefficient: measures strength of linear relationship

r=cov(X,Y)var(X)var(Y)r = \frac{\text{cov}(X,Y)}{\sqrt{\text{var}(X)} \sqrt{\text{var}(Y)}}

Range: −1≤r≤1-1 \leq r \leq 1

Applications:

  • Financial market relationships
  • Portfolio diversification
  • Risk assessment

Google Stock Example

Unsupervised Learning: Election Forecasting

2012 Obama Election Prediction

  • Goal: predict probability of Obama winning
  • Data: polling data across 50 states + DC
  • Method: Bayesian simulation with Dirichlet distribution
  • Technique: Monte Carlo simulation (10,000 runs)

Loading the data and aggregating it by state.

Display the data

Election 2012 Data
state R.pct O.pct EV
Alabama 61 38 9
Alaska 55 42 3
Arizona 54 44 11
Arkansas 61 37 6
California 38 59 55
Colorado 47 51 9
Connecticut 40 58 7
D.C. 7 91 3
Delaware 40 59 3
Florida 49 50 29
Georgia 53 45 16
Hawaii 28 71 4
Idaho 65 33 4
Illinois 41 57 20
Indiana 54 44 11
Iowa 47 52 6
Kansas 60 38 6
Kentucky 61 38 8
Louisiana 58 41 8
Maine 41 56 4
Maryland 37 62 10
Massachusetts 38 61 11
Michigan 45 54 16
Minnesota 45 53 10
Mississippi 56 44 6
Election 2012 Data
state R.pct O.pct EV
26 Missouri 54 44 10
27 Montana 55 41 3
28 Nebraska 61 38 5
29 Nevada 46 52 6
30 New Hampshire 46 52 4
31 New Jersey 41 58 14
32 New Mexico 43 53 5
33 New York 36 63 29
34 North Carolina 51 48 15
35 North Dakota 59 39 3
36 Ohio 48 50 18
37 Oklahoma 67 33 7
38 Oregon 43 54 7
39 Pennsylvania 47 52 20
40 Rhode Island 36 63 4
41 South Carolina 55 44 9
42 South Dakota 58 40 3
43 Tennessee 60 39 11
44 Texas 57 41 38
45 Utah 73 25 6
46 Vermont 31 67 3
47 Virginia 48 51 13
48 Washington 42 56 12
49 West Virginia 62 36 5
50 Wisconsin 46 53 10
51 Wyoming 69 28 3

Run the simulation and plot probabilities by state.

Probabilities of Obama winning by state

Probabilities of Obama winning by state

Simulate the probability of Obama winning the election.

Calculate the probability of Obama having 270 EV or more

[1] 0.9631

Plot the distribution of the simulated electoral votes for Obama.

Beta distribution

  • A law on a single probability, θ∈(0,1)\theta \in (0,1). Coin, poll share, conversion rate. f(θ)=Γ(α+β)Γ(α)Γ(β)θα−1(1−θ)β−1. f(\theta) = \frac{\Gamma(\alpha+\beta)}{\Gamma(\alpha)\Gamma(\beta)}\,\theta^{\alpha-1}(1-\theta)^{\beta-1}.
  • α\alpha and β\beta are positive. Mean α/(α+β)\alpha/(\alpha+\beta).
  • Beta(1,1)\mathrm{Beta}(1,1) is uniform. Larger α+β\alpha+\beta: tighter around the mean.
  • Two shares that sum to 1: Obama vs not Obama is a Beta. Three shares need Dirichlet.

Dirichlet Distribution

  • Same idea for kk shares that sum to 1. Poll: Republican, Democrat, other.
  • k=2k=2 is Beta: Dirichlet(α,β)=Beta(α,β)\mathrm{Dirichlet}(\alpha,\beta)=\mathrm{Beta}(\alpha,\beta).
  • Parameters α=(α1,…,αk)\alpha=(\alpha_1,\ldots,\alpha_k), each αi>0\alpha_i>0.
  • Support: xi≥0x_i\ge 0 and ∑ixi=1\sum_i x_i=1. f(x∣α)=Γ(∑iαi)∏iΓ(αi)∏i=1kxiαi−1. f(x\mid\alpha)=\frac{\Gamma(\sum_i\alpha_i)}{\prod_i\Gamma(\alpha_i)}\prod_{i=1}^k x_i^{\alpha_i-1}.

Dirichlet Distribution

Application in Election Forecasting:

  • Models uncertainty in polling percentages
  • Three components: Republican, Democrat, Undecided
  • Parameters reflect poll sample sizes and percentages
  • Generates probability distributions for each candidate’s support

Why Use Dirichlet for Polling?

  • Naturally handles the constraint that percentages sum to 100%
  • Incorporates polling uncertainty
  • Allows for Monte Carlo simulation of election outcomes
  • Conjugate prior for multinomial likelihood (Bayesian convenience)

2008 Election Example

Results of recent state polls in the 2008 United States Presidential Election between Barack Obama and John McCain.

Estimation

Case Study: Emissions of Alpha Particles

  • Berkson (1966) conducted a careful analysis of data obtained from the National Bureau of Standards.
  • The source of the alpha particles was americium 241.
  • n is the number of counts that were observed in 1207 intervals, each of length 10 sec. 
  • In 18 of the 1207 intervals, there were 0, 1, or 2 counts; in 28 of the intervals there were 3 counts, etc.
  n Observed Expected
1 1       18     12.2
2 3       28     27.0
3 4       56     56.5
4 5      105     94.9
5 6      126    132.7
6 7      146    159.1
[1] 0.8354598

Case Study: Emissions of Alpha Particles

To fit a Poisson distribution, we need to estimate its single parameter, λ.

P(X=k)=λke−λk! P(X=k) = \frac{\lambda^k e^{-\lambda}}{k!}

A natural choice for the estimate, λ̂\hat{\lambda}, is the sample mean of the observed counts.

  • Estimate: A value for an unknown parameter based on data.
  • Sampling Distribution: The probability distribution of an estimate if the experiment were repeated. The spread of this distribution indicates the estimate’s variability.

We will explore the rationale for this choice and how to assess its reliability.

Fitting a Poisson Distribution

  • In order to fit the Poisson distribution, we must estimate a value for λ from the observed data.
  • Since the average count in a 10-second interval was 8.352, we take this as an estimate of λ (recall that the E(X) = λ) and denote it by λ̂\hat{\lambda}.

Let’s plot the observed and expected frequencies.

Sampling Distribution of Estimates

  • If the experiment were to be repeated, the counts would be different and the estimate of λ would be different
  • It is thus appropriate to regard the estimate of λ as a random variable which has a probability distribution referred to as its sampling distribution
  • The situation is entirely analogous to tossing a coin 10 times and regarding the number of heads as a binomially distributed random variable

Understanding Variability of Estimates

  • Observing 6 heads in 10 coin tosses generates one realization of a random variable
  • In the same sense, 8.392 is a realization of a random variable
  • Key Question: What is the sampling distribution?
  • This is of practical interest, since the spread of the sampling distribution reflects the variability of the estimate
  • We could ask: to what decimal place is the estimate 8.392 accurate?
  • Later we will discuss the rationale for choosing to estimate λ as we have done

Normal Distribution

Normal Distribution

The density of normal is f(x)=12πσ2e−(x−μ)22σ2 f(x) = \frac{1}{\sqrt{2\pi\sigma^2}} e^{-\frac{(x-\mu)^2}{2\sigma^2}}

The mean and variance of the normal distribution are: E(X)=μ E(X) = \mu

Fit Normal Distribution

Now Plot the histogram and the fitted normal curve.

Parameter Estimation: The Core Idea

  • We treat observed data (x1,x2,…,xnx_1, x_2, \dots, x_n) as realizations of a random variable (X1,X2,…,XnX_1, X_2, \dots, X_n).
  • The joint distribution of these random variables depends on an unknown parameter, θ\theta.
  • Often, we assume the XiX_i are independent and identically distributed (i.i.d.) from a distribution f(x|θ)f(x|\theta).
  • An estimate of θ\theta is a function of the data, and thus is itself a random variable with a sampling distribution.

We will look at two general methods for creating estimates: 1. The Method of Moments 2. The Method of Maximum Likelihood

The Method of Moments

This method equates sample moments with the theoretical moments of the distribution, which are functions of the parameters.

Procedure:

  1. Calculate the first few theoretical moments of the distribution, E(Xk)E(X^k), in terms of the parameters.
  2. Express the parameters as functions of these moments.
  3. Replace the theoretical moments with the sample moments, μ̂k=1n∑i=1nXik\hat{\mu}_k = \frac{1}{n}\sum_{i=1}^n X_i^k, to get the estimates.

Method of Moments: Poisson Example

For a Poisson distribution, the first theoretical moment is the mean: E(X)=λ E(X) = \lambda

The first sample moment is the sample mean: μ̂1=X‾ \hat{\mu}_1 = \bar{X}

Equating them gives the method of moments estimate for λ: λ̂=X‾ \hat{\lambda} = \bar{X}

This is precisely what was done in the alpha particle example.

Method of Moments: Normal Distribution

For a Normal distribution, the first two theoretical moments are: E(X)=μE(X) = \mu E(X2)=μ2+σ2E(X^2) = \mu^2 + \sigma^2 Solving for the parameters gives: μ=E(X)\mu = E(X) σ2=E(X2)−[E(X)]2\sigma^2 = E(X^2) - [E(X)]^2 The method of moments estimates are found by replacing theoretical moments with sample moments: μ̂=X‾\hat{\mu} = \bar{X} σ̂2=1n∑i=1nXi2−X‾2=1n∑i=1n(Xi−X‾)2\hat{\sigma}^2 = \frac{1}{n}\sum_{i=1}^n X_i^2 - \bar{X}^2 = \frac{1}{n}\sum_{i=1}^n (X_i - \bar{X})^2

Method of Moments: Body Temperature Example

Let’s fit a normal distribution to human body temperature data. We’ll use the method of moments to estimate μ and σ and visualize the fit.

[1] "Estimated mu: 98.25"
[1] "Estimated sigma: 0.73"

Error = bias + variance

An estimate is wrong for two reasons.

  • Bias: even with infinite data you are pointed at the wrong place. E(θ̂)−θE(\hat\theta)-\theta does not go to zero.
  • Variance: a new sample would move the answer. That is the sampling distribution we just discussed.
  • Expected squared error splits: MSE(θ̂)=Bias(θ̂)2+Var(θ̂)\mathrm{MSE}(\hat\theta)=\mathrm{Bias}(\hat\theta)^2+\mathrm{Var}(\hat\theta)
  • The course will spend weeks on the second term. In the data you actually meet, the first term is usually the one that matters.

Low/high bias vs low/high variance

Courses teach variance. Life is bias.

  • Variance dies like 1/n1/\sqrt{n}. Bias does not.
  • Ten times the sample, a third the noise. The systematic miss is still there.

Internet-scale nn makes the blue line vanish.

  • The orange line is the error that is left.
  • A tight interval around the wrong number is not a good estimate.
  • Week 10 is the other bias-variance: model complexity. This one is the data.

Biased data

  • The sample is not the population you will decide for. More rows of the same kind do not fix that.
  • Who answered, who clicked, who left a review, who got scraped into the training set.
  • Literary Digest, 1936: two million replies, Landon by a landslide. Roosevelt won. The list was phone books and car registrations.
  • App-store stars, Twitter as “the public,” click-through as “what people want.”
  • The instrument is off. The labeler is tired. You measured the easy cases. Wald: you only see the planes that came back.
  • Write the sentence: how did a row get here? If you cannot, you do not know what θ̂\hat\theta is estimating.

How to detect it

  • Bias does not announce itself as a wide interval. The interval is often tiny.
  • Compare margins to something you trust: a census, an administrative file, a small paid panel, last year’s audited count.
  • Split by source, week, device, geography. If the answer moves, a group is missing or over-weighted.
  • A number that cannot be: turnout over 100%, a mean that the mechanism cannot produce.
  • Add more of the same data. If the estimate does not move and you still doubt the story, that is bias, not precision.
  • Ask who is absent. The missing rows are the bias.
  • Variance you see by resampling. Bias you see by changing who is in the sample.

How to treat it

  • You cannot average it away. Do not buy a larger pull from the same hose.
  • Get the missing group, or narrow the claim to the population you actually have.
  • Reweight only when you know who is missing and by how much. Otherwise you are inventing a census.
  • Measure the same thing another way: a different instrument, a different window, a designed sample.
  • If the decision needs an unbiased number, design the data. A survey with a frame. An experiment. A smaller honest sample beats a large biased one.
  • Report the selection story with the number. A correct figure with the wrong population is still a wrong answer.

Case: Women’s Health Initiative

  • Hormone replacement was supposed to protect the heart.
  • Observational cohorts, including the Nurses’ Health Study, found that women on estrogen had about a third the coronary disease of women who were not.
  • Guidelines followed. By 2001 about 15 million women a year were filling prescriptions.
  • The rows were women who had chosen the pill: they also exercised, kept appointments, had money. A tight interval around the wrong θ̂\hat\theta.

WHI: how they treated it

  • They treated the bias by changing who is in the sample.
  • They did not buy a larger observational pull, and they did not reweight it until they knew who starts and who stays on the drug.
  • Randomized 16,608 postmenopausal women to estrogen plus progestin or placebo. Stopped early.
  • Coronary disease went up, about 29 percent, not down.
  • Later new-user analyses of the observational sample move toward the trial, but only after the mechanism is named.
  • Read Shrank, Patrick, and Brookhart, JGIM 2011 (open). The trial is Rossouw et al., JAMA 2002. Catalog of Bias: healthy users.

How many calls finished in time?

  • Eight calls took (in seconds) 0.4,0.6,0.9,1.1,1.5,1.8,2.4,3.10.4,\ 0.6,\ 0.9,\ 1.1,\ 1.5,\ 1.8,\ 2.4,\ 3.1

  • The timeout is 2 seconds.

  • What share finished in time?

P(X≤2)=F(2)=68=0.75P(X\le 2) = F(2)=\frac{6}{8}=0.75

This is an empirical CDF!

Cumulative Distribution Function (CDF)

F(x)=P(X≤x)F(x)=P(X\leq x)

  • For the eight times, F(2)F(2) is the share at most 2 seconds. For the next call, F(2)F(2) is a probability, and the eight counts are one estimate of it.

  • A later time cannot have a smaller accumulated probability: if a≤ba\leq b, then F(a)≤F(b)F(a)\leq F(b).

For a fair die, what are F(2)F(2) and F(4)F(4)? What event has probability F(4)−F(2)F(4)-F(2)?

What if we had a model?

Empirical step from the eight call times, and a Uniform(0,4) model

The blue step is the sample. The orange ramp is the model X∼U(0,4)X\sim U(0,4). At 2 seconds the sample says 0.750.75 and the model says 0.500.50. Under the model, F(2)=1/2F(2)=1/2 and P(X=2)=0P(X=2)=0, because a single instant has no length.

Which number would you trust for the next call?

0.75 0.5

Example: a fair die

Fair-die CDF with jumps at one through six

Each face has probability 1/61/6, so FF jumps 1/61/6 at 1,2,…,61,2,\ldots,6.

F(2)=2/6F(2)=2/6, F(4)=4/6F(4)=4/6, and F(4)−F(2)=2/6F(4)-F(2)=2/6 is the event 2<X≤42<X\leq 4.

Does that interval include a 2? The jump at 2 is in F(2)F(2), not in the difference.

Example: Uniform Distribution CDF

For uniform distribution on [0,1][0,1] with PDF: f(x)={1if 0≤x≤10otherwise f(x) = \begin{cases} 1 & \text{if } 0 \leq x \leq 1 \\ 0 & \text{otherwise} \end{cases}

The CDF is: F(x)={0if x<0xif 0≤x≤11if x>1 F(x) = \begin{cases} 0 & \text{if } x < 0 \\ x & \text{if } 0 \leq x \leq 1 \\ 1 & \text{if } x > 1 \end{cases}

CDF of uniform distribution

CDF of normal distribution

Applications of CDF

1. Probability Calculations:

  • P(X≤a)=F(a)P(X \leq a) = F(a)
  • P(X>a)=1−F(a)P(X > a) = 1 - F(a)
  • P(a<X≤b)=F(b)−F(a)P(a < X \leq b) = F(b) - F(a)

Normal CDF: Practical Applications

1. Probability Calculations: P(a<X<b)=Φ(b−μσ)−Φ(a−μσ)P(a < X < b) = \Phi\left(\frac{b-\mu}{\sigma}\right) - \Phi\left(\frac{a-\mu}{\sigma}\right)

2. Confidence Intervals:

  • 68% of data within μ±σ\mu \pm \sigma (between -1 and 1 standard deviations)
  • 95% of data within μ±1.96σ\mu \pm 1.96\sigma
  • 99% of data within μ±2.58σ\mu \pm 2.58\sigma

3. Quality Control:

  • Process capability indices
  • Control chart limits
  • Defect rate calculations

Example: SAT Scores

SAT scores are approximately N(1000,2002)N(1000, 200^2). The green band is one standard deviation around the mean, P(800<SAT<1200)≈0.683P(800 < \mathrm{SAT} < 1200) \approx 0.683. The red tail is P(SAT>1200)≈0.159P(\mathrm{SAT} > 1200) \approx 0.159.

Normal model for SAT scores

Normal CDF in R

Key R functions for Normal CDF:

Code
# Standard normal CDF
pnorm(1.96)  # Φ(1.96) ≈ 0.975
[1] 0.9750021
Code
# General normal CDF
pnorm(1200, mean = 1000, sd = 200)  # P(X ≤ 1200)
[1] 0.8413447
Code
# Two-sided probabilities
pnorm(1.96) - pnorm(-1.96)  # P(-1.96 < Z < 1.96) ≈ 0.95
[1] 0.9500042

Standard Normal CDF Properties

Key Properties of Φ(z)\Phi(z):

  • Φ(0)=0.5\Phi(0) = 0.5 (median at origin)
  • Φ(−z)=1−Φ(z)\Phi(-z) = 1 - \Phi(z) (symmetry)
  • Φ(1.96)≈0.975\Phi(1.96) \approx 0.975 (97.5th percentile, so ±1.96\pm 1.96 holds the middle 95%)
  • Φ(2.58)≈0.995\Phi(2.58) \approx 0.995 (99.5th percentile)

Standard Normal CDF with key values highlighted

The quantile

  • The next call has X∼U(0,4)X\sim U(0,4) seconds, so F(x)=x/4F(x)=x/4 on [0,4][0,4].

  • The 0.90.9 quantile is 3.63.6 seconds, the smallest time that keeps 90% of the calls.

  • In general, qu=inf{x:F(x)≥u}q_u=\inf\{x:F(x)\geq u\}.

Inverse CDF Method

That same quantile is a draw. Write quq_u as Q(u)Q(u), the inverse of FF. Take U∼Uniform(0,1)U\sim\mathrm{Uniform}(0,1) and set X=Q(U)X=Q(U). Then XX has CDF FF.

For the call model, Q(u)=4uQ(u)=4u. The draw U=0.9U=0.9 returns the 3.63.6 seconds already computed.

The same step works for any distribution whose quantile you can compute, and it returns an exact sample from FF.

Quantile Function in R: Examples

R function: qnorm() for the normal distribution (and q* for other distributions)

Code
qnorm(0.975)  # 97.5th percentile of standard normal
[1] 1.959964
Code
qnorm(0.95, mean = 1000, sd = 200)  # 95th percentile of N(1000, 200²)
[1] 1328.971
Code
curve(qnorm(x), from = 0, to = 1, n = 200,
      xlab = "Probability (p)", ylab = "Quantile Q(p)",
      main = "Quantile Function of Standard Normal (qnorm)")
abline(h = 0, v = 0.5, col = "red", lty = 2)

What we used FF for

  • A probability: the share of calls by 2 seconds, or of die faces up to 4.
  • A quantile: the deadline that keeps 90% of calls.
  • A draw: X=F−1(U)X=F^{-1}(U) is that quantile used as a sample.

The next block uses a sample to choose a model.

The Royal Mint Tradition (12th Century)

  • Pyx: Greek word “pyxis” = small box
  • Purpose: Test quality of minted coins
  • Standards: Weight and purity compliance

Sir Isaac Newton’s Role (1696):

  • Warden then Master of the Mint
  • Rigorous standards enforcement
  • Combated counterfeiting and clipping
  • Introduced milled edges on coins

Pyx Trial: The Statistical Method

The Process:

  1. Select nn coins from each batch
  2. Place in the Pyx box
  3. Calculate mean and variance for each attribute
  4. Compare against legal tolerances

Example: 1 million coins minted, n=100n=100 sample

  • Legal weight tolerance: 0.05 grams
  • True mean: 5.0 grams

Pyx Trial: Multiple Samples

One sample of 100 coins, then the same draw repeated 2000 times. The histogram is the sampling distribution of the mean.

Sample mean: 4.9951 grams

Two thousand Pyx sample means

The red curve is a normal density with the mean and standard deviation of these 2000 sample means.

Likelihood: eight heads, unknown pp

A CDF reads a probability from a known model. Now the tosses are known and pp is not.

Eight heads and two tails give L(p)∝p8(1−p)2.L(p)\propto p^8(1-p)^2.

  • Keep the observations fixed.
  • Change the proposed success probability.
  • Compare the likelihoods, not a new sample at every pp.
[[0.5        0.14551915]
 [0.8        1.        ]
 [0.95       0.24714337]]

Logs make the calculation easier

ℓ(p)=8logp+2log(1−p)\ell(p)=8\log p+2\log(1-p)

ℓ′(p)=8p−21−p\ell'(p)=\frac8p-\frac2{1-p}

  • At the maximum, 8(1−p)=2p8(1-p)=2p, giving p̂=0.8\hat p=0.8.

  • The logarithm preserves the ordering of positive likelihoods.

Same estimate, different information

10 minutes. Estimation notebook, notebooks/p1-estimation.ipynb.

  • Before running: predict the peaks and widths for 8/10 and 80/100.

Open the notebook. Plot both likelihoods, then multiply both counts by another factor.

  • Record what stays fixed and what changes. Explain why the curve alone is not a posterior distribution.

The peak stays at 0.8

Relative likelihood for eight successes and eighty successes

The larger sample distinguishes nearby parameter values more strongly.

The estimate changes across samples

  • Imagine a machine whose true success probability is 0.6.

  • We observe 25 trials and calculate p̂\hat p. Another team repeats the experiment independently.

Must the two estimates agree?

  • The distribution of the estimates across repetitions is a sampling distribution.

Repeating the experiment

35 minutes. Notebook B. Switch the keyboard operator halfway through.

  1. Predict the spread of p̂\hat p for n=25,100,400n=25,100,400.
  2. Simulate repeated samples and compare the spreads.
  3. Change the true probability to 0.05. Inspect the shape.

Explain which uncertainty the histogram measures.

Four times the sample size

Sampling distributions at three sample sizes
  • For one Bernoulli trial, E[Y]=pE[Y]=p and Y2=YY^2=Y, so

Var(Y)=E[Y2]−(E[Y])2=p−p2=p(1−p).\operatorname{Var}(Y)=E[Y^2]-(E[Y])^2=p-p^2=p(1-p).

  • For nn independent trials, p̂\hat p is their average, and

sd(p̂)=p(1−p)n.\operatorname{sd}(\hat p)=\sqrt{\frac{p(1-p)}n}.

  • Four times as many observations halves the standard error.

One click is still a coin flip

The formula has two standard deviations. They answer different questions.

Question, at p=0.6p=0.6 Standard deviation
Will the next click happen? 0.6×0.4≈0.49\sqrt{0.6\times 0.4}\approx 0.49
How far is p̂\hat p from 100 clicks? 0.49/100≈0.0490.49/\sqrt{100}\approx 0.049
  • The second row is the width of the histogram from the activity.
  • A larger nn shrinks that width. It does not make the next click predictable.
25 0.601392 0.09798603133100146
100 0.600142 0.048667852181907514
400 0.6002105000000001 0.024467364789653993

The n=100n=100 spread matches 0.49/1000.49/\sqrt{100}. Four times the sample size, about half the spread.

Central limit theorem

  • The coin-flip slide was the width: sd(p̂)=p(1−p)/n\mathrm{sd}(\hat p)=\sqrt{p(1-p)/n}.
  • The shape is the new fact. An average of many independent draws is approximately normal, even when one draw is not.
  • Four times the sample, about half the width. The next slide is the shape. The square-root law follows the board.
  • Google’s intervals use this approximation. The normal mean, μ̂=y‾\hat\mu=\bar y, comes after.

Galton Board: Physical demonstration of CLT

Galton Board: Physical demonstration of the CLT

Interactive board

  • Each pin = binomial draw
  • Each row = summand
  • Bottom location = sum of binomial draws
Figure 1: Galton Board

One coin per ball

The central limit theorem is not wrong here. Its main assumption, independence, is broken.

  • K=X1+⋯+XnK=X_1+\cdots+X_n looks normal when the bounces are independent, or only weakly dependent.
  • The bell curve is cancellation. Each bounce adds a small error. Some push left and some push right, and the sum of many small independent errors is approximately normal.

Each ball’s randomness has two parts:

K=np+(the flips’ noise around np). K=np+\text{(the flips' noise around }np\text{)}.

  • The noise is a sum of nn independent errors once you know the coin. The theorem works on it, and it grows only like n\sqrt{n}.
  • The npnp term is one draw, the coin, made once per ball. Nothing cancels it. It is either 0.5n0.5n or 0.8n0.8n, and it grows like nn.

As nn grows, the npnp part dominates. K/nK/n does not settle at 0.590.59. It settles at that ball’s own coin, 0.50.5 or 0.80.8. The limit of the standardized KK is a two-point distribution, not N(0,1)N(0,1). The picture is two bells, because the theorem still works inside each coin, at a location chosen by one coin draw.

A shared coin does not average away

Every pair of bounces from the same ball is correlated through the shared coin: Cov(Xi,Xj)=Var(p)\mathrm{Cov}(X_i,X_j)=\mathrm{Var}(p). That correlation does not shrink with the distance between the rows, so

Var(K)=np‾(1−p‾)[1+(n−1)ρ]. \mathrm{Var}(K)=n\bar p(1-\bar p)\bigl[1+(n-1)\rho\bigr].

  • For independent bounces the bracket is 11. Here it grows without bound, which is where the theorem’s hypotheses fail.
  • The nn correlated bounces are worth only

neff=n1+(n−1)ρ→1ρas n→∞. n_{\mathrm{eff}}=\frac{n}{1+(n-1)\rho}\to\frac{1}{\rho}\quad\text{as }n\to\infty.

  • With these settings, ρ≈0.078\rho\approx 0.078, so the board behaves like about 1313 independent flips no matter how many rows you add. With coins 0.70.7 and 0.50.5, the ceiling is about 2929. Rows past that ceiling only repeat the same coin draw.
  • Pick the coin at each peg and each bounce is a fresh independent Bernoulli(p‾\bar p) draw. Then ρ=0\rho=0, neff=nn_{\mathrm{eff}}=n, and the theorem applies.

Averaging removes noise that is independent from one observation to the next. It cannot remove a factor every observation shares, and with a shared coin that factor sets the shape.

The Fundamental Relationship

Standard Error decreases with n\sqrt{n}: sx‾=sns_{\bar x} = \frac{s}{\sqrt{n}}

This means: To halve uncertainty, you need to quadruple sample size!

The Math:

  • Variance of mean: Var(X‾)=σ2n\mathrm{Var}(\bar X) = \frac{\sigma^2}{n}
  • Standard error: sx‾=sns_{\bar x} = \frac{s}{\sqrt{n}}
  • Confidence interval width: 2×sn2 \times \frac{s}{\sqrt{n}}

Practical Implications:

  • Sample size 100 → Standard error = s/10s/10
  • Sample size 400 → Standard error = s/20s/20 (half the uncertainty)
  • Sample size 1600 → Standard error = s/40s/40 (quarter the uncertainty)

Variance Decay: Visual Demonstration

Key Insight: The relationship is logarithmic - each doubling of sample size reduces uncertainty by 2≈1.41\sqrt{2} \approx 1.41

Variance Decay: Real-World Example

Scenario: Quality control for coin weights

  • Population standard deviation: s=0.1s = 0.1 grams
  • Target: 95% confidence interval width ≤ 0.02 grams

Required sample sizes:

Required sample size: 385 
This gives CI width: 0.02 grams

CI width changes with sample size


CI widths for different sample sizes:
n = 100 → CI width = 0.0392 grams
n = 400 → CI width = 0.0196 grams
n = 1600 → CI width = 0.0098 grams
n = 6400 → CI width = 0.0049 grams

The Cost of Precision: - To get 4x more precise (0.08 → 0.02 grams), need 16× more data! - This is why large-scale experiments are expensive but necessary

Android Earthquake Alerts: CLT in Action

The Challenge:

  • Individual phone accelerometers are “noisy sensors”
  • Single phone signal = weak, unreliable
  • Many false triggers (drops, trucks, music)

The Solution:

  • Aggregate signals from millions of phones
  • Real earthquakes: synchronized vibrations
  • Random noise cancels out through averaging

The Math: sx‾=s/ns_{\bar x} = s/\sqrt{n} where nn = number of phones With massive nn, standard error becomes incredibly small!

Google: Algo 1 vs Algo 2

Search requests are assigned at random to the current algorithm or a new one. Success is a click on a result. 2500 requests each.

Algo 1 Algo 2
Success 1755 1818
Failure 745 682
Total 2500 2500
  • p̂1=1755/2500=0.702\hat p_1=1755/2500=0.702
  • p̂2=1818/2500=0.727\hat p_2=1818/2500=0.727

Google: do the intervals separate?

The same standard error, p̂(1−p̂)/n\sqrt{\hat p(1-\hat p)/n}, for each click rate and for their difference.

0.702 0.7272
(0.6840707239008375, 0.7199292760991625)
(0.7097403640054438, 0.7446596359945561)
(-0.05022594314910829, -0.00017405685089171008)
  • p̂2=1818/2500=0.7272\hat p_2=1818/2500=0.7272, not the rounded 0.7270.727.
  • Algo 1: [0.684,0.720][0.684, 0.720]. Algo 2: [0.710,0.745][0.710, 0.745].
  • Difference p1−p2p_1-p_2: [−0.050,−0.0002][-0.050, -0.0002]. Zero is outside.
  • With p2p_2 rounded to 0.7270.727, that upper end is about +0.00003+0.00003 and zero sneaks back in.
  • Random assignment is why a 2.5 point gap is worth talking about. A million voluntary replies would not be.

A million replies, the wrong people

You just watched an interval miss zero by 0.00020.0002. That gap was earned by random assignment.

  • Literary Digest, 1936, mailed ten million ballots and got two million back. Landon by a landslide. Roosevelt won.
  • The names came from phone books and car registrations. Another million of those names would have made the interval smaller and the forecast no better.
  • Before you read the width, write who could not get into the sample.

A narrow interval means the sample agreed with itself. It does not mean the sample was the population.

The normal log-likelihood

Independent observations, one unknown mean, variance held fixed:

Yi∼N(μ,σ2). Y_i \sim N(\mu,\sigma^2).

The log-likelihood is the sum of the log densities:

ℓ(μ)=−n2log(2πσ2)−12σ2∑i=1n(yi−μ)2. \ell(\mu) = -\frac{n}{2}\log(2\pi\sigma^2) - \frac{1}{2\sigma^2}\sum_{i=1}^n (y_i-\mu)^2.

  • Only the sum of squares depends on μ\mu.
  • σ2\sigma^2 is a positive constant here. It moves the height of the curve, not the location of the peak.

The log-likelihood has one peak

  • Five numbers. σ\sigma fixed at 1.51.5.
  • The curve rises, peaks, and falls. We have not yet named the peak.

Set the derivative to zero

Differentiate the sum of squares. The constant terms drop out.

∂ℓ∂μ=1σ2∑i=1n(yi−μ). \frac{\partial\ell}{\partial\mu} = \frac{1}{\sigma^2}\sum_{i=1}^n (y_i-\mu).

Set that to zero. σ2>0\sigma^2>0, so

∑i=1n(yi−μ)=0⇒μ̂=y‾. \sum_{i=1}^n (y_i-\mu)=0 \qquad\Rightarrow\qquad \hat\mu=\bar y.

  • The peak in the plot is the average of 2,3,3,6,62,3,3,6,6, which is 44.
  • Same μ̂\hat\mu for every σ2>0\sigma^2>0. The variance changes the curvature, not the maximizer.

Example: MLE for Normal Mean with Real Data

Dataset: SAT score for 1000 students

MLE Estimation

Maximum Likelihood Estimates for Normal Distribution
Parameter Value
μ (mean) 103.33
σ² (variance) 203.92
σ (std dev) 14.28
n (sample size) 1000.00

Draw bell curve on top of histogram

Use Optimization to find MLE

Code
# Define negative log-likelihood function
neg_log_likelihood <- function(params, data) {
  mu <- params[1]
  sigma <- params[2]
  
  # Ensure sigma is positive
  if (sigma <= 0) return(Inf)
  
  # Calculate negative log-likelihood
  n <- length(data)
  -sum(dnorm(data, mean = mu, sd = sigma, log = TRUE))
}

# Optimize using built-in optimizer
result <- optim(c(50, 10), neg_log_likelihood, data = sat$sat_sum)
mu_optim <- result$par[1]
sigma_optim <- result$par[2]

# Create results table for optimization
optim_table <- data.frame(
  Parameter = c("μ", "σ"),
  Analytical = c(round(mu_mle, 2), round(sigma_mle, 2)),
  Optimized = c(round(mu_optim, 2), round(sigma_optim, 2)),
  Difference = c(round(abs(mu_mle - mu_optim), 6), round(abs(sigma_mle - sigma_optim), 6))
)
kable(optim_table, caption = "Comparison of Analytical vs Numerical Optimization Results")
Comparison of Analytical vs Numerical Optimization Results
Parameter Analytical Optimized Difference
μ 103.33 103.33 0.000542
σ 14.28 14.28 0.002433

Likelihood Function Visualization

Log-likelihood surface for different values of μ

Confidence Interval for μ

Code
# 95% confidence interval for μ
alpha <- 0.05
z_critical <- qnorm(1 - alpha/2)
se_mu <- sigma_mle / sqrt(n)
ci_lower <- mu_mle - z_critical * se_mu
ci_upper <- mu_mle + z_critical * se_mu

cat("95% Confidence Interval for μ:\n")
95% Confidence Interval for μ:
Code
cat("Lower bound:", round(ci_lower, 2))
Lower bound: 102.44
Code
cat("Upper bound:", round(ci_upper, 2))
Upper bound: 104.21
Code
cat("Margin of error:", round(z_critical * se_mu, 2))
Margin of error: 0.89

MLE: Poisson Example

For an i.i.d. sample X1,…,XnX_1, \dots, X_n from a Poisson(λ) distribution, the log-likelihood is: l(λ)=∑i=1nln(λXie−λXi!)=(lnλ)∑Xi−nλ−∑ln(Xi!) l(\lambda) = \sum_{i=1}^n \ln\left(\frac{\lambda^{X_i} e^{-\lambda}}{X_i!}\right) = (\ln \lambda) \sum X_i - n\lambda - \sum \ln(X_i!)

To find the maximum, we take the derivative with respect to λ and set it to zero: dldλ=1λ∑Xi−n=0 \frac{dl}{d\lambda} = \frac{1}{\lambda}\sum X_i - n = 0 ⟹λ̂MLE=∑Xin=X‾ \implies \hat{\lambda}_{MLE} = \frac{\sum X_i}{n} = \bar{X}

For the Poisson distribution, the Method of Moments and the Maximum Likelihood estimates are the same.

Gamma distribution

A law for a positive number: a waiting time, a rainfall amount, a claim size.

  • Shape α>0\alpha>0 is how many Poisson events you are waiting for.
  • Scale λ>0\lambda>0 stretches the clock. Mean αλ\alpha\lambda, variance αλ2\alpha\lambda^2.
  • α=1\alpha=1 is the exponential distribution: time until the first event.
  • An integer α=k\alpha=k is the time until the kk-th event in a Poisson process. f(x)=1Γ(α)λαxα−1e−x/λ,x>0. f(x)=\frac{1}{\Gamma(\alpha)\lambda^\alpha}x^{\alpha-1}e^{-x/\lambda},\qquad x>0.

Three gamma shapes

Same scale, three shapes. Shape 1 piles up at zero. Larger shape moves the mass to the right and makes a hump.

Where a gamma is the model

  • Time until the kk-th arrival: customers, decays, packets. k=1k=1 is the red curve.
  • A size with no natural ceiling and a long right tail: insurance claims, daily rainfall.
  • Service time in a queue, or time until recovery, when the histogram looks like the blue curve rather than a bell.
  • The next fit is inter-arrival times of gamma rays. Those are waiting times.
  • The fit writes the same law with a rate, 1/λ1/\lambda. R’s dgamma(..., rate = ) is that form. The curve does not change.

MLE: Gamma Distribution Example

For the Gamma distribution, the log-likelihood is: l(α,λ)=nαln(λ)−nln(Γ(α))+(α−1)∑ln(Xi)−λ∑Xil(\alpha, \lambda) = n\alpha\ln(\lambda) - n\ln(\Gamma(\alpha)) + (\alpha-1)\sum\ln(X_i) - \lambda\sum X_i The MLEs for α and λ don’t have a simple closed-form solution and must be found numerically by maximizing this function.

Let’s fit a Gamma distribution to the inter-arrival times of gamma-rays.

MLE: Gamma Distribution Example

[1] "MLE for alpha: 1.0263"
[1] "MLE for lambda: 0.0128"

Negative binomial

A law for a count, like the Poisson, with one extra fact: the variance is larger than the mean.

  • Keep tossing a coin until you have rr successes. XX is the number of failures along the way.
  • Mean μ=r(1−p)/p\mu=r(1-p)/p. Variance μ+μ2/r\mu+\mu^2/r, which is always bigger than μ\mu.
  • A Poisson count has variance equal to its mean. The negative binomial is what you get when that rate is itself random, drawn from the gamma on the last slides.
  • Large rr pulls the extra term μ2/r\mu^2/r toward zero, and the law collapses back to the Poisson.

Same mean, more spread

Mean fixed at 4. The Poisson is the narrowest. Small rr puts more mass at zero and a longer right tail.

Where a negative binomial is the model

  • Insects on a plant, visits to a clinic, claims on a policy: many zeros, and a few units with a huge count.
  • The Poisson fit is too tight there. The sample variance is larger than the sample mean, and the gamma mixture is the reason.
  • The next fit is potato beetles per plant. rr and the mean are found numerically. There is no closed form, same as the gamma.

MLE: Negative Binomial Example

Potato beetles per plant. The count is the negative binomial from the last slides.

[1] "MLE for r (size): 2.24"
[1] "MLE for mean (mu): 4.7"

Prediction Problems:

Output Type Problem Type Example
Binary Classification Spam detection
Categorical Classification Content categorization
Quantitative Regression House prices
Ordinal Ranking Customer satisfaction

The mean can depend on an input

  • For a Gaussian model with fixed variance,

−ℓ(μ)=12σ2∑i(yi−μi)2+C.-\ell(\mu)=\frac1{2\sigma^2}\sum_i(y_i-\mu_i)^2+C.

  • The best-fitting mean minimizes squared deviations.

μi=axi+b.\mu_i=ax_i+b.

Averages within groups, then across groups

A quarter of the houses are small, and their average price is 2. The other three quarters are large, and their average price is 6. Prices are in the same thousands of dollars as the next slide.

  • Ignore size, and the one number you can report is 0.25×2+0.75×6=5.0.25\times 2+0.75\times 6=5.
  • Keep size, and you report 2 for a small house and 6 for a large one.
  • The line on the next slide is that second average, with living area in place of the two groups.

How Does Zestimate Work?

Original Saratoga housing data, fitted line, and 2200 square foot prediction

Saratoga house prices

  • 1,728 sales in the supplied file.
  • ŷ=13.44+113.12x\hat y=13.44+113.12x.
  • xx: thousands of square feet of living area.
  • yy: thousands of dollars.

What does the slope say at 2,200 square feet?

[ 13.439394   113.12254185] 262.30898606787036

Housing Data Visualization

For Saratoga use the revised 1,728-row fit. Its intercept is extrapolation, not an identified land value.

House prices vs living area in Saratoga County

Fitting the Linear Model

Linear regression line fitted to housing data

R Code Explanation:

  • lm(): Fits linear model using least squares
  • price ~ livingArea: Formula notation (dependent ~ independent)
  • abline(): Adds regression line to plot

Original saved output: Fitting the Linear Model

Model Coefficients

For Saratoga use the revised 1,728-row fit. Its intercept is extrapolation, not an identified land value.

(Intercept)  livingArea 
   13.43939   113.12254 

Interpretation:

  • Intercept (β0\beta_0): Fitted value at zero living area, an extrapolation
  • Slope (β1\beta_1): Price increase per 1000 sq ft
  • Economic significance: Every additional 1000 sq ft increases price by β1×$1000\beta_1 \times \$1000

Making Predictions

Example: Predict price for 2,200 sq ft house

ŷ=β0+β1×2.2\hat{y} = \beta_0 + \beta_1 \times 2.2

Prediction visualization for 2,200 sq ft house

Original saved output: Making Predictions

Apply to housing data

For Saratoga use the revised 1,728-row fit. Its intercept is extrapolation, not an identified land value.

mle mle_optim
(Intercept) 13.44 13.44 13.40
livingArea 113.12 113.12 113.14

One prediction for everyone?

The three observations used in the hand calculation
  • Would you predict the same value at every xx?
  • Sketch a rule.
  • Which point will a straight line miss?

A curve through every point is easy. Would you trust it at x=4x=4?

Residuals keep the units of the response

Residuals as vertical distances from the candidate line

ei=yi−ŷie_i=y_i-\hat y_i

  • Candidate line: ŷ=1+x\hat y=1+x.
  • At x=1x=1, observed y=3y=3.
  • Prediction: 2.
  • Residual: +1.

Would a negative residual sit above or below the line?

A loss for choosing the line

  • We use the same convention throughout this calculation:

J(a,b)=12n∑i(a+bxi−yi)2.J(a,b)=\frac1{2n}\sum_i(a+bx_i-y_i)^2.

  • Squaring prevents positive and negative errors from canceling.

  • The factor 1/(2n)1/(2n) simplifies the gradient. It does not change the minimizing line.

Why squared deviations appear

  • The constant-mean case is the previous derivation: μ̂=y‾\hat\mu=\bar y.
  • With a line, assume independent responses

Yi∣xi∼N(a+bxi,σ2).Y_i\mid x_i\sim N(a+bx_i,\sigma^2).

  • For fixed σ2\sigma^2,

−ℓ(a,b)=12σ2∑i(yi−a−bxi)2+C.-\ell(a,b)=\frac1{2\sigma^2}\sum_i(y_i-a-bx_i)^2+C.

  • Maximizing this likelihood gives the least-squares line. The same sum of squares, now in aa and bb.

Least squares slope and intercept

b̂=∑i(xi−x‾)(yi−y‾)∑i(xi−x‾)2,â=y‾−b̂x‾.\hat b=\frac{\sum_i(x_i-\bar x)(y_i-\bar y)}{\sum_i(x_i-\bar x)^2},\qquad \hat a=\bar y-\hat b\,\bar x.

  • The numerator pairs each point’s deviation in xx with its deviation in yy.
  • The denominator is the sum of the squared deviations in xx. A point far from x‾\bar x gets a large vote.
  • The intercept puts the line through the point of averages, (x‾,y‾)(\bar x,\bar y).
  • â\hat a is the predicted yy at x=0x=0. If the data are nowhere near zero, that prediction is an extrapolation.

Variance of a new prediction

A new outcome at a chosen xx is the fitted line plus a fresh error. The line is estimated from the sample, so both pieces vary. Here ss is the residual standard deviation.

Var=s2(1+1n+(x−x‾)2∑i(xi−x‾)2).\operatorname{Var}=s^2\left(1+\frac1n+\frac{(x-\bar x)^2}{\sum_i(x_i-\bar x)^2}\right).

  • The 11 is the new error. It does not shrink as nn grows.
  • 1/n1/n is uncertainty in the height of the line.
  • The last term grows as xx moves away from x‾\bar x. The same denominator as in the slope.
  • A band for the mean line drops the 11. A band for one new outcome keeps it.

Predictions as a matrix product

X=(101112),θ=(11),Xθ=(123)X=\begin{pmatrix}1&0\\1&1\\1&2\end{pmatrix}, \qquad\theta=\begin{pmatrix}1\\1\end{pmatrix}, \qquad X\theta=\begin{pmatrix}1\\2\\3\end{pmatrix}

[1. 2. 3.]
  • One row produces one prediction.
  • The column of ones supplies the intercept.

Which array operation do you mean?

  • With X.shape == (3, 2) and theta.shape == (2,):
NumPy expression Meaning Shape
X @ theta Three dot products (3,)
X * theta Elementwise scaling of columns (3, 2)
X.T Transpose (2, 3)
theta[:, None] Explicit column (2, 1)
  • Predict the output shape before running each line. A one-dimensional array’s .T does not make it a column.

When coefficients cannot be distinguished

  • If two columns of XX are identical, only the sum of their coefficients affects XθX\theta.

  • Adding 1 to one coefficient and subtracting 1 from the other leaves every prediction unchanged.

  • Linear dependence can make the coefficients non-unique. We can still ask about predictions and the loss.

A derivative is local sensitivity

  • For a small change δ\delta,

J(θ+δ)≈J(θ)+∇J(θ)⊤δ.J(\theta+\delta)\approx J(\theta)+\nabla J(\theta)^\top\delta.

  • A partial derivative changes one parameter while holding the others fixed.

  • Compare an analytic derivative with central finite differences:

J(θ+ϵej)−J(θ−ϵej)2ϵ.\frac{J(\theta+\epsilon e_j)-J(\theta-\epsilon e_j)}{2\epsilon}.

A fitted line on a larger sample

A line fitted to simulated curved data and its residuals

Which feature of the residual plot would you investigate?

The experiment’s known mechanism

X∼U(−2,2)X\sim U(-2,2)

Y=1+2X+0.7X2+ϵ,ϵ∼N(0,1)Y=1+2X+0.7X^2+\epsilon,\qquad \epsilon\sim N(0,1)

  • We know the mechanism because we generated these observations.

  • The straight line cannot represent the whole conditional mean.

Curvature and influence

The fitted line before and after changing one response
  • The rightmost response increases by 15.
  • Its large squared error pulls the line.
  • Curvature and an influential observation are different clues.

Which feature of your residual plot supports your explanation?

More examples: the same regression questions

  • The original Tiger Woods example asks why one response can dominate a fit.
  • Mammal brain and body mass asks whether a different scale reveals structure.
  • Compare what changes when the response scale or observation changes.

Tiger Woods: what does the residual mean?

PGA earnings residuals on dollar and log-dollar scales
  • Same 195 golfers and predictors, different response scale.
  • Tiger Woods earns much more than the dollar-scale fit predicts.
  • A log transform changes which errors matter. It does not prove a causal explanation.
Notah Begay III

Golf Performance Prediction

Use the verified 2000 PGA data. Raw coefficient sizes across different units do not rank causal importance. These fits are in-sample diagnostics.

Dave Pelz: From Rocket Scientist to Golf Analytics Pioneer

  • NASA Apollo program engineer turned golf instructor
  • Applied data analytics to revolutionize golf instruction
  • Discovered optimal putt speed: 17 inches past hole if missed
  • Author of Short Game Bible and Putting Bible

Data-Driven Golf Insight: Short game matters most for overall scoring

PGA Tour Performance Analysis

Use the verified 2000 PGA data. Raw coefficient sizes across different units do not rank causal importance. These fits are in-sample diagnostics.

Dataset: 195 professional golfers, 2000 PGA Tour season

Variables:

  • money: Official dollar winnings
  • nevents: Number of official PGA events
  • drivedist: Average driving distance (yards)
  • gir: Greens in regulation (percentage)
  • avgputts: Average putts per round

Goal: Determine which factors most influence tour earnings

Loading and Examining Golf Data

Use the verified 2000 PGA data. Raw coefficient sizes across different units do not rank causal importance. These fits are in-sample diagnostics.

Code
d00 = read.csv("../data/pga-2000.csv")
d18 = read.csv("../data/pga-2018.csv")
Code
library(broom)
library(dplyr, warn.conflicts = FALSE)
model00 = lm(money ~ nevents + drivedist + gir + avgputts, data=d00)
model00 %>% broom::tidy() %>% knitr::kable(digits=2)
term estimate std.error statistic p.value
(Intercept) 14856637.77 4206466.17 3.53 0.00
nevents -30066.53 11183.31 -2.69 0.01
drivedist 21309.72 6912.98 3.08 0.00
gir 120855.16 17429.37 6.93 0.00
avgputts -15203044.72 2000904.79 -7.60 0.00

Residual Analysis: The Tiger Woods Effect

Use the verified 2000 PGA data. Raw coefficient sizes across different units do not rank causal importance. These fits are in-sample diagnostics.

Residual distribution showing extreme outlier

Problem: Extreme outlier suggests need for transformation

Original saved output: Residual Analysis: The Tiger Woods Effect

Log Transformation Improves Model

Use the verified 2000 PGA data. Raw coefficient sizes across different units do not rank causal importance. These fits are in-sample diagnostics.

Code
model00log = lm(log(money) ~ nevents + drivedist + gir + avgputts, data=d00)
model00log %>% broom::tidy() %>% knitr::kable(digits=2)
term estimate std.error statistic p.value
(Intercept) 36.15 3.58 10.10 0.00
nevents -0.01 0.01 -0.94 0.35
drivedist 0.01 0.01 2.40 0.02
gir 0.17 0.01 11.18 0.00
avgputts -21.13 1.70 -12.42 0.00

Improved residual distribution after log transformation

Original saved output: Log Transformation Improves Model

Variable Selection and Final Model

Use the verified 2000 PGA data. Raw coefficient sizes across different units do not rank causal importance. These fits are in-sample diagnostics.

Remove nevents (t-statistic < 1.5, not significant)

Code
m1 = lm(log(money) ~ drivedist + gir + avgputts, data=d00)
m1 %>% broom::tidy() %>% knitr::kable(digits=2)
term estimate std.error statistic p.value
(Intercept) 36.17 3.58 10.11 0.00
drivedist 0.01 0.01 2.50 0.01
gir 0.17 0.01 11.19 0.00
avgputts -21.37 1.68 -12.70 0.00

Key Insights:

  • Putting: Most important factor (highest coefficient magnitude)
  • GIR: β̂=0.17\hat{\beta} = 0.17 → 1% GIR increase = 18% earnings boost
  • Driving: β̂=0.014\hat{\beta} = 0.014 → 10-yard increase = 15% earnings boost

Performance Outliers Analysis

Use the verified 2000 PGA data. Raw coefficient sizes across different units do not rank causal importance. These fits are in-sample diagnostics.

Over-performers (earning more than predicted):

  • Tiger Woods, Phil Mickelson, Ernie Els
  • Won major championships with high prize money
  • Tiger Woods: 9 standard deviations above prediction!

Under-performers (earning less than predicted):

  • Strong technical statistics but lower earnings
  • Possible factors: tournament pressure, event selection, mental game

Practical Application: Model identifies players exceeding/falling short of statistical expectations

Golf Analytics Takeaways

Use the verified 2000 PGA data. Raw coefficient sizes across different units do not rank causal importance. These fits are in-sample diagnostics.

  1. Short game dominance: Putting has greatest impact on earnings
  2. Power advantage: Driving distance provides significant competitive edge
  3. Accuracy matters: Greens in regulation crucial for success
  4. Outlier insights: Model reveals over/under-performers
  5. Data transformation: Log scale better captures exponential earnings distribution

Modern relevance: Analytics-driven approach now standard in professional golf training and strategy

Mammals: a change of scale

The original 62 mammal species on original and log scales
  • The fitted relation is log(Brain)≈2.183+0.743log(Body)\log(\mathrm{Brain})\approx2.183+0.743\log(\mathrm{Body}).
  • Doubling body mass multiplies fitted brain mass by 20.743≈1.672^{0.743}\approx1.67.
  • A large residual is a modeling question, not a measure of intelligence.
2.1832796605662286 0.7431983221963678 1.673882572282309

Case Study: Mammal Brain vs Body Weight

Brain/body residuals do not rank intelligence. Exponentiating a log fit does not automatically estimate the arithmetic conditional mean.

Dataset: 62 mammal species (Jerison, 1973) - Brain weight (grams) - Body weight (kilograms)

Code
mammals = read.csv("../data/mammals.csv")
head(mammals) %>% knitr::kable()
Mammal Brain Body
African_elephant 5712.0 6654.000
African_giant_pouched_rat 6.6 1.000
Arctic_Fox 44.5 3.385
Arctic_ground_squirrel 5.7 0.920
Asian_elephant 4603.0 2547.000
Baboon 179.5 10.550

Question: How does brain size relate to body size across species?

Linear Model: Poor Fit

Linear model shows poor fit with outliers

Problems: Outliers, non-constant variance, poor fit

Original saved output: Linear Model: Poor Fit

Residual Analysis Shows Problems

Residuals show heteroscedasticity

Fitted vs actual shows nonlinearity

Diagnosis: Need transformation to fix model assumptions

Log-Log Transformation: Much Better!

Code
model_log = lm(log(Brain) ~ log(Body), data=mammals)
model_log %>% broom::tidy() %>% knitr::kable(digits=3)
term estimate std.error statistic p.value
(Intercept) 2.183 0.107 20.439 0
log(Body) 0.743 0.032 23.477 0

Model: log(Brain)=2.18+0.74×log(Body)\log(\text{Brain}) = 2.18 + 0.74 \times \log(\text{Body})

Interpretation: - 10% increase in body weight → 7.4% increase in brain weight - Brain weight scales as Body0.74 (allometric scaling)

Improved Residual Diagnostics

Residuals now show constant variance

Strong linear relationship achieved

Diagnostic question: Does the transformed residual plot support a linear mean and roughly constant spread?

Outlier analysis: mammal brain/body residuals

Brain/body residuals do not rank intelligence. Exponentiating a log fit does not automatically estimate the arithmetic conditional mean.

Code
res = model_log$residuals/sd(model_log$residuals)
outliers = base::order(res, decreasing = TRUE)[1:5]
cbind(mammals[outliers,],
      Std.Res = res[outliers], Residual=model_log$residuals[outliers],
      Fit = exp(model_log$fitted.values[outliers])) %>% knitr::kable(digits=2)
Mammal Brain Body Std.Res Residual Fit
11 Chinchilla 64.0 0.42 3.41 2.61 4.70
34 Man 1320.0 62.00 2.53 1.93 190.67
50 Rhesus_monkey 179.0 6.80 2.06 1.58 36.89
6 Baboon 179.5 10.55 1.64 1.26 51.13
42 Owl_monkey 15.5 0.48 1.44 1.10 5.14

Key Finding: Humans and some small mammals have disproportionately large brains!

Dummy Variables

A 1/0 column standing in for a yes/no feature. The intercept is the mean when that column is 0. The coefficient is how the mean shifts when it is 1. “Has a garage” is this: one column.

A factor with more than two levels is the same idea, repeated.

Dummy Variables: kk levels, k−1k-1 columns

Neighborhood is A, B, or C. You cannot put {A,B,C}\{A, B, C\} into a sum. You make two columns and omit A as the reference:

House IBI_B ICI_C
A 0 0
B 1 0
C 0 1

The intercept is the mean for A. The coefficient on IBI_B is how B differs from A. Four neighborhoods would be three columns.

Dummy Variables: the reference is a choice

R’s lm drops the first level of a factor. factor(nbhd, levels = c("A","B","C")) makes A the reference. That is a modeling decision, not a default to ignore.

If you want “typical house” as the baseline, put that level first. If you change the reference, every coefficient changes and the fitted values do not.

Simple Predictive Rules

Mean Rule: f(x)=y‾=1n∑i=1nyif(x) = \bar{y} = \frac{1}{n} \sum_{i=1}^n y_i

Binary Classification (Thresholding): f(x)={1if y‾>0.50if y‾≤0.5f(x) = \begin{cases} 1 & \text{if } \bar{y} > 0.5 \\ 0 & \text{if } \bar{y} \leq 0.5 \end{cases}

Nearest Neighbor Rule: f(x)=yi*,where i*=argmini=1,…,n∥xi−x∥f(x) = y_{i^*}, \quad \text{where } i^* = \arg\min_{i=1,\ldots,n} \|x_i - x\|

Trade-off: Mean rule (high bias, low variance) vs NN rule (low bias, high variance)

Logarithmic and Power Transformations

Problem: Not all relationships are linear!

  • Linear models assume: y=β0+β1xy = \beta_0 + \beta_1 x
  • Reality: Many relationships are multiplicative or exponential
  • Solution: Transform variables to linearize relationships
  • Key insight: Linear regression on transformed data

Examples: Stock prices, population growth, brain-body relationships

When Linear Models Fail: Apple Stock Growth

Apple Stock (2000-2024): Exponential growth pattern

[1] "AAPL"

Apple stock shows exponential growth over time

Observation: Linear model would be poor fit for exponential growth

Original saved output: When Linear Models Fail: Apple Stock Growth

Linear Model vs Exponential Growth

Linear model fails to capture exponential growth

Problem: Straight line cannot capture curved relationship

Original saved output: Linear Model vs Exponential Growth

The Mathematics of Compounding

Compounding Formula: y=y0×(1+r/n)nty = y_0 \times (1 + r/n)^{nt}

Example: $1,000 investment at 10% annual rate - Annual compounding: y=1000×(1.1)1=$1,100y = 1000 \times (1.1)^1 = \$1,100 - Monthly compounding: y=1000×(1+0.1/12)12=$1,105y = 1000 \times (1 + 0.1/12)^{12} = \$1,105

Extreme example: 0.1% daily compounding for 4 years y=1000×(1+0.001)4×365=$20,380,072,410y = 1000 \times (1 + 0.001)^{4 \times 365} = \$20,380,072,410

Euler’s Number and Continuous Compounding

Compound growth approaches e^r as frequency increases

Key Limit: (1+r/n)n→er(1+r/n)^n \rightarrow e^r as n→∞n \rightarrow \infty

Original saved output: Euler’s Number and Continuous Compounding

Exponential Models and Log Transformation

Exponential Growth Model: y=y0×eβTxy = y_0 \times e^{\beta^T x}

Log Transformation: logy=logy0+βTx\log y = \log y_0 + \beta^T x

  • Multiplicative relationships become additive
  • Exponential curves become linear
  • Can use standard linear regression on transformed data
  • Interpretation: Coefficients represent percentage changes

Power Law Relationships

Power Law Model: y=β0xβ1y = \beta_0 x^{\beta_1}

Examples:

  • City size vs. number of cars
  • Metabolic rate vs. body mass
  • Website traffic vs. page rank

Log-Log Transformation: logy=logβ0+β1logx\log y = \log \beta_0 + \beta_1 \log x

Interpretation: β1\beta_1 is the elasticity (% change in yy per % change in xx)

Transformation Guidelines

  1. Exponential growth → Log transform yy: log(y)=β0+β1x\log(y) = \beta_0 + \beta_1 x
  2. Power relationships → Log-log transform: log(y)=β0+β1log(x)\log(y) = \beta_0 + \beta_1 \log(x)
  3. Check requirements: Variables must be positive for log transformation
  4. Don’t transform: Binary/dummy variables (0/1)
  5. Diagnostic check: Residual plots after transformation

Remember: Coefficients in log models represent percentage effects!

Practical Applications

Business Examples:

  • Revenue growth over time (exponential)
  • Price elasticity of demand (power law)
  • Economies of scale (power relationships)

Scientific Examples:

  • Population dynamics
  • Allometric scaling (brain-body, metabolic rates)
  • Network effects (Metcalfe’s law)

Key Insight: Transform to reveal hidden linear structure

Predictive modeling practice

  • Practice small calculations and explanations:

  • Conditional means and the assumptions behind a prediction.

  • CDFs, likelihood, and sampling variability.

  • Fitted values, residuals, loss, and one gradient update.

  • Compare a numerical prediction with a predicted class probability.

Explain the fitted model

Work individually.

What does a slope of 2 mean in the units of xx and yy?

What does a curved residual pattern suggest?

Why does a small training loss leave a question about future predictions unanswered?