9.2. Comparing Distributions#

Hide code cell source

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

%matplotlib inline

Section Assessing a Model with Simulation tested a model with one number: the count of women among 50 promotions. Many business questions involve more than two categories. Does the age mix of survey respondents match the age mix of customers? Does this quarter’s sales by channel match last quarter’s? Does the share of support tickets across product lines match the plan?

The method is the one you already know: state a chance model, choose a statistic, simulate the statistic many times, and see where the observed value falls. The new pieces are a statistic that summarizes a whole distribution across several categories, and a simulation that draws counts for all categories at once. The section also looks closely at what a large gap can mean when the cause is not chance.

9.2.1. Is the Survey Representative?#

A retailer emailed a customer satisfaction survey to its customer list and received 600 responses. Leadership will read the results to decide whether to change store hours and service staffing. Before the analyst reports anything, one question comes first: do the 600 respondents look like the customers the company actually has?

This matters because the answer to “how satisfied are customers?” depends on who is answering. Suppose older customers rate service differently from younger ones, perhaps because they visit stores more often and use staff help more. If older customers are overrepresented among respondents, the average score describes older customers more than it describes the customer base. A survey is representative when the group that answered has about the same make-up as the group you want to learn about. Age is one visible check. If the respondents’ ages are far off, you have reason to doubt that other traits, including satisfaction, are in proportion either.

You can check age because the retailer knows the age mix of its whole customer base from its loyalty program records. (The retailer and its numbers are hypothetical, made up for this example.)

9.2.2. Comparing Two Distributions#

The distribution of a categorical variable lists each category with its share of the whole. The table below gives two distributions across five age groups: the customer base (all customers) and the 600 survey respondents.

age_groups = ['18-24', '25-34', '35-44', '45-54', '55+']
base_shares = np.array([0.12, 0.22, 0.24, 0.20, 0.22])    # all customers
resp_shares = np.array([0.04, 0.15, 0.24, 0.25, 0.32])    # the 600 respondents

ages = pd.DataFrame({'Customer base': base_shares, 'Respondents': resp_shares},
                    index=age_groups)
ages.index.name = 'Age group'
ages
Customer base Respondents
Age group
18-24 0.12 0.04
25-34 0.22 0.15
35-44 0.24 0.24
45-54 0.20 0.25
55+ 0.22 0.32

Each column adds to 1 (100%). A side-by-side bar chart makes the gaps easier to see than a table of numbers.

x = np.arange(len(age_groups))
width = 0.38

fig, ax = plt.subplots(figsize=(7, 4))
ax.bar(x - width / 2, 100 * base_shares, width, color='#1f77b4', label='Customer base')
ax.bar(x + width / 2, 100 * resp_shares, width, color='#ff7f0e', label='Survey respondents')
ax.set_xticks(x)
ax.set_xticklabels(age_groups)
ax.set_xlabel('Age group (years)')
ax.set_ylabel('Share of group (%)')
ax.set_title('Respondents skew older than the customer base')
ax.legend()
plt.show()
../../_images/1a434481bf4a99410491e270761769833cb7aec20eeb104041e2b16848cbd31b.png

The chart shows a pattern: the two youngest groups are underrepresented among respondents, the two oldest are overrepresented, and the 35 to 44 group matches exactly. You can put numbers on each gap by subtracting the shares, in percentage points.

diff_points = 100 * (resp_shares - base_shares)
for group, d in zip(age_groups, diff_points):
    print(f'{group:>5}: respondents minus base = {d:.0f} points')
print('Sum of the differences:', round(diff_points.sum(), 10))
18-24: respondents minus base = -8 points
25-34: respondents minus base = -7 points
35-44: respondents minus base = 0 points
45-54: respondents minus base = 5 points
  55+: respondents minus base = 10 points
Sum of the differences: 0.0

The differences add to zero because both columns add to 100%. Whatever one group gains, others lose.

You could run a separate test for each age group, asking whether 4% is too low for ages 18 to 24, whether 32% is too high for ages 55 and over, and so on. That is awkward for two reasons. First, the five tests would give five answers, and the manager wants one: does the survey match the customers or not? Second, the groups are not independent. A sample that has too many older respondents must have too few of someone else, so the five differences move together. It is better to summarize all the gaps in a single number and test that.

9.2.3. Total Variation Distance#

The total variation distance (TVD) measures how far apart two distributions are across the same categories. It takes three steps:

  1. For each category, find the difference between the two shares.

  2. Take the absolute value of each difference, so gaps in either direction count as distance.

  3. Add the absolute differences and divide by 2.

