Roll one die many times and every face turns up about equally often. Roll two dice and add them, and 7 turns up far more often than 2 or 12. Same dice, very different patterns. The pattern of how often each value occurs is called a distribution, and it's the single most important idea in the rest of this course.
You've already been looking at distributions without the name: every histogram in the describing data module was a picture of one. Centre, spread, skew and tails are all features of a distribution. What's new in this module is the step from "the pattern in my data" to "the pattern the data comes from". That step is what lets statistics, and machine learning, say anything about data they haven't seen yet.
What you need first: frequency tables and histograms, skewness and kurtosis and population vs sample.
Key terms
- Distribution: the pattern of which values occur and how often.
- Empirical distribution: the distribution of the data you actually have, shown by its histogram or frequency table.
- Population distribution: the pattern the data comes from, the one you'd see with unlimited data.
- Discrete distribution: one where the values are separate, such as die faces or counts.
- Continuous distribution: one where values can be anything in a range, such as weights or times.
- Density: for continuous data, how tightly values are packed around each point. Areas under a density curve give shares of the data.
One die versus two dice
Simulate 60,000 rolls of one die, and 60,000 throws of two dice added together. Before you run this, sketch what you think each bar chart will look like:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
rng = np.random.default_rng(7)
one_die = rng.integers(1, 7, size=60_000)
two_dice = rng.integers(1, 7, size=60_000) + rng.integers(1, 7, size=60_000)
fig, axes = plt.subplots(1, 2, figsize=(11, 3.8))
for ax, data, title in [(axes[0], one_die, "One die: every face equally common"),
(axes[1], two_dice, "Sum of two dice: 7 is most common")]:
shares = pd.Series(data).value_counts(normalize=True).sort_index()
ax.bar(shares.index, shares.values, color="#d9a05a")
ax.set_xticks(shares.index)
ax.set_ylabel("Share of throws")
ax.set_title(title)
plt.tight_layout()
plt.show()
rng.integers(1, 7, size=60_000) gives 60,000 random whole numbers from 1 to 6 (the 7 is excluded). value_counts(normalize=True) gives the share of throws for each value instead of the count, and sort_index() puts the values in order.
A single die has a flat (uniform) distribution: each face turns up about 1/6 of the time. The sum of two dice has a triangle. Why? Count the ways to make each total. There's only one way to make 2 (1 + 1) and one way to make 12 (6 + 6), but six ways to make 7 (1 + 6, 2 + 5, 3 + 4, 4 + 3, 5 + 2, 6 + 1). With 36 equally likely pairs, 7 should come up 6/36 = 1/6 of the time, and 2 only 1/36. The simulation agrees:
shares = pd.Series(two_dice).value_counts(normalize=True).sort_index()
print(shares[[2, 7, 12]].round(4))
print(round(1 / 36, 4), round(6 / 36, 4))
2 0.0281
7 0.1680
12 0.0284
Name: proportion, dtype: float64
0.0278 0.1667
So a distribution isn't random noise: it has a reason. Here the reason is counting; for real data it's how the world works. Penguins of one species have a typical weight because of their biology; fares have a long tail because a few people buy first-class tickets.
Your data's distribution and the true one
The shares in the chart came from 60,000 throws, so they're very close to the true 1/36 and 6/36. With fewer throws they'd be rougher. Watch the histogram settle as the number of throws grows. Predict what 50 throws will look like:
fig, axes = plt.subplots(1, 3, figsize=(12, 3.4), sharey=True)
for ax, n in zip(axes, [50, 500, 50_000]):
sample = rng.integers(1, 7, size=n) + rng.integers(1, 7, size=n)
shares = pd.Series(sample).value_counts(normalize=True).reindex(range(2, 13), fill_value=0)
ax.bar(shares.index, shares.values, color="#c2410c")
ax.plot(range(2, 13), [min(t - 1, 13 - t) / 36 for t in range(2, 13)], "o--", color="#1c1917", label="true shares")
ax.set_title(f"{n:,} throws")
ax.set_xticks(range(2, 13))
axes[0].set_ylabel("Share of throws")
axes[0].legend()
plt.tight_layout()
plt.show()
reindex(range(2, 13), fill_value=0)makes sure every total from 2 to 12 has a bar, with a share of 0 if it never came up.min(t - 1, 13 - t) / 36is the number of ways to make the total t, divided by 36: the true share for each total.
With 50 throws, the histogram is ragged: a total of 4 turned up only once, far below its true share, and 5 beat 6. From those 50 throws alone, you'd draw the wrong shape. With 50,000 it sits right on the true shares. This is the same lesson as population vs sample, now for whole shapes instead of single averages: your data's distribution (the empirical distribution) is a noisy picture of the true distribution, and it gets sharper as the sample grows.
When statisticians talk about "the distribution of penguin weights", they usually mean the true pattern, the one you'd see if you could weigh every penguin. The 342 weights in the dataset are a sample from it.
Discrete and continuous distributions
Die totals are discrete: they come in whole steps, and each value has its own share, like 1/6 for a total of 7. You draw them as separate bars.
Weights, heights and times are continuous: they can take any value in a range. Here there's a twist. What share of Adelie penguins weigh exactly 3,712.38 g? Almost none, because almost no penguin weighs precisely that. So for continuous data, it makes no sense to give each single value a share. Instead, you give shares to ranges: what share weigh between 3,500 g and 4,000 g?
The way to picture this is a density histogram, scaled so the total area of the bars is 1. Then the area of the bars over any range is the share of data in that range:
Download the data: penguins.csv (15 KB), or from the original source, the palmerpenguins project. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with
pd.read_csv("penguins.csv").
import seaborn as sns
adelie = sns.load_dataset("penguins").query("species == 'Adelie'")["body_mass_g"].dropna()
counts, edges = np.histogram(adelie, bins=15, density=True)
widths = np.diff(edges)
print("total area:", round(float((counts * widths).sum()), 3))
share = ((adelie >= 3500) & (adelie < 4000)).mean()
print("share between 3,500 g and 4,000 g:", round(share, 3))
total area: 1.0
share between 3,500 g and 4,000 g: 0.384
np.histogram(..., density=True) returns the bar heights scaled so the total area is 1, plus the bin edges; np.diff(edges) gives each bar's width. The share between 3,500 g and 4,000 g comes from counting the penguins directly.
As the sample grows and the bins get narrower, a density histogram smooths into a density curve. The height of the curve isn't a share by itself; the area under it between two values is. That's the idea behind the normal distribution in the next lesson.
Describing any distribution
Everything from the describing data module now becomes a way to describe a distribution:
| Feature | Question | Tools |
|---|---|---|
| Centre | Where is it? | Mean, median, mode |
| Spread | How wide is it? | SD, IQR, range |
| Shape | Symmetric or skewed? One hump or more? | Histogram, skewness |
| Tails | How often do extreme values occur? | Kurtosis, percentiles, outlier counts |
Two datasets can match on one feature and differ on others, which is why statisticians look at the whole distribution, usually as a picture, rather than a single number.
Where machine learning uses distributions
- Training and test data must come from the same distribution. A model learns the patterns of its training distribution. If live data comes from a different one (new customers, a new season), performance drops. This is called distribution shift or data drift.
- Classifiers predict distributions.
predict_probareturns a distribution over the classes for each example: 0.8 spam, 0.2 not spam. - Some models assume a shape. Gaussian Naive Bayes assumes each feature follows a bell curve within each class; linear regression's usual confidence intervals assume bell-shaped errors.
- Generative models learn distributions. Image and text generators learn the distribution of their training data, then produce new samples from it.
Common mistakes
- Treating a small sample's histogram as the true shape. With 50 values, bumps and gaps are often luck.
- Reading a density curve's height as a share. For continuous data, only areas are shares.
- Describing a distribution with one number. Give centre, spread and shape, ideally with a picture.
- Assuming new data will look like old data. Check the distribution of new data before trusting a model on it.
Practice
- Without simulating: what share of throws of two dice should give a total of 4? Why?
Show the answer
There are 3 ways to make 4 (1 + 3, 2 + 2, 3 + 1) out of 36 equally likely pairs, so 3/36 = 1/12, about 0.083.
- Predict, then check: what does the distribution of the difference between two dice (first minus second) look like?
Show the answer
A triangle centred on 0, from −5 to 5: a difference of 0 can happen 6 ways, and ±5 only one way each.
diff = rng.integers(1, 7, size=60_000) - rng.integers(1, 7, size=60_000)
print(pd.Series(diff).value_counts(normalize=True).sort_index().round(3))
-5 0.027
-4 0.056
-3 0.084
-2 0.111
-1 0.140
0 0.165
1 0.138
2 0.111
3 0.085
4 0.056
5 0.027
Name: proportion, dtype: float64
- Is each of these discrete or continuous: the number of goals in a football match; a runner's 100 m time; the number of UPI payments a shop gets in an hour; the temperature at noon?
Show the answer
Goals: discrete. 100 m time: continuous. UPI payments: discrete. Temperature: continuous.
- Explain why the share of penguins weighing exactly 3,712.38 g is almost 0, while the share between 3,500 g and 4,000 g isn't.
Show the answer
Weight is continuous, so there are endlessly many possible exact values, and almost no penguin hits any particular one precisely. A range contains a whole stretch of values, so it catches many penguins.
- A model was trained on loan applications from 2019 and is used in 2024. Using the word "distribution", explain why it might perform worse.
Show the answer
The distribution of applicants' incomes, debts and behaviour in 2024 may differ from the 2019 training distribution, for example after price rises or new kinds of customers. The model learned 2019's patterns, which may no longer hold: that's distribution shift.
Interview questions
What is a probability distribution?
A description of how likely each possible value of a random quantity is. For discrete variables it's given by a probability mass function (the probability of each value); for continuous variables by a probability density function, where probabilities are areas under the curve over intervals.
What is distribution shift, and why does it matter for ML?
Distribution shift is a difference between the data distribution a model was trained on and the one it sees in use. It includes covariate shift (inputs change) and concept drift (the relationship between inputs and outputs changes). Models can degrade silently, so teams monitor input distributions and model performance over time.
Key takeaways
- A distribution is the pattern of which values occur and how often, and it usually has a reason behind it.
- Your data's histogram is a noisy picture of the true distribution; it sharpens as the sample grows.
- Discrete distributions give each value a share; continuous ones give shares to ranges, as areas under a density curve.
- Describe a distribution by its centre, spread, shape and tails, ideally with a picture.
- In ML, training and live data must share a distribution, and classifiers output distributions over classes.
Frequently asked questions
Is a distribution the same as a histogram?
A histogram is a picture of the distribution of your data. The true distribution is the pattern behind the data; the histogram estimates it, more accurately as the sample grows.
What's the difference between a distribution and a probability?
A probability is a single number for one event, such as "a total of 7 has probability 1/6". A distribution lists the probabilities for every possible value at once.
Do I need to know the names of distributions?
A handful come up constantly: uniform, normal, binomial, Poisson, exponential and log-normal. You'll meet them in common distributions in data science, starting with the normal distribution next.
What to learn next
- Meet the bell curve in the normal distribution explained.
- See named shapes and where they come from in common distributions in data science.
- Revisit how samples vary in population vs sample.