9.1. Assessing a Model with Simulation#
Managers often have to decide whether a pattern in their data is real or just the luck of the draw. Last quarter’s best-selling region might have simply had a good quarter. A batch of defective parts might be bad luck, or a sign that a machine needs repair. The way to tell is to build a model of what chance alone would produce, simulate it many times, and see whether the data actually observed look like one of the simulated outcomes.
This section walks through that method on one case: promotions at a bank. In Sampling Variability you saw that a statistic computed from a random sample varies from sample to sample. Here that variation serves as a yardstick. Comparing Distributions extends the method to categories with more than two outcomes, and Hypotheses and p-Values gives the method its formal name.
9.1.1. The Promotion Question#
A regional bank promoted 50 employees last year. Women make up 40% of the employees who were eligible for promotion. Yet only 11 of the 50 people promoted were women. If promotions had mirrored the eligible pool, you would expect about 40% of 50, or 20, of them to be women. (The bank and its numbers are hypothetical, made up for this example; the method works the same way on real promotion records.)
The HR analytics team is asked a narrow question: is a gap this large the kind of thing that happens when promotions are decided by chance alone? The question matters for several reasons. A fair process is a goal in itself. A pattern that looks unfair creates legal exposure for the bank. And a process that overlooks qualified people wastes talent the bank has already paid to hire and train.
“By chance” has a precise meaning here. Imagine that each of the 50 promotion slots was filled by drawing a name at random from the pool of eligible employees, without regard to who the person was. Even then, the number of women promoted would not be exactly 20 every year. It would bounce around 20, sometimes higher and sometimes lower. The task is to find out how far from 20 chance typically bounces, and whether 11 is within that range.
9.1.2. A Model of Random Selection#
A chance model is a description of how the data would be generated if only randomness were at work. For the bank, the model is:
There are 50 promotions.
Each promotion goes to a person drawn at random from the eligible pool.
Each person drawn is a woman with probability 0.40, no matter who was drawn before.
The 0.40 is a parameter of the model, a fixed number describing the process, as in Sampling Variability. It is also the model’s one assumption about the bank: that the promotion process treats women and men alike. The rest of this section asks whether the observed data are believable under that assumption.
Note
Treating each draw as independent with probability 0.40 is a simplification. The eligible pool is large, so removing one person barely changes the share of women left, and the simplification is a good one here.
Each promotion is a yes/no trial (woman or not) with the same chance of “yes”, and the yeses are counted in 50 trials. In Descriptive Distributions you met this setup as the binomial distribution and drew binomial counts with np.random.binomial(). Store the facts of the case in three variables.
n_promotions = 50 # people promoted last year
p_woman = 0.40 # share of eligible employees who are women
observed_women = 11 # women among those promoted
print('Expected number of women under the model:', n_promotions * p_woman)
print('Observed number of women:', observed_women)
Expected number of women under the model: 20.0
Observed number of women: 11
The model predicts 20 women, and the data show 11. The difference is 9 people. The next question is how often chance alone produces a difference that large.
9.1.3. Choosing a Statistic#
To compare the data with the model, you need one number that summarizes the data and can be computed the same way for a simulated outcome. This number is called the test statistic. Its value in the real data is the observed statistic.
For the bank, the natural statistic is the number of women among the 50 people promoted. The observed value is 11.
Before simulating, decide which values count as evidence against the model. Under the model, the count is centered at 20. A count far above 20 would mean women were promoted more often than their share predicts, which is not what the team was asked to investigate. A count far below 20 is the pattern of concern. So here small counts are evidence against the model, and large counts are not. Because only one direction counts, you will look at only one end of the distribution later on. Hypotheses and p-Values shows what changes when both directions matter.
Deciding the statistic and the direction before looking at the simulation keeps the analysis honest. Otherwise it is tempting to choose whichever direction makes the data look most unusual.
9.1.4. Simulating the Model#
You cannot ask the bank to repeat last year thousands of times. You can, however, have a computer repeat it under the chance model. Each repetition draws 50 promotions and counts the women. If the model is a reasonable description of a fair process, the simulated counts show what fair promotion rounds look like.
9.1.4.1. One Simulated Round#
NumPy’s random number generator does the drawing, as in Random Number Generation. You create a generator once with a seed, a starting number that makes the results repeatable, and then call its binomial() method:
rng.binomial(n, p, size=None)
n: the number of independent yes/no trials in one round, here 50 promotionsp: the chance of “yes” on each trial, here 0.40size: how many rounds to simulate; leave it out for one round
Without size, the call returns one whole number: the count of yeses in n trials. With size=10000, it returns an array of 10,000 counts, one per round. Writing the argument names, as in rng.binomial(n=50, p=0.40), gives the same call as rng.binomial(50, 0.40).
rng = np.random.default_rng(901)
one_round = rng.binomial(n_promotions, p_woman)
print('Women promoted in one simulated round:', one_round)
Women promoted in one simulated round: 22
In this one simulated round, 22 of the 50 people promoted were women, a little above the expected 20. Run it again and the number changes, because each call produces a new random round. Repeating the call a few times shows the spread.
for i in range(5):
print('Simulated round', i + 1, ':', rng.binomial(n_promotions, p_woman), 'women promoted')
Simulated round 1 : 25 women promoted
Simulated round 2 : 19 women promoted
Simulated round 3 : 24 women promoted
Simulated round 4 : 21 women promoted
Simulated round 5 : 17 women promoted
Five rounds are not enough to say how far chance usually strays from 20, but none of them looks like 11.
9.1.4.2. Many Rounds#
One round tells you little. Repeat the process 10,000 times by asking rng.binomial for 10,000 results at once with the size argument. The code creates the generator again with the same seed, 901, so the 10,000 rounds come out the same no matter how many times you ran the cells above. The resulting list of counts is the empirical distribution of the statistic: the distribution of values that actually came up in the simulation, summarized as a table or histogram. It approximates the statistic’s sampling distribution from Sampling Variability, here under the chance model.
rng = np.random.default_rng(901)
n_rounds = 10000
simulated_counts = rng.binomial(n_promotions, p_woman, size=n_rounds)
print('Rounds simulated:', len(simulated_counts))
print('Average count:', round(simulated_counts.mean(), 2))
print('Smallest count:', simulated_counts.min())
print('Largest count:', simulated_counts.max())
Rounds simulated: 10000
Average count: 19.99
Smallest count: 7
Largest count: 34
Across 10,000 fair rounds the average count of women is almost exactly 20, as the model predicts. Individual rounds ranged from 7 to 34. A histogram shows how the counts are spread.
values = np.arange(simulated_counts.min(), simulated_counts.max() + 1)
frequency = np.array([np.sum(simulated_counts == v) for v in values]) / n_rounds * 100
fig, ax = plt.subplots(figsize=(7, 3.8))
ax.bar(values, frequency, width=1.0, color='steelblue', edgecolor='white')
ax.set_xlabel('Women among the 50 promoted (count)', fontsize=12)
ax.set_ylabel('Share of simulated rounds (%)', fontsize=12)
ax.set_title('Under random selection, about 20 women are promoted', fontsize=13)
plt.show()
The histogram is centered at 20 and is roughly symmetric, with most rounds between about 14 and 26. Small counts are rare, and the farther a count is from 20 the rarer it becomes. This is the model’s prediction for the statistic. Next, see where the real data fall.
9.1.4.3. Practice#
9.1.4.3.1. One Simulated Round#
### Exercise: One Simulated Round
# 1. Create a generator with np.random.default_rng(7).
# 2. Simulate one audit of 40 receipts, where each receipt is an online order with probability 0.30, using rng.binomial(40, 0.30).
# 3. Print the number of online orders in the audit and the number expected under the model (40 * 0.30).
# Print exactly:
# Online orders in the audit: 13
# Expected under the model: 12.0
### Your code starts here.
### Your code ends here.
Online orders in the audit: 13
Expected under the model: 12.0
9.1.4.3.2. Many Rounds#
### Exercise: Many Rounds
# 1. Create a generator with np.random.default_rng(11).
# 2. Simulate 5,000 audits of 40 receipts, each receipt an online order with probability 0.30, with one call to rng.binomial and size=5000.
# 3. Print the average count, rounded to 2 decimals, and the smallest and largest counts.
# Print exactly:
# Average count: 11.98
# Smallest count: 3
# Largest count: 23
### Your code starts here.
### Your code ends here.
Average count: 11.98
Smallest count: 3
Largest count: 23
9.1.5. Comparing the Data with the Simulation#
Now place the observed count, 11, on the same histogram. The bars for counts of 11 or fewer are shaded red, since those are the outcomes at least as unfavorable to the model as the data.
fig, ax = plt.subplots(figsize=(7, 3.8))
colors = ['firebrick' if v <= observed_women else 'steelblue' for v in values]
ax.bar(values, frequency, width=1.0, color=colors, edgecolor='white')
ax.axvline(observed_women, color='black', lw=2, linestyle='--')
ax.annotate('Observed: 11', xy=(observed_women, frequency.max() * 0.8),
xytext=(observed_women - 7.5, frequency.max() * 0.9), fontsize=12,
arrowprops=dict(arrowstyle='->'))
ax.set_xlabel('Women among the 50 promoted (count)', fontsize=12)
ax.set_ylabel('Share of simulated rounds (%)', fontsize=12)
ax.set_title('Only a sliver of random rounds is as low as 11 (red)', fontsize=13)
plt.show()
The observed value sits far out in the left tail, where few simulated rounds reach. To measure how far, count the simulated rounds with 11 or fewer women and take the proportion of all rounds.
rounds_as_low = np.sum(simulated_counts <= observed_women)
share_as_low = rounds_as_low / n_rounds
print('Rounds with', observed_women, 'or fewer women:', rounds_as_low, 'of', n_rounds)
print('Proportion of rounds:', share_as_low)
print('As a percent:', round(share_as_low * 100, 2), '%')
Rounds with 11 or fewer women: 56 of 10000
Proportion of rounds: 0.0056
As a percent: 0.56 %
Only 56 of the 10,000 simulated rounds, or about 0.56%, produced 11 or fewer women. If promotions really were drawn at random from the eligible pool, a result this low would turn up roughly once in every 180 rounds. Either the bank saw an unusually rare piece of bad luck, or the random-selection model does not describe how promotions were decided. The data give strong evidence against the model.
Note
The proportion of simulated outcomes at least as extreme as the observed one is the p-value. Hypotheses and p-Values defines it formally and explains how to use it to make a decision.
Simulation gives an approximate answer, and a different seed would give a slightly different proportion near 0.006. The exact binomial probability, computed from the formula, is a useful check.
from math import comb
exact_tail = sum(comb(n_promotions, k) * p_woman**k * (1 - p_woman)**(n_promotions - k)
for k in range(observed_women + 1))
print('Exact probability of 11 or fewer women:', round(exact_tail, 4))
print('Simulated proportion: ', share_as_low)
Exact probability of 11 or fewer women: 0.0057
Simulated proportion: 0.0056
The simulation and the exact value agree to within 0.0001, so 10,000 rounds is plenty for this purpose.
9.1.6. What the Test Can and Cannot Say#
The result is strong evidence against the claim that promotions were drawn at random from the eligible pool. It is worth being careful about what that does and does not mean.
It is evidence against chance, not proof of intent. The simulation shows that random selection is an unlikely explanation. It says nothing about why promotions departed from random selection, and it cannot show that anyone acted unfairly on purpose.
Other explanations should be checked. Several ordinary factors can produce a gap without any discrimination at all, and an analyst should look at each before drawing conclusions:
The applicant pool. If few women applied for promotion, the relevant pool is smaller than the 40% share of employees.
Qualifications and tenure. If the promotion requires experience that is unevenly spread across groups, the eligible pool is not the right comparison.
Part-time status or role. Promotion may be concentrated in roles that differ in their gender mix.
Each factor changes the model: it changes the 0.40 to something else. The method stays the same, so the analyst can rerun the simulation with a better-justified probability.
Statistical bias. When a selection process systematically yields a different mix than random selection would, it has statistical bias. That is a statement about outcomes, and it does not claim motive. A process can be biased in this sense with no one intending it, for example because informal sponsorship favors people who resemble the existing leaders. Statistical bias is a reason to look into how the process works, not a verdict.
The four-fifths rule. HR departments often screen selection rates with the four-fifths rule (or 80% rule), a guideline from the U.S. Equal Employment Opportunity Commission. It compares the selection rate of one group with the rate of the group with the highest rate. If the ratio is below 80%, regulators may treat the difference as evidence of adverse impact. It is a quick screen, not a test, and the two work differently.
To see the difference, suppose there were 1,000 eligible employees, 400 women and 600 men. Then 11 women and 39 men were promoted.
women_eligible, men_eligible = 400, 600
women_promoted = observed_women
men_promoted = n_promotions - observed_women
women_rate = women_promoted / women_eligible
men_rate = men_promoted / men_eligible
print('Promotion rate, women:', round(women_rate * 100, 2), '%')
print('Promotion rate, men: ', round(men_rate * 100, 2), '%')
print('Ratio of rates:', round(women_rate / men_rate, 3))
Promotion rate, women: 2.75 %
Promotion rate, men: 6.5 %
Ratio of rates: 0.423
The ratio, 0.423, is far below 0.8, so the rule flags the pattern too. But the rule is a fixed threshold. It does not ask how much a ratio of rates varies by chance, and that variation is large when only 50 people are promoted. You can use the same simulation to see how often a purely random process would fail the screen.
women_counts = simulated_counts
men_counts = n_promotions - women_counts
ratios = (women_counts / women_eligible) / (men_counts / men_eligible)
fails_screen = np.mean(ratios < 0.8)
print('Share of random rounds that fail the four-fifths screen:', round(fails_screen, 3))
Share of random rounds that fail the four-fifths screen: 0.235
About 23.5% of fair, random rounds produce a ratio under 0.8, so with this few promotions the rule flags fair processes nearly one time in four. The screen is easy to apply and is the one regulators know, but with small numbers it raises many false alarms, and in large groups it can miss gaps that a test would catch. The simulation test asks a different question. It asks how surprising the observed gap is, given how much chance alone varies. Here the two methods agree: the gap fails the screen and is also very unlikely under random selection. When they disagree, the analyst should look closer rather than trust either one.
9.1.6.1. Practice#
### Exercise: A Screen Versus a Test
# 1. Create a generator with np.random.default_rng(21).
# 2. A team picks 40 staff for a training program from a pool of 500, of whom 150 are part-time. Under random selection each pick is part-time with probability 150 / 500.
# 3. Simulate 10,000 rounds of 40 picks with rng.binomial and size=10000.
# 4. For each round compute the ratio of the part-time selection rate (picks / 150) to the full-time selection rate ((40 - picks) / 350).
# 5. Print the share of rounds with a ratio below 0.8, rounded to 3 decimals. This is how often a random process fails the four-fifths screen.
# Print exactly:
# Share of random rounds failing the screen: 0.305
### Your code starts here.
### Your code ends here.
Share of random rounds failing the screen: 0.305
9.1.7. Section Practice#
A company hired 40 people last year. About 25% of the applicants were under age 30, but only 6 of the 40 people hired were under 30. If hiring were a random draw from the applicant pool, about 10 of the 40 hires would be under 30.
Use the method of this section to decide whether 6 is unusual under that model. Work through the steps in order: state the chance model, choose the statistic and the direction that counts against the model, simulate, and compare.
### Exercise: Hires by Age Group
# 1. Create a generator with np.random.default_rng(31).
# 2. The model: each of 40 hires is under 30 with probability 0.25. Simulate 10,000 rounds with rng.binomial and size=10000.
# 3. The observed count of hires under 30 is 6. Small counts count against the model.
# 4. Print the average simulated count (2 decimals) and the number of rounds with 6 or fewer hires under 30.
# 5. Print the proportion of rounds with 6 or fewer. Then print whether that proportion is
# smaller than the promotion example's 0.0056, the result this section called strong evidence.
# Print exactly:
# Average simulated count: 10.02
# Rounds with 6 or fewer: 969
# Proportion: 0.0969
# As rare as the promotion result: False
### Your code starts here.
### Your code ends here.
Average simulated count: 10.02
Rounds with 6 or fewer: 969
Proportion: 0.0969
As rare as the promotion result: False