Why divide by 2? Because the signed differences add to zero, the total amount by which some groups are too high equals the total amount by which others are too low. The sum of absolute differences counts every shift twice, once where the share is too high and once where it is too low. Halving it counts the share that would have to move from one group to another to turn one distribution into the other.

In symbols, for shares \(p_i\) and \(q_i\) in category \(i\):

\[\text{TVD} = \frac{1}{2} \sum_i |p_i - q_i|\]

A TVD of 0 means the distributions are identical. A TVD of 1 means they have no overlap at all (for example, one distribution puts everything in one category and the other puts everything in a different category). Here are the steps for the survey.

abs_diff = np.abs(resp_shares - base_shares)

for group, d in zip(age_groups, abs_diff):
    print(f'{group:>5}: |difference| = {d:.2f}')

print('Sum of absolute differences:', round(abs_diff.sum(), 2))
observed_tvd = abs_diff.sum() / 2
print('Total variation distance:', round(observed_tvd, 2))
18-24: |difference| = 0.08
25-34: |difference| = 0.07
35-44: |difference| = 0.00
45-54: |difference| = 0.05
  55+: |difference| = 0.10
Sum of absolute differences: 0.3
Total variation distance: 0.15

The TVD is 0.15. Read it as: about 15% of the respondents would have to be in a different age group for the survey to match the customer base exactly. That is 90 of the 600 people. That is a large share, but you cannot yet say whether it is larger than chance would produce with 600 respondents. The next two parts answer that.

Because you will compute TVD many times, put the steps in a function.

def tvd(p, q):
    return np.abs(p - q).sum() / 2

print(round(tvd(resp_shares, base_shares), 2))
0.15

9.2.3.1. Practice#

### Exercise: TVD of a Drink Mix
# 1. A coffee shop sold drinks in three categories last month and this month.
# 2. Compute the TVD between last month and this month. Store it in tvd_value.
# 3. Print the TVD rounded to 3 decimals.
# 4. Print how many of this month's 1,000 drinks would have to be in a different category to match last month's mix (TVD times 1,000, as a whole number).
# Print exactly:
# TVD: 0.1
# Drinks to move: 100
import numpy as np
last_month = np.array([0.50, 0.30, 0.20])   # coffee, tea, cold drinks
this_month = np.array([0.40, 0.35, 0.25])
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
import numpy as np
last_month = np.array([0.50, 0.30, 0.20])   # coffee, tea, cold drinks
this_month = np.array([0.40, 0.35, 0.25])
tvd_value = np.abs(this_month - last_month).sum() / 2
print('TVD:', round(tvd_value, 3))
print('Drinks to move:', round(tvd_value * 1000))
TVD: 0.1
Drinks to move: 100

9.2.4. Simulating Random Samples#

The chance model for the survey is: the 600 respondents are a random sample of the customer base. Each respondent is an independent draw, and each draw lands in age group \(i\) with the customer-base share \(p_i\) (0.12, 0.22, 0.24, 0.20, 0.22). If this model were true, any gap between the respondents and the customer base would come only from chance in who happened to respond.

In Section Assessing a Model with Simulation each draw had two outcomes (promoted woman or not), and rng.binomial gave the count of one outcome. Here each draw has five outcomes, so the counts for the five groups come from a multinomial distribution, which you met in Descriptive Distributions. The call rng.multinomial(600, base_shares) returns five counts that add to 600, one per age group. It is the same idea as the binomial with more categories, and the same method as 9.1. The pattern is:

rng.multinomial(n, pvals, size=None)

  • n: the number of draws in one sample, here 600 respondents

  • pvals: the chance of each category, in a fixed order, here base_shares

  • size: how many samples to draw; leave it out for one sample

Without size, the call returns one array of counts that adds to n, with the counts in the same order as pvals. With size=10000, it returns a 2-D array with 10,000 rows, one sample per row and one column per category. This section uses a loop instead, so each step stays visible.

Warning

The chances in pvals must add to 1, and NumPy does not check this. It ignores the last value and gives the last category whatever chance the others leave. With pvals=[0.5, 0.3, 0.1], which adds to 0.9, the last category gets 20% of the draws, not 10%. NumPy raises an error only when the other values alone add to more than 1. Check pvals.sum() before you simulate, especially when the shares were rounded.

9.2.4.1. One Random Sample#

Seed the generator so the numbers in this section are the same each time you run it. One simulated sample gives five counts, which are converted to shares by dividing by 600.

rng = np.random.default_rng(902)

