Probability and Statistics

Chapter 8 · Think Data Science & Management

Probability Models

8.1 · Think Data Science & Management

Today's goals

  • Write a probability model: outcomes and their probabilities
  • Find the probability of an event and its complement
  • Compute and interpret an expected value
  • Use simulation to connect a model to data
  • Separate population from sample, variable from observation

A probability model for one shipment

shipping = pd.DataFrame({
    'outcome': ['on time', '1 day late', '3+ days late'],
    'probability': [0.80, 0.15, 0.05],
})
shipping
        outcome  probability
0       on time         0.80
1    1 day late         0.15
2  3+ days late         0.05
  • Outcomes together form the sample space

Two rules every model follows

  1. Each probability is between 0 (impossible) and 1 (certain)
  2. The probabilities of all outcomes add up to 1
print(shipping['probability'].sum())
1.0

Is this a valid probability model?

On time 0.80 · 1 day late 0.15 · 3+ days late 0.10

  1. Yes: every probability is between 0 and 1
  2. No: the probabilities add up to 1.05
  3. Yes: late shipments are rarer than on-time ones
  4. No: a model needs at least four outcomes

Events and complements

late = shipping['outcome'] != 'on time'
p_late = shipping.loc[late, 'probability'].sum()
print(p_late, 1 - p_late)
0.2 0.8
  • An event is a set of outcomes: "late" = 1 day late or 3+ days late
  • Complement: P(not A) = 1 − P(A)

Expected value: the long-run average

shipping['credit'] = [0, 5, 20]     # $ credit per outcome
print((shipping['credit'] * shipping['probability']).sum())
1.75

What $1.75 means

  • No shipment costs $1.75: each costs $0, $5, or $20
  • It is the average over many shipments
  • 10,000 shipments a month → budget about $17,500

Expected value is for planning across many cases, not predicting one.

The expected credit is $1.75. Which statement is right?

  1. A typical shipment costs $1.75 in credits
  2. Over many shipments, credits average about $1.75 each
  3. Every shipment has a 1.75% chance of a credit
  4. The store should give every customer $1.75

From model to data: simulation

rng = np.random.default_rng(8)
simulated = pd.Series(rng.choice(shipping['outcome'], size=10000,
                                 p=shipping['probability']))
simulated.value_counts(normalize=True)
on time         0.8016
1 day late      0.1525
3+ days late    0.0459
Name: proportion, dtype: float64

Model vs. simulated

Bars comparing model probabilities with simulated proportions for each outcome; they nearly match

  • Simulated average credit: $1.68, close to the expected $1.75
  • More shipments → closer (law of large numbers, 8.2)

Population vs. sample

  • Population: the full group we care about
    • all lunch and dinner bills at the restaurant this year
  • Sample: the part we actually measured
    • the 244 bills in the tips data

We see the sample; we want to learn about the population.

Variables and observations

   total_bill   tip     sex  day    time  size
0       16.99  1.01  Female  Sun  Dinner     2
1       10.34  1.66    Male  Sun  Dinner     3
2       21.01  3.50    Male  Sun  Dinner     3
  • Each row is an observation (one bill)
  • Each column is a variable
  • Quantitative: total_bill, tip · Categorical: sex, day, time

A distribution shows how often values occur

  • Numeric: are most bills around $10? $20? Any very large ones?
  • Categorical: how common is Dinner vs. Lunch?
  • A probability model gives a distribution of chances
  • An empirical distribution gives the observed proportions

Which is the complement of "a support ticket is solved the same day"?

  1. Solved the next day
  2. Not solved the same day
  3. Solved within two days
  4. Never solved

Your turn: a bakery's daily demand

demand = [0, 1, 2, 3]                       # cakes ordered in a day
probabilities = [0.10, 0.30, 0.40, 0.20]
observed = [2, 1, 0, 3, 2, 2, 1, 0, 2, 3, 1, 2, 2, 1, 3, 2, 0, 2, 1, 2]
  1. Check that the probabilities add up to 1
  2. Find P(at least one order) using the complement
  3. Compute the expected number of orders per day
  4. Compare with 20 observed days: share with an order, average orders

Recap

  • A model lists outcomes and probabilities; they add up to 1
  • Complement: P(not A) = 1 − P(A)
  • Expected value = Σ value × probability: a long-run average
  • Simulation turns a model into data
  • Sample → learn about the population

Descriptive Distributions

8.2 · Think Data Science & Management

Today's goals

  • Summarize a variable with mean, median, SD, and IQR
  • Use percentiles and the 1.5 × IQR rule to flag outliers
  • Describe center, spread, shape, and outliers from a plot
  • Recognize normal, binomial, multinomial, and uniform distributions
  • Explain the Central Limit Theorem and the law of large numbers

describe(): a summary in one call

tips[['total_bill', 'tip', 'size']].describe().round(2)
       total_bill     tip    size
count      244.00  244.00  244.00
mean        19.79    3.00    2.57
std          8.90    1.38    0.95
min          3.07    1.00    1.00
25%         13.35    2.00    2.00
50%         17.80    2.90    2.00
75%         24.13    3.56    3.00
max         50.81   10.00    6.00