sample_counts = rng.multinomial(600, base_shares)
sample_shares = sample_counts / 600

sim_table = pd.DataFrame({'Customer base': base_shares,
                          'Simulated sample': sample_shares.round(3)},
                         index=age_groups)
print('Counts:', sample_counts, ' total =', sample_counts.sum())
sim_table
Counts: [ 65 127 145 126 137]  total = 600
Customer base Simulated sample
18-24 0.12 0.108
25-34 0.22 0.212
35-44 0.24 0.242
45-54 0.20 0.210
55+ 0.22 0.228
print('TVD of this one simulated sample:', round(tvd(sample_shares, base_shares), 3))
TVD of this one simulated sample: 0.02

A random sample of 600 does not match the customer base exactly. Each group’s share is a little above or below its base share, just as the sampling variability in Section Sampling Variability led you to expect. The TVD of this one sample is 0.02, far below the observed 0.15. One sample is not enough to judge, since a single draw could be unusually close or unusually far. You need many.

9.2.4.2. Many Samples#

Now repeat the sampling 10,000 times. Each repetition draws a random sample of 600 from the customer base, computes the age shares, and records the TVD between the sample and the customer base. The 10,000 TVDs form the empirical distribution of the statistic under the chance model, as in 9.1.

n_sims = 10000
sim_tvds = np.zeros(n_sims)

for i in range(n_sims):
    counts = rng.multinomial(600, base_shares)
    sim_tvds[i] = tvd(counts / 600, base_shares)

print('Mean simulated TVD:   ', round(sim_tvds.mean(), 3))
print('95th percentile:      ', round(np.percentile(sim_tvds, 95), 3))
print('Largest simulated TVD:', round(sim_tvds.max(), 3))
Mean simulated TVD:    0.032
95th percentile:       0.053
Largest simulated TVD: 0.082

Under the chance model, the typical TVD for a sample of 600 is about 0.03, 95% of samples stay below about 0.05, and even the largest of 10,000 samples is about 0.09. Now draw the histogram and mark the observed value.

fig, ax = plt.subplots(figsize=(7, 4))
ax.hist(sim_tvds, bins=30, color='#1f77b4', edgecolor='white')
ax.axvline(observed_tvd, color='#d62728', linewidth=2.5)
ax.annotate('Observed survey TVD = 0.15', xy=(observed_tvd, 600),
            xytext=(0.14, 1000), ha='right', color='#d62728',
            arrowprops=dict(arrowstyle='->', color='#d62728'))
ax.set_xlabel('Total variation distance from the customer base')
ax.set_ylabel('Number of simulated samples')
ax.set_title('Random samples stay close to the base; the survey does not')
ax.set_xlim(0, 0.17)
plt.show()
../../_images/6d2c80d895e5bf13e9652b5d6a6096b41e3466740da9631dfc718f435ed66542.png

The red line is far to the right of the whole histogram. The simulated samples cluster between 0.01 and 0.06, while the survey sits at 0.15.

9.2.4.3. Practice#

9.2.4.3.1. One Simulated Sample#

### Exercise: One Simulated Sample of Orders
# 1. Create a generator with np.random.default_rng(5) named ex_rng.
# 2. Draw one multinomial sample of 200 orders using ex_probs. Store the counts in ex_counts.
# 3. Print the counts.
# 4. Print the shares (counts divided by 200), rounded to 3 decimals.
# Print exactly:
# Counts: [109  57  34]
# Shares: [0.545 0.285 0.17 ]
import numpy as np
ex_probs = np.array([0.5, 0.3, 0.2])   # store, web, app
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
import numpy as np
ex_probs = np.array([0.5, 0.3, 0.2])   # store, web, app
ex_rng = np.random.default_rng(5)
ex_counts = ex_rng.multinomial(200, ex_probs)
print('Counts:', ex_counts)
print('Shares:', (ex_counts / 200).round(3))
Counts: [109  57  34]
Shares: [0.545 0.285 0.17 ]

9.2.4.3.2. Simulating the TVD#

### Exercise: Simulating the TVD for Orders
# 1. Create a generator with np.random.default_rng(6) named ex_rng.
# 2. Simulate 5,000 samples of 200 orders from ex_probs. For each, compute the TVD between the sample shares and ex_probs, and store it in ex_tvds.
# 3. Print the mean of ex_tvds, rounded to 3 decimals.
# 4. Print the 95th percentile of ex_tvds, rounded to 3 decimals.
# 5. Print the largest value in ex_tvds, rounded to 3 decimals.
# Print exactly:
# Mean: 0.038
# 95th percentile: 0.075
# Largest: 0.13
import numpy as np
ex_probs = np.array([0.5, 0.3, 0.2])   # store, web, app
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
import numpy as np
ex_probs = np.array([0.5, 0.3, 0.2])   # store, web, app
ex_rng = np.random.default_rng(6)
ex_tvds = np.zeros(5000)
for i in range(5000):
    ex_counts = ex_rng.multinomial(200, ex_probs)
    ex_tvds[i] = np.abs(ex_counts / 200 - ex_probs).sum() / 2