Center and spread for total_bill

Statistic Value Meaning
Mean $19.79 the average
Median $17.80 the middle bill
SD $8.90 typical distance from the mean
IQR $10.78 range of the middle 50%

Mean > median: a few large bills pull the mean up.

Spread: variance, SD, and percentiles

col = tips['total_bill']
print(round(col.var(), 2), round(col.std(), 2), round(np.std(col), 2))
np.percentile(col, [25, 50, 75, 90])
79.25 8.9 8.88
array([13.3475, 17.795 , 24.1275, 32.235 ])
  • Variance = SD², in dollars², so we report the SD
  • pandas .std() divides by n − 1; np.std() divides by n
  • 90th percentile $32.24: 90% of bills are at or below it

Outliers: the 1.5 × IQR rule

  • Q1 = $13.35 · Q3 = $24.13 · IQR = Q3 − Q1 = $10.78
  • Upper fence = Q3 + 1.5 × IQR = $40.30
  • Lower fence = Q1 − 1.5 × IQR = −$2.82 (no bill is that low)
  • 9 bills are above $40.30
upper = q75 + 1.5 * (q75 - q25)
(col > upper).sum()          # 9

Look at the shape

Left: a right-skewed histogram of total bill with the mean line to the right of the median line. Right: a box plot with several high outliers

Center · spread · shape · outliers

Salaries: most employees earn $50K–$80K, a few executives over $1M. Which describes a typical employee best?

  1. The mean salary
  2. The median salary
  3. The maximum salary
  4. The standard deviation

The normal distribution

  • Symmetric, bell-shaped, centered on the mean
  • Defined by its mean and standard deviation
  • About 68% within 1 SD, 95% within 2 SD, 99.7% within 3 SD
np.random.seed(42)
values = np.random.normal(loc=50, scale=5, size=1000)   # mean 50, SD 5

68-95-99.7, checked

Histogram of 1,000 normal draws with dashed lines at 1 and 2 standard deviations from the mean

  • Within 1 SD: 69.8% · 2 SD: 95.9% · 3 SD: 99.7% of these 1,000 draws

The binomial distribution

  • Number of successes in n independent yes/no trials
  • Each trial has the same probability p
  • np.random.binomial(n=10, p=0.5, size=100): heads in 10 flips, 100 times

Histogram of the number of heads in 10 flips across 100 experiments, peaking at 5, with red points marking the exact binomial probabilities

The multinomial distribution: more than two outcomes

  • Counts in each of k categories over n independent trials
  • np.random.multinomial(20, [0.3, 0.5, 0.2], size=1000): small, medium, large among 20 coffee orders, 1,000 times

Left: stacked bars for 10 draws of 20 coffee orders, each reaching 20. Right: histograms of small, medium, and large counts across 1,000 draws, centered on dashed lines at 6, 10, and 4

The uniform distribution: every value equally likely

Four histograms of die rolls for 60, 600, 6,000, and 60,000 rolls; the bars flatten toward one sixth

  • One fair die: each face has probability 1/6
  • Few rolls: bumpy · many rolls: flat

100 customers are each offered an upgrade; each accepts with probability 0.3, independently. The number who accept is:

  1. Normal with mean 0.3
  2. Uniform from 0 to 100
  3. Binomial with n = 100, p = 0.3
  4. Always exactly 30

Central Limit Theorem: more trials, more bell-shaped

Three histograms of binomial counts with p = 0.2 for 5, 30, and 300 trials, each with a matching normal curve; skewed at 5 trials, bell-shaped at 300

  • Same 5,000 draws in every panel; only the number of trials n changes
  • Central Limit Theorem: sums and averages of many independent values tend toward a normal shape

Distributions are connected

Diagram linking eight distributions. Solid arrows: Bernoulli to binomial by summing n trials, multinomial to binomial by taking one category, normal to standard normal by Z = (X minus mu) over sigma, uniform 0 to 1 to discrete uniform by floor of nU plus 1. Dashed arrows: binomial to normal for large n, binomial to Poisson for large n and small p, Poisson to normal for large lambda

  • Solid: exact · Dashed: approximately, as n or λ grows

The bigger map

Map of 18 probability distributions, with the eight from the previous slide plus hypergeometric, geometric, negative binomial, lognormal, exponential, gamma, beta, chi-square, Student t, and F, joined by exact, approximate, and same-process arrows

The law of large numbers

Two line charts of the running proportion of heads with a red dashed line at 0.5: the first 200 flips swing widely, and all 5,000 flips settle onto the line

  • After 10 flips: 0.300 · 100: 0.560 · 1,000: 0.510 · 5,000: 0.499
  • More observations → the proportion settles near the true value

How the running proportion is computed

np.random.seed(42)
flips = np.random.choice([0, 1], size=5000)    # 0 = tails, 1 = heads
running = flips.cumsum() / (np.arange(5000) + 1)
  • cumsum(): heads so far · np.arange(5000) + 1: flips so far