print('Mean:', round(ex_tvds.mean(), 3))
print('95th percentile:', round(np.percentile(ex_tvds, 95), 3))
print('Largest:', round(ex_tvds.max(), 3))
Mean: 0.038
95th percentile: 0.075
Largest: 0.13

9.2.5. Assessing the Model#

The observed TVD is 0.15. Count how many of the 10,000 simulated samples have a TVD at least that large. Large TVDs are the evidence against the model, so the tail that matters is the right-hand tail.

n_extreme = np.sum(sim_tvds >= observed_tvd)
print('Simulated samples with TVD >= 0.15:', n_extreme, 'of', n_sims)
print('Proportion:', n_extreme / n_sims)
print('Largest simulated TVD:', round(sim_tvds.max(), 3))
print('Observed TVD is', round(observed_tvd / sim_tvds.max(), 1), 'times the largest simulated TVD')
Simulated samples with TVD >= 0.15: 0 of 10000
Proportion: 0.0
Largest simulated TVD: 0.082
Observed TVD is 1.8 times the largest simulated TVD

None of the 10,000 random samples came close. The tail proportion is 0, and the largest simulated TVD is about 0.09, well below 0.15. The simulation does not mean the true chance is exactly zero; it means that a gap this large essentially never happens when 600 respondents are drawn at random from this customer base. Section Hypotheses and p-Values gives this tail proportion its standard name.

Conclusion. The survey respondents are not what a random sample of the customer base looks like. The data are inconsistent with the chance model, and the age gap is not a fluke of who happened to respond. Something systematic is shaping who answers. This is the second of the three outcomes in this chapter: in 9.1 a small tail proportion gave evidence against random selection, here the evidence is stronger still, and in 9.3 the data will turn out to be consistent with the model.

The test tells you the sample is skewed. It does not say why. That is a question about how the survey was run.

9.2.6. Why the Survey Is Skewed#

Two common causes of a skewed sample, both visible in this case, are who gets asked and who answers.

The sampling frame. The sampling frame is the list from which respondents are drawn. Here it is the retailer’s email list. Customers who never gave an email address, or whose address is outdated, cannot be reached at all. If younger customers shop as guests, or older customers are more likely to have registered, the frame itself is tilted before anyone answers.

Non-response. Even among customers who receive the email, only some respond. Non-response bias arises when the people who answer differ systematically from those who do not. Older customers may open and complete email surveys more often; many younger customers ignore promotional email or have a separate address for it. The result is a respondent group that looks older than the customer base, which is what the test found. Note that the bias is not about the 600 who answered being wrong. It is about the people the survey never heard from.

Three fixes are common, and each has limits.

  • Follow-ups and reminders raise response rates and bring in some who would have skipped the first email. They help most when non-response is due to inattention, but the people who still refuse may be different from those who respond to a nudge.

  • Other channels such as text messages, in-store tablets, or a receipt link reach customers the email list misses. They add new groups, but each channel has its own skew, and the mix of channels is itself a choice.

  • Weighting gives each respondent a weight so that the weighted age mix matches the customer base. A respondent in an underrepresented group counts more, and one in an overrepresented group counts less. The weight for a group is its base share divided by its respondent share.

weights = base_shares / resp_shares
for group, w in zip(age_groups, weights):
    print(f'{group:>5}: weight = {w:.2f}')
18-24: weight = 3.00
25-34: weight = 1.47
35-44: weight = 1.00
45-54: weight = 0.80
  55+: weight = 0.69

Each 18 to 24 respondent counts as 3 people (12% divided by 4%), while each 55 and over respondent counts as about 0.7. To see what this does, suppose the average satisfaction scores (1 to 5) by age group in the survey were as follows.

avg_score = np.array([3.4, 3.6, 3.8, 4.0, 4.3])        # mean score by age group

raw_mean = np.sum(resp_shares * avg_score)               # what the survey reports
adjusted_mean = np.sum(base_shares * avg_score)          # weighted to the customer base