Your turn: website visits

visits = np.array([410, 395, 430, 420, 405, 1250, 415,
                   400, 425, 390, 435, 410, 1180, 420])
  1. Compute the mean, median, and SD (np.std)
  2. Is the distribution skewed? Compare mean and median
  3. Which would you report as a typical day?
  4. Find Q1, Q3, the IQR, and the upper fence; how many outlier days?

Recap

  • Center: mean and median · Spread: SD, percentiles, IQR
  • Outliers: beyond 1.5 × IQR from the quartiles
  • Mean > median → right skew; report the median for "typical"
  • Normal: 68-95-99.7 · Binomial: successes in n trials · Multinomial: counts in k categories · Uniform: all equal
  • CLT: sums of many independent values → bell shape
  • Law of large numbers: proportions and averages settle as n grows

Sampling Variability

8.3 · Think Data Science & Management

Today's goals

  • Tell a parameter from a statistic
  • Explain why repeated samples give different results
  • Simulate a sampling distribution
  • Compute the standard error of a proportion and of a mean
  • Predict how sample size changes the standard error

Parameter vs. statistic

  • Treat the 244 bills as the whole population
  • Parameter: the population mean, = $19.79
  • Statistic: the mean of one random sample of 20 bills
rng = np.random.default_rng(42)
for i in range(3):
    print(rng.choice(bills, size=20).mean().round(2))
22.45
17.54
20.98

5,000 samples of 20 bills

Left: histogram of the 244 bills, skewed right. Right: histogram of 5,000 sample means on the same axis, narrow and bell-shaped around 19.79

  • Centered on μ · SD of the means $1.99 vs $8.88 for single bills
  • Bell-shaped even though the bills are skewed: the CLT again

One survey, one number

  • True share of customers who would renew: p = 0.6 (unknown in practice)
  • We survey n = 40 customers and get a sample proportion,
  • A second survey of 40 different customers gives a different

How much do those numbers bounce around?

Simulate 5,000 surveys

rng = np.random.default_rng(seed=0)
p_true, n, n_sims = 0.6, 40, 5000

samples = rng.binomial(n=n, p=p_true, size=n_sims)
sample_props = samples / n
np.percentile(sample_props, [2.5, 97.5])
array([0.45, 0.75])

The sampling distribution

Histogram of 5,000 sample proportions from samples of 40, centered on the true 0.6

  • Centered on the true p = 0.6
  • The spread is the sampling variability

Two levels: the data and the samples

One survey's data

  • 40 answers: renew or not
  • Summarized by one
  • What a company actually has

The sampling distribution

  • 5,000 surveys' values
  • Shows how varies
  • Imagined, or simulated

The histogram on the sampling distribution slide shows...

  1. The 40 answers in one survey
  2. The sample proportions from 5,000 surveys
  3. The true proportion of all customers
  4. The customers who did not renew

Standard error: the typical miss

print(round(np.sqrt(0.6 * 0.4 / 40), 4),
      round(sample_props.std(ddof=1), 4))
0.0775 0.0781
  • Formula and simulation agree
  • In practice, plug in for the unknown

Margin of error: about 2 standard errors

  • About 95% of sample proportions land within 2 SE of p
  • 0.6 ± 2 × 0.0775 → 0.445 to 0.755
  • Matches the simulated middle 95%: 0.45 to 0.75

A survey's "margin of error" is usually 2 SE.

Worked example: plug in

A survey of 40 customers finds 26 would renew.

  • 2 SE ≈ 0.15: the true share is plausibly about 0.50 to 0.80
  • Too wide to tell a manager "most customers will renew" with confidence

Standard error of a sample mean

  • Matches the SD of the 5,000 simulated means: $1.99
  • Single bills vary by about $8.88; means of 20 vary by about $2
  • In practice, plug in the sample SD : SE ≈

Bigger samples, smaller standard error

Three histograms of sample proportions for n = 10, 40, and 200; the spread shrinks as n grows

n 10 40 200
SE (formula) 0.155 0.077 0.035

The square-root rule

  • SE shrinks with , not with
  • 4× the sample → ½ the standard error
  • 40 → 160 customers: SE 0.077 → about 0.039

Precision costs more and more: halving the error needs four times the data.

A manager surveys 400 customers instead of 100. The standard error...

  1. Stays the same
  2. Is cut in half
  3. Is cut to one quarter
  4. Doubles

Your turn: planning a bank survey

About 30% of a bank's customers use mobile check deposit.

  1. Compute the SE for samples of 100 and 900 customers
  2. How many times smaller is the SE with 900?
  3. Is 900 worth nine times the cost?
  4. A survey of 100 finds 27%: parameter or statistic?
  5. Deposits have SD $400: SE of the mean deposit for n = 100 and 400

Recap

  • A statistic estimates a parameter; repeated samples vary
  • The sampling distribution shows how much
  • Standard error = SD of the sampling distribution
  • SE of a proportion: · of a mean:
  • 4× the sample → ½ the SE