print('Survey average score:      ', round(raw_mean, 2))
print('Weighted to customer base: ', round(adjusted_mean, 2))
print('Overstatement:             ', round(raw_mean - adjusted_mean, 2))
Survey average score:       3.96
Weighted to customer base:  3.86
Overstatement:              0.11

In this example the older respondents are happier, so the raw average overstates satisfaction for the customer base: the survey says 3.96, while the weighted average is 3.86. Weighting corrects the age imbalance and gives a better estimate.

But weighting has limits. It fixes only the traits that are measured. If the 55 and over customers who answered are happier than the 55 and over customers who did not, then within every age group the respondents are still unlike the non-respondents, and no age weight can repair that. Weights also make estimates less stable, since a few young respondents are made to count as three each. The strongest protection is to design the survey to reach the whole customer base in the first place, and to report the response rate and the comparison with the customer base along with the results.

9.2.6.1. Practice#

### Exercise: Weights for a Regional Survey
# 1. A survey has respondents from three regions. Compute weights as base share divided by respondent share and store them in ex_weights.
# 2. Print the weights rounded to 2 decimals.
# 3. Compute the weighted average score: sum of ex_base times ex_score. Compute the raw average: sum of ex_resp times ex_score.
# 4. Print the raw average and the weighted average, each rounded to 2 decimals.
# Print exactly:
# Weights: [2.   0.86 0.5 ]
# Raw average: 4.15
# Weighted average: 3.7
import numpy as np
ex_base = np.array([0.50, 0.30, 0.20])    # customer base: north, south, west
ex_resp = np.array([0.25, 0.35, 0.40])    # respondents
ex_score = np.array([3.0, 4.0, 5.0])      # average score by region
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
import numpy as np
ex_base = np.array([0.50, 0.30, 0.20])    # customer base: north, south, west
ex_resp = np.array([0.25, 0.35, 0.40])    # respondents
ex_score = np.array([3.0, 4.0, 5.0])      # average score by region
ex_weights = ex_base / ex_resp
print('Weights:', ex_weights.round(2))
raw = np.sum(ex_resp * ex_score)
weighted = np.sum(ex_base * ex_score)
print('Raw average:', round(raw, 2))
print('Weighted average:', round(weighted, 2))
Weights: [2.   0.86 0.5 ]
Raw average: 4.15
Weighted average: 3.7

9.2.7. Section Practice#

A retailer sold through four channels last year: stores 45%, website 30%, mobile app 15%, and wholesale 10%. This quarter it recorded 800 orders: 336 in stores, 264 on the website, 144 on the app, and 56 in wholesale. Management asks whether the channel mix has really changed, or whether this quarter’s orders could be a random sample from last year’s mix.

### Exercise: Has the Channel Mix Changed?
# 1. Compute the shares for this quarter (counts divided by 800). Store them in ex_shares.
# 2. Compute the observed TVD between ex_shares and last_year. Store it in ex_observed.
# 3. Create a generator with np.random.default_rng(77) named ex_rng. Simulate 10,000 samples of 800 orders from last_year and compute the TVD of each. Store them in ex_tvds.
# 4. Print the observed TVD rounded to 3 decimals.
# 5. Print the proportion of simulated TVDs that are at least as large as the observed TVD.
# 6. Print "Evidence of a change" if that proportion is below 0.05, otherwise "Consistent with last year".
# Print exactly:
# Observed TVD: 0.06
# Proportion at least as large: 0.0012
# Evidence of a change
import numpy as np
last_year = np.array([0.45, 0.30, 0.15, 0.10])   # stores, website, app, wholesale
this_quarter = np.array([336, 264, 144, 56])       # 800 orders
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
import numpy as np
last_year = np.array([0.45, 0.30, 0.15, 0.10])   # stores, website, app, wholesale
this_quarter = np.array([336, 264, 144, 56])       # 800 orders
ex_shares = this_quarter / 800
ex_observed = np.abs(ex_shares - last_year).sum() / 2
ex_rng = np.random.default_rng(77)
ex_tvds = np.zeros(10000)
for i in range(10000):
    ex_counts = ex_rng.multinomial(800, last_year)
    ex_tvds[i] = np.abs(ex_counts / 800 - last_year).sum() / 2
ex_prop = np.mean(ex_tvds >= ex_observed)
print('Observed TVD:', round(ex_observed, 3))
print('Proportion at least as large:', ex_prop)
if ex_prop < 0.05:
    print('Evidence of a change')
else:
    print('Consistent with last year')
Observed TVD: 0.06
Proportion at least as large: 0.0012
Evidence of a change