A catalogue of distributions and their generative stories
A dense review of distributions recurring throughout the map, organized by their generative stories: Bernoulli trials, rare-event counts, waiting times, proportions, sums and heavy tails. Study their relationships as limits, sums and ratios, which moments exist, and how to avoid scipy.stats parameterization errors.
After this lesson you can
- Associate each distribution with a generative process and choose an appropriate model for a phenomenon.
- Derive the Poisson law as a limit of binomials and the memorylessness of exponential and geometric laws.
- Relate gamma, chi-squared, beta and Dirichlet laws through sums and ratios of independent gamma variables.
- Distinguish light, exponential and heavy tails and determine which moments exist.
- Use scipy.stats without confusing parameterizations (loc, scale, shape, rate versus scale).
Before you start
- 04Random variableCumulative distribution functionQuantile functionProbability densityExpectationVariance and momentsSkewness and kurtosisIndependent random variablesProbability integral transform and inverse transform sampling
- 01Binomial theoremStars and bars
- 03Improper integralGamma functionLimit of a sequence
Motivation: choosing a distribution means choosing a story and a loss
A security service receives an average of critical alerts per day. You want a model for daily alert counts and the first idea is the default in many libraries: a normal with the same mean and variance (for a Poisson count, variance is also ). The model assigns probability to fewer than zero alerts. This visible symptom reflects a deeper error: the normal tells one story (a sum of many small contributions of both signs, unbounded), not the phenomenon’s story (rare independent events accumulating in a counter). The right story, Poisson, gives and no negative mass.
In machine learning the cost of the wrong choice is double, because a distribution does more than describe data: it fixes the loss function. If you model with family and train by maximum likelihood, you minimize , and each family yields a different loss:
| Generative story | Law of | Loss (up to constants) |
|---|---|---|
| Real value with light symmetric noise | normal | squared error |
| The same with outliers | Laplace | absolute error |
| Yes or no | Bernoulli | binary cross-entropy |
| One class among | categorical | cross-entropy |
| A rare-event count | Poisson | (Poisson deviance) |
| A real value with heavy tails | Student |
Each row follows in one line and will recur in regression, classification and network modules. This review therefore does more than catalog formulas: it organizes distributions by their generative story (Bernoulli trials, rare events, waiting times, proportions, sums and heavy tails), which lets you choose the right law and derive its properties. The map outlines the lesson. Each arrow is a construction: a sum, limit, ratio or transformation. Choose one and vary its parameters to watch the starting law become the target law.
Nearly everything that follows reduces to three moves. Add independent variables (Bernoulli to binomial, exponential to gamma, squared normal to chi-squared). Take limits as a parameter becomes extreme (binomial to Poisson, geometric to exponential, hypergeometric to binomial). Divide one variable by another or by a sum (a gamma divided by a gamma sum gives beta). Once seen, the catalog becomes a network of consequences to reconstruct rather than a list to memorize.
Bernoulli trials: binomial, geometric and relatives
The simplest story is an experiment with two outcomes repeated under the same conditions. We work with discrete random variables as in the random variables lesson: their laws are determined by a mass function .
The binomial is a sum of trials, the geometric waits for the first success. The counting arguments behind the formulas are worth seeing once, as a way to reconstruct them without memorization.
Proof
For the binomial, the event “ specified successes and failures” has probability by independence, and ways choose which trials succeed (the binomial theorem confirms masses sum to ). Since is the sum of independent variables with mean and variance , its mean is and by Bienaymé’s variance identity its variance is . For geometric, (the first trials fail), and since is integer-valued, ; for variance, , giving . Count the negative binomial by choosing slots for failures: the -th success occurs after exactly failures if and only if trial succeeds and the preceding trials contain successes and failures in any order. There are orders, each with probability . This also counts distributing failures among slots before each success, i.e. nonnegative integer solutions of counted by stars and bars. Another reading follows: , the sum of independent geometric variables (failures before each success), so its mean is and variance . In the multinomial, is binomial (each trial is “ or not”), and for , , with (the events are incompatible), and covariance zero across different trials, giving .
∎The multinomial’s negative signs matter: if rises, the rest must fall because the sum is fixed at . This occurs in token counts in a corpus or class-specific successes in an evaluation set, and is why simultaneous confidence intervals for category proportions cannot be built as if they were independent. The categorical law also describes a language model’s output at each step: sampling the next token is a categorical draw with , and training with cross-entropy is categorical maximum likelihood.
Sampling without replacement: the hypergeometric
The binomial assumes independent trials: after each draw, the urn returns to its initial state. Drawing balls without replacement from an urn of balls, of them red, makes trials dependent: drawing red reduces the remaining red fraction. This describes a minibatch drawn from a dataset within one training epoch, or an audit sample from a finite population.
The formula counts favorable over possible cases: choose red balls among and the remaining among non-red balls, divided by all subsets of size . Mean and variance follow from writing with the indicator that draw is red. Each is with (by symmetry: draws are exchangeable), so . For variance use covariance between two distinct draws, , the negative correlation seen in the moments lesson for sampling without replacement. This gives
Factor is the finite-population correction: it equals when , decreases with and vanishes at , when the whole urn is drawn and the red count is without uncertainty. With , and , variance is versus for a binomial with the same .
Proof
Using falling-factorial notation , : the same case count, but ordering the draws. If and is fixed, , because each of factors tends to . Applied to , and , ratio tends to , including boundary cases and .
∎In words: if the urn is enormous relative to the sample, replacement makes no difference. The proof also specifies how enormous: fixed and . With and , the binomial is still wrong in the second decimal place of ( exact versus ); the map’s hypergeometric-to-binomial transition ranges from (where the hypergeometric is a point mass) to .
Rare events: the Poisson law
A service receives calls, a server suffers failures, a social network receives incoming links: in each case there are many opportunities for an event, each with tiny probability independent of the others, and the observed quantity is the total count. A binomial describes this story, but with enormous and tiny . Poisson is the limiting law, with only one quantity that matters: the expected count .
The masses sum to by the expansion of , which also gives moments: ; similarly , so . Mean and variance agree: Poisson’s signature and a common diagnostic (if count data have variance much greater than mean, the Poisson story is wrong and a more flexible one, such as negative binomial, is needed).
Proof
Fix . For ,
The first product has factors, each with limit , and since is fixed its limit is ; the second factor’s base tends to and its exponent is fixed. The final factor remains: by the Taylor expansion ,
and by continuity of the exponential (a sequence limit worth knowing how to prove, not just cite). Multiplying the limits gives the result.
∎Pointwise convergence of masses is true, but a model calculates probabilities of sets of values, not just individual values. The appropriate notion is total variation distance between two discrete laws, . If and are laws on the integers and for every , then (Scheffé’s lemma): since , the distance is , a sum of terms tending to dominated by , which is summable; dominated convergence for series gives the limit. The next figure measures it.
Two readings. First, error decays as and no faster, explaining why the approximation is good with trials but not . Second, Le Cam’s bound, proved now, has the right order but a pessimistic constant.
Proof
Three pieces. (i) For one summand, . Indeed assigns to (more than because ), to (less than ), and to the remaining integers, where has no mass. Distance is the sum of positive differences of over : . (ii) Total variation is subadditive for sums of independent variables: , where is convolution. Pass through intermediate and use that convolution with a law cannot increase distance: . (iii) A sum of independent Poisson variables is Poisson: by the binomial theorem, . Then and applying (ii) times with (i) gives the first inequality. The second follows from .
∎For , exact numbers (cell below) are with versus bound , and with versus : the bound is about twelve times reality and the ratio stabilizes because true distance behaves as . The Chen–Stein refinement (Barbour and Hall, 1984) reduces the bound to , only four times larger. Beyond constants, the rule of thumb is Poisson approximation is reasonable when is small, even if differ, as in actual failure or click counts.
Waiting times: exponential, gamma and chi-squared
Now view the same story in time. If Poisson events occur at rate per unit time, how long until the first? Divide time into pieces of length with a trial of probability each: the wait in pieces is geometric. As the mesh refines, this rescaled geometric tends to the continuous-time waiting law.
Memorylessness
The exponential has a property characterizing it among continuous laws. If you have already waited with nothing happening, the remaining wait has exactly the same law as at the start.
Proof
For the exponential, ; for the failure-counting geometric, . Uniqueness is proved at the end (first proof exercise): solve Cauchy’s functional equation with monotone .
∎Memorylessness formalizes absence of wear or burn-in: instantaneous event risk is constant. A gamma with shape does not have this: risk increases with (something that wears, like a mechanical component) and decreases with (something sturdy if it survives the start, like infant failures of a chip). The next figure shows it.
This warns against simplistic failure-time and latency models. If data show those waiting longer will wait still longer (decreasing hazard), the exponential predicts an overoptimistic residual time and a gamma with or a heavier-tailed law is needed (see the heavy-tail section).
Sums and ratios of gamma variables
A key calculation using change of variables gives three results at once: a sum of gammas is gamma, the proportion is beta, and the two are independent.
Proof
The joint density of is on . Change variables , , with and , a bijection with Jacobian of absolute value . By the density change-of-variables formula, the joint density of is
This is a product of a function of and one of on a rectangle: by the density characterization of independence, , and each bracket, normalized, is a marginal density. The first is that of and the second a beta. Since both are densities, the second integrates to , also proving .
∎Three frequently used consequences. First, a sum of independent gammas with the same rate is gamma, and by induction the sum of exponentials of rate is , seen in the exponential-to-gamma map. Second, beta is a normalized gamma, a ratio of form . Third, waiting time until arrival number in a process with exponential waits is gamma, connected to Poisson counts through a duality proved by differentiation.
Proof
Equality of events defines . For equality of probabilities, differentiate the right side with respect to . With , , and summing for terms cancel in a telescoping sum, leaving . Multiplied by , this is density of . Both sides equal at and have the same derivative, so agree.
∎This links the stories: exponential waits, Poisson counts. With three alerts per day on average, the probability the third arrives before hours is . The map’s exponential-to-Poisson edge simulates this: count arrivals with exponential waits in one unit of time and compare with the Poisson pmf.
Chi-squared
We must justify that is what its name says: a sum of squares of independent standard normals. For , if , the distribution function of is , which differentiated with respect to gives , density , since and . The remainder is a sum of gammas: .
Laplace: the difference of two exponentials
An exponential lives only on . Subtract two independent exponentials with the same rate to obtain a symmetric variable with exponential tails on both sides: the double exponential or Laplace law.
If , then . For , its density is , and by symmetry the same for . Thus mean , variance , skewness and kurtosis (from the moments table): heavier tails than normal, though still exponential, with all moments.
Its statistical importance is absolute value. A sample has log likelihood, up to constants, , and function is convex and piecewise linear with derivative where it exists. That derivative changes sign as crosses half the observations, so the maximum-likelihood estimator of Laplace location is the sample median, just as for normal it is the mean. The scale estimator evaluated at the median is mean absolute deviation .
This law appears in machine learning for two reasons. First, a Laplace prior on regression weights, , makes the maximum-a-posteriori estimator minimize squared error plus penalty : lasso, with the density’s sharp peak at generating exactly zero weights. Second is differential privacy. If query changes by at most when one record changes, the mechanism responding with has response density ratio for neighboring databases
by the triangle inequality. That uniform bound defines -differential privacy (Dwork, McSherry, Nissim and Smith, 2006): Laplace bounds the ratio for all outputs , unlike a Gaussian under this scheme. With sensitivity and , noise has scale and exceeds in absolute value with probability .
Proportions: beta and Dirichlet
A proportion is a variable on : an advertisement’s click-through rate, an unknown coin probability, or a budget fraction. Its natural law is beta, already seen as the law of with independent gammas of equal rate. For more than two categories, when allocation among them matters, Dirichlet generalizes it.
The best way to understand Dirichlet is to generate it. The proof repeats the gamma–beta theorem with a larger Jacobian.
Proof
Use substitution for and , with ; its Jacobian has absolute value (the matrix that was in the two-variable proof). With joint density and , joint density of is , product of the density of and the Dirichlet density. Consequences follow from with : gives the mean; the second moment; covariance. Parts (ii) and (iii) apply the previous theorem to versus (gamma with by gamma addition), and similarly for groups.
∎Negative covariance parallels the multinomial: components sum to . The figure interprets the parameters.
Two qualitative regimes. With , density diverges near face and mass clusters at corners and edges: allocations are sparse, with nearly all mass on few categories. This is desirable in topic modeling, where each document covers few topics: the Dirichlet prior in latent Dirichlet allocation (Blei, Ng and Jordan, 2003) has small . With there is an interior mode at and, the larger , the more tightly allocations concentrate around the mean. acts as the prior’s sample size, visible in conjugacy.
Proof
By Bayes’ rule the posterior density is proportional to likelihood times prior: , the kernel of ; the normalizing constant follows. The multinomial is identical with .
∎Thus with uniform prior and seven successes in ten trials, the posterior is with mean and central interval approximately . Parameters are interpreted as pseudo-successes and pseudo-failures. This conjugacy, with and accumulating data, is the thread of conjugate priors in statistics. Outside inference, beta appears in mixup data augmentation, mixing two examples with weight (Zhang et al., 2018): with , weight is usually near or (examples hardly mix), while for large it is near .
The univariate normal and standardization
The normal needs no introduction, but its uses and proofs deserve review.
The constant follows from the Gaussian integral (Gaussian integral). Standardization observes that all normal laws are the same up to location and scale: if then because , and substitution turns that integral into . Conversely : any normal is an affine transform of the standard one, a sampling recipe and the basis of reparameterization in generative models. Every normal probability reduces to .
Even moments follow from the gamma function: with ,
and odd moments are by symmetry. Thus and , the reference kurtosis (skewness and kurtosis). All normal moments exist and depend only on variance; this is special, explaining why many results for a normal do not survive other laws.
The normal tail is particularly useful. Since has no closed form, we need bounds that do.
Proof
Upper bound: for , , hence because . Lower bound: , so ; rearrange to obtain the result.
∎The bounds converge as grows: the Gaussian tail decays as (with correction ). At the tail is , between and . Probabilities beyond standard deviations are for , for and for , and the quantile leaving split between both tails is . Compare earlier and later laws: an exponential exceeds standard deviations above its mean with probability , about fourteen times normal tail . This difference in tail decay rate classifies laws, as studied next.
Three reasons explain why normals appear everywhere, proved in later lessons: they are limits of normalized sums with finite variance (central limit theorem), closed under affine transformations and independent sums, and standard multivariate normals are rotationally invariant (rotational invariance), yielding all geometric results about the multivariate Gaussian.
Heavy tails: Cauchy, Student , Pareto and log-normal
Normal, exponential and Laplace tails decay exponentially or faster. Some laws have much heavier tails, so heavy that moments may not exist. Examples include financial losses, file sizes, API response times under load, or follower counts.
Cauchy, and Pareto are power laws: their tails decay as a power of , with for Cauchy and for . The log-normal decays faster than any power but slower than any exponential. A formula turns the question of existing moments into a tail integral.
Proof
The formula: , exchanging expectation and integral by Tonelli (nonnegative integrand). (1) for and afterward, so , converging if and only if and then equal to . (2) Density of behaves as as , so converges at infinity if and only if ; variance and kurtosis follow by calculating moments using representation . (3) . (4) Moments are those of , namely (complete the square). But grows faster than decays as , because , so the integral defining diverges.
∎One relationship organizes the picture: Pareto is the exponential of an exponential. If then because , just as log-normal is the exponential of a normal. This is the same mechanism backward: logarithms turn a heavy tail into a light tail, explaining why prices and times are often modeled on a log scale.
What breaks when a moment does not exist
Statistics’ great theorems have moment assumptions, which fail with heavy tails in three progressive ways.
- No mean (Cauchy, Pareto with ): the average of observations does not stabilize. Cauchy is worst: the average of independent copies has the same law as one observation (proved using the characteristic function, , unchanged by averaging), so more data do not help. For Pareto with , the mean grows without bound in jumps, as (and as in boundary case ).
- Mean but no variance ( for Pareto, for ): the law of large numbers still holds (sample mean converges to the mean), but error no longer decays as and Gaussian confidence intervals are invalid.
- Variance but no fourth moment ( for Pareto, for ): the mean works and sample variance converges, but fluctuates enormously because its own variance involves the fourth moment. The cell below shows with : sample variance swings between and (true value ), while a normal’s stays between and .
The common feature is the big-jump principle: in a sum of heavy-tailed variables, a single term can contribute a non-negligible fraction of the total. This is measured by the right panel of Running mean and the final column of the cell below: with Pareto and observations, the largest absolute term exceeds half the sum of absolute values; with a normal, roughly five hundred-thousandths.
Relationship map and library parameterizations
The opening map summarizes relationships, with some more lacking their own figure: sums of independent normals are normal; the square of is Snedecor ; geometric and exponential are the only memoryless laws; negative binomial is a Poisson mixture with gamma intensity (the mixtures lesson proves this and explains overdispersed counts). For code, every library parameterizes each law differently and errors are silent. The table gives verified conventions: SciPy and NumPy in cells below, PyTorch against those.
| Law (lesson convention) | scipy.stats | numpy.random.Generator | torch.distributions |
|---|---|---|---|
expon(scale=1/lam) | exponential(scale=1/lam) | Exponential(rate=lam) | |
gamma(a=alpha, scale=1/beta) | gamma(shape=alpha, scale=1/beta) | Gamma(concentration=alpha, rate=beta) | |
chi2(df=k) | chisquare(k) | Chi2(df=k) | |
beta(a, b) | beta(a, b) | Beta(a, b) | |
dirichlet(alpha) | dirichlet(alpha) | Dirichlet(alpha) | |
binom(n, p) | binomial(n, p) | Binomial(n, probs=p) | |
poisson(mu=lam) | poisson(lam=lam) | Poisson(rate=lam) | |
| Geometric, trials (from ) | geom(p) | geometric(p) | unavailable |
| Geometric, failures (from ) | geom(p, loc=-1) | geometric(p) - 1 | Geometric(probs=p) |
| , failures | nbinom(n=r, p=p) | negative_binomial(r, p) | NegativeBinomial(total_count=r, probs=1-p) |
hypergeom(M=N, n=K, N=n) | hypergeometric(ngood=K, nbad=N-K, nsample=n) | unavailable | |
laplace(loc=mu, scale=b) | laplace(mu, b) | Laplace(mu, b) | |
norm(loc=mu, scale=sigma) | normal(mu, sigma) | Normal(mu, sigma) | |
| Log-normal | lognorm(s=sigma, scale=exp(mu)) | lognormal(mean=mu, sigma=sigma) | LogNormal(mu, sigma) |
t(df=nu) | standard_t(nu) | StudentT(df=nu) | |
| Cauchy | cauchy(loc=mu, scale=s) | standard_cauchy() | Cauchy(mu, s) |
pareto(b=alpha, scale=xm) | xm * (1 + pareto(alpha)) | Pareto(scale=xm, alpha=alpha) |
Four cases are especially dangerous. In hypergeom the first argument is population, second the number of successes in the urn, third the number of draws (in that order, unlike the usual formula). scipy.stats.lognorm asks for and scale , not . NumPy’s pareto is the Lomax law, starting at (add and multiply by ). PyTorch’s negative binomial counts successes before total_count failures, with probs the success probability: to count failures before successes, pass .
Implementation from scratch
First the generators. All start from uniforms and follow the relevant story: inversion of the distribution function for exponential, geometric, Cauchy and Pareto (the probability integral transform with quantile function), sums for binomial and integer-shape gamma, differences for Laplace, and normalized gammas for beta and Dirichlet. Real-shape gamma uses Marsaglia and Tsang’s method, accepting or rejecting a transformed normal (also obtained here by inversion). They are checked against scipy.stats with Kolmogorov–Smirnov distance, chi-squared tests for discrete laws and QQ plots.
import numpy as np
from scipy import stats
from scipy.special import ndtri # inversa de la función de distribución normal
import matplotlib.pyplot as plt
rng = np.random.default_rng(7)
def U(size):
"""Uniformes en el intervalo abierto (0, 1): nunca 0 ni 1, así que log y ndtri son seguros."""
return rng.integers(1, 2**53, size=size) / 2.0**53
# 1) por inversión: X = F^{-1}(U)
def exponencial(lam, size):
return -np.log(U(size)) / lam
def geometrica(p, size):
"""Fracasos antes del primer éxito (soporte 0, 1, 2, ...): P(G = k) = p (1 - p)^k."""
return np.floor(np.log(U(size)) / np.log1p(-p)).astype(int)
def cauchy(size):
return np.tan(np.pi * (U(size) - 0.5))
def pareto(alpha, size, xm=1.0):
return xm * U(size) ** (-1 / alpha)
# 2) por sumas y diferencias
def binomial(n, p, size):
return (U((size, n)) < p).sum(axis=1)
def gamma_entera(k, size, lam=1.0):
return exponencial(lam, (size, k)).sum(axis=1)
def laplace(b, size):
return exponencial(1 / b, size) - exponencial(1 / b, size)
# 3) gamma de forma cualquiera (Marsaglia-Tsang con rechazo, vectorizado) y, con ella, beta y Dirichlet
def gamma(a, size):
if a < 1: # G(a) = G(a + 1) U^{1/a}
return gamma(a + 1, size) * U(size) ** (1 / a)
d = a - 1 / 3
c = 1 / np.sqrt(9 * d)
out = np.empty(size)
pend = np.arange(size)
while pend.size:
x = ndtri(U(pend.size)) # normal por inversión
v = (1 + c * x) ** 3
u = U(pend.size)
ok = v > 0
acc = ok & (np.log(u) < 0.5 * x**2 + d * (1 - v + np.log(np.where(ok, v, 1.0))))
out[pend[acc]] = d * v[acc]
pend = pend[~acc]
return out
def beta(a, b, size):
x, y = gamma(a, size), gamma(b, size)
return x / (x + y)
def dirichlet(alpha, size):
g = np.stack([gamma(a, size) for a in alpha], axis=1)
return g / g.sum(axis=1, keepdims=True)
# verificación: distancia de Kolmogorov-Smirnov contra scipy.stats (continuas) y chi-cuadrado (discretas)
n = 20_000
casos = [
("exponencial(2)", exponencial(2.0, n), stats.expon(scale=1 / 2.0)),
("Cauchy", cauchy(n), stats.cauchy()),
("Pareto(1.5)", pareto(1.5, n), stats.pareto(1.5)),
("Laplace(b=1.5)", laplace(1.5, n), stats.laplace(scale=1.5)),
("gamma(k=4)", gamma_entera(4, n), stats.gamma(4)),
("gamma(a=0.4)", gamma(0.4, n), stats.gamma(0.4)),
("gamma(a=3.7)", gamma(3.7, n), stats.gamma(3.7)),
("beta(2, 5)", beta(2, 5, n), stats.beta(2, 5)),
]
for nombre, x, ley in casos:
ks = stats.kstest(x, ley.cdf)
print(f"{nombre:16s} KS = {ks.statistic:.4f} p = {ks.pvalue:.2f}")
for nombre, x, ley in [("binomial(20, 0.3)", binomial(20, 0.3, n), stats.binom(20, 0.3)),
("geométrica(0.3)", geometrica(0.3, n), stats.geom(0.3, loc=-1))]:
obs = np.bincount(x, minlength=40)[:40]
esp = n * ley.pmf(np.arange(40))
m = esp > 5 # solo celdas con frecuencia esperada > 5
chi2 = ((obs[m] - esp[m]) ** 2 / esp[m]).sum()
print(f"{nombre:16s} chi2 = {chi2:6.1f} con {m.sum() - 1} g.l. p = {stats.chi2.sf(chi2, m.sum() - 1):.2f}")
# gráficos QQ: cuantiles de la muestra frente a los de la ley, entre los percentiles 1 y 99
q = np.linspace(0.01, 0.99, 99)
fig, axs = plt.subplots(2, 4, figsize=(8.6, 4.2))
for ax, (nombre, x, ley) in zip(axs.ravel(), casos):
ax.plot(ley.ppf(q), np.quantile(x, q), ".", ms=3)
lim = [ley.ppf(0.01), ley.ppf(0.99)]
ax.plot(lim, lim, "k--", lw=0.8)
ax.set_title(nombre, fontsize=8)
ax.tick_params(labelsize=6)
fig.tight_layout()
plt.show()Kolmogorov–Smirnov distances lie between and , with values that do not reject, and both discrete laws pass chi-squared tests: the generators reproduce laws of scipy.stats. QQ plots follow the diagonal, including Cauchy and Pareto between percentiles and (beyond that the tail is a lottery, studied next). Note the requirements: one line for inversion laws, a sum for derived laws and a rejection loop for real-shape gamma.
The second cell measures total variation between binomial and Poisson and verifies gamma duality. Pmfs are computed on a log scale using math.lgamma to avoid overflow for large .
import math
import numpy as np
def logpmf_binom(n, p, k):
return math.lgamma(n + 1) - math.lgamma(k + 1) - math.lgamma(n - k + 1) + k * math.log(p) + (n - k) * math.log1p(-p)
def logpmf_pois(lam, k):
return -lam + k * math.log(lam) - math.lgamma(k + 1)
def tv_binom_pois(n, lam, kmax=200):
"""Distancia de variación total (1/2) sum_k |Bin(n, lam/n)(k) - Pois(lam)(k)|, sumando hasta kmax."""
p = lam / n
s = 0.0
for k in range(kmax + 1):
b = math.exp(logpmf_binom(n, p, k)) if k <= n else 0.0
s += abs(b - math.exp(logpmf_pois(lam, k)))
return s / 2
lam = 3.0
print(f"{'n':>7s} {'TV exacta':>10s} {'cota lam^2/n':>13s} {'cota afinada':>13s} {'n * TV':>8s}")
for n in [10, 30, 100, 1000, 10_000]:
tv = tv_binom_pois(n, lam)
print(f"{n:7d} {tv:10.6f} {min(1, lam**2 / n):13.4f} {lam * (1 - math.exp(-lam / n)):13.4f} {n * tv:8.4f}")
# dualidad Poisson-gamma: Pr(Gamma(k, lam) <= t) = Pr(Pois(lam t) >= k)
def pois_sf(mu, k):
return 1 - sum(math.exp(logpmf_pois(mu, j)) for j in range(k))
def gamma_cdf_entera(k, lam, t):
"""Pr(Gamma(k, lam) <= t): regla de Simpson sobre la densidad lam^k x^(k-1) e^(-lam x)/(k-1)!."""
xs = np.linspace(0, t, 2001)
f = lam**k * xs ** (k - 1) * np.exp(-lam * xs) / math.factorial(k - 1)
h = xs[1] - xs[0]
return h / 3 * (f[0] + f[-1] + 4 * f[1:-1:2].sum() + 2 * f[2:-1:2].sum())
print("\nPr(la 3.ª alerta llega antes de 1 día), con tasa 3 al día:")
print(" integral de la densidad gamma :", round(gamma_cdf_entera(3, 3.0, 1.0), 6))
print(" Pr(Poisson(3) >= 3) :", round(pois_sf(3.0, 3), 6))
print(" 1 - 8.5 e^{-3} :", round(1 - 8.5 * math.exp(-3), 6))Column stabilizes at : error decays exactly as , and bound remains about twelve times larger. The final three lines agree: the density integral of to , the Poisson tail with mean and the closed-form calculation equal .
The third cell runs the heavy-tail experiment with NumPy’s generator: running means, fraction contributed by the largest term and sample-variance instability.
import numpy as np
rng = np.random.default_rng(3)
N = 200_000
ks = np.array([10, 100, 1_000, 10_000, 100_000])
def resumen(nombre, x):
media = np.cumsum(x) / np.arange(1, len(x) + 1)
mayor = np.maximum.accumulate(np.abs(x)) / np.cumsum(np.abs(x)) # fracción de la suma que aporta el mayor sumando
print(f"{nombre:11s}" + "".join(f"{media[k - 1]:10.3f}" for k in ks) + f"{mayor[ks[-1] - 1]:12.3f}")
print(f"{'media en k =':11s}" + "".join(f"{k:10d}" for k in ks) + " mayor/suma")
resumen("normal", rng.standard_normal(N))
resumen("t (3 g.l.)", rng.standard_t(3, N))
resumen("Cauchy", rng.standard_cauchy(N))
resumen("Pareto 3", 1 + rng.pareto(3.0, N)) # numpy.pareto es Lomax: sumar 1 da la Pareto con x_m = 1
resumen("Pareto 1.5", 1 + rng.pareto(1.5, N))
resumen("Pareto 0.8", 1 + rng.pareto(0.8, N))
print("\nmedias teóricas: Pareto(3) = 1.5, Pareto(1.5) = 3, Pareto(0.8) = infinita; t3 = 0; Cauchy no existe")
# la varianza muestral de una ley con cuarto momento infinito converge, pero con fluctuaciones enormes
v_n = [rng.standard_normal(10_000).var(ddof=1) for _ in range(200)]
v_t = [rng.standard_t(3, 10_000).var(ddof=1) for _ in range(200)]
print("\nvarianza muestral con 10^4 datos, 200 repeticiones (teórica 1 y 3):")
print(f" normal : media {np.mean(v_n):.3f} rango [{min(v_n):.3f}, {max(v_n):.3f}]")
print(f" t_3 : media {np.mean(v_t):.3f} rango [{min(v_t):.3f}, {max(v_t):.3f}]")Read rows with the three-breakdown traffic light. Normal and converge to (the latter more slowly). Pareto means with and approach and , though does so in jumps. Cauchy’s mean still jumps with observations, while Pareto converges nowhere: it jumps between and without settling, and the largest term exceeds half the total. Exact values change with the seed; behavior does not.
The professional version
In real use there is no need to program the above: numpy.random.Generator and scipy.stats supply it, leaving the table’s conventions as the difficulty. The first cell samples a Dirichlet via normalized NumPy gammas and verifies the theorem’s formulas: means, covariances, marginals, aggregation and the sparse regime.
import numpy as np
from scipy import stats
def dirichlet_gammas(alpha, n, rng):
"""n muestras de Dirichlet(alpha) como gammas independientes normalizadas."""
g = rng.gamma(shape=np.asarray(alpha, dtype=float), size=(n, len(alpha)))
return g / g.sum(axis=1, keepdims=True)
rng = np.random.default_rng(11)
alpha = np.array([2.0, 3.0, 5.0])
a0 = alpha.sum()
X = dirichlet_gammas(alpha, 200_000, rng)
media_t = alpha / a0
cov_t = (np.diag(alpha * a0) - np.outer(alpha, alpha)) / (a0**2 * (a0 + 1))
print("media muestral :", np.round(X.mean(axis=0), 4), " teórica:", media_t)
print("covarianza muestral:\n", np.round(np.cov(X.T), 5))
print("covarianza teórica :\n", np.round(cov_t, 5))
print("las filas suman 1 (error máximo):", np.abs(X.sum(axis=1) - 1).max())
# agregación: X1 + X2 ~ Beta(a1 + a2, a3); marginal: X1 ~ Beta(a1, a0 - a1)
print("KS de X1 + X2 contra Beta(5, 5):", round(stats.kstest(X[:, 0] + X[:, 1], stats.beta(5, 5).cdf).statistic, 4))
print("KS de X1 contra Beta(2, 8) :", round(stats.kstest(X[:, 0], stats.beta(2, 8).cdf).statistic, 4))
# independencia entre la suma de las gammas y la proporción (la base del resultado): correlación ~ 0
g = rng.gamma(shape=[2.0, 3.0], size=(100_000, 2))
print("corr(G1 + G2, G1/(G1 + G2)) =", round(np.corrcoef(g.sum(axis=1), g[:, 0] / g.sum(axis=1))[0, 1], 4))
# régimen disperso: con alpha pequeño casi toda la masa se concentra en una componente
for a in (0.05, 0.3, 1.0, 10.0):
Y = dirichlet_gammas([a] * 5, 50_000, rng)
print(f"alpha = {a:5.2f} en 5 componentes: Pr(max > 0.9) = {np.mean(Y.max(axis=1) > 0.9):.3f} media del mayor = {Y.max(axis=1).mean():.3f}")Sample covariances agree with to the third digit (with , ); Kolmogorov–Smirnov distances for marginals and aggregation are of order and correlation between sum and proportion is virtually zero, confirming the theorem’s independence. The final lines show the sparse regime: with five components and , of samples have one component above .
Conventions of scipy.stats and NumPy are checked by pointwise comparison asserts against lesson formulas.
import numpy as np
from scipy import stats
x = np.linspace(0.3, 6, 7)
lam, forma, tasa = 0.5, 3.0, 2.0 # tasa de la exponencial; forma y tasa de la gamma
# (densidad en la convención de la lección, densidad de scipy.stats): deben coincidir punto a punto
pares = {
"exponencial(tasa 0.5)": (lam * np.exp(-lam * x), stats.expon(scale=1 / lam).pdf(x)),
"gamma(forma 3, tasa 2)": (tasa**forma * x**(forma - 1) * np.exp(-tasa * x) / 2.0, stats.gamma(forma, scale=1 / tasa).pdf(x)),
"Pareto(alpha 1.5, x_m 2)": (1.5 * 2.0**1.5 / x**2.5 * (x >= 2.0), stats.pareto(1.5, scale=2.0).pdf(x)),
"log-normal(mu 0.3, sigma 0.8)": (np.exp(-0.5 * ((np.log(x) - 0.3) / 0.8) ** 2) / (x * 0.8 * np.sqrt(2 * np.pi)),
stats.lognorm(s=0.8, scale=np.exp(0.3)).pdf(x)),
"Laplace(mu 1, b 2)": (np.exp(-np.abs(x - 1) / 2) / 4, stats.laplace(loc=1, scale=2).pdf(x)),
}
for nombre, (a, b) in pares.items():
print(f"{nombre:31s} diferencia máxima: {np.abs(a - b).max():.1e}")
# las discretas: soporte y significado de cada argumento
p = 0.3
print("\nstats.geom cuenta ENSAYOS (soporte 1, 2, ...): pmf(1) =", stats.geom(p).pmf(1), " pmf(0) =", stats.geom(p).pmf(0))
print("para contar FRACASOS, loc=-1 (soporte 0, 1, ...): pmf(0) =", stats.geom(p, loc=-1).pmf(0))
print("stats.nbinom(r, p) cuenta FRACASOS antes del r-ésimo éxito: media =", stats.nbinom(3, 0.4).mean(), " = r (1 - p)/p =", 3 * 0.6 / 0.4)
print("stats.hypergeom(M=N, n=K, N=extracciones): P(4 éxitos) =", round(stats.hypergeom(50, 20, 10).pmf(4), 5), " (urna de 50, 20 éxitos, 10 extracciones)")
print("stats.poisson(mu=lambda): P(0) con lambda = 3 =", round(stats.poisson(3).pmf(0), 5))
# NumPy: exponential y gamma piden la ESCALA (1/tasa); geometric cuenta ensayos; pareto es Lomax
rng = np.random.default_rng(0)
print("\nmedia de rng.exponential(scale=2):", round(rng.exponential(scale=2, size=200_000).mean(), 3), " (tasa 0.5, media 2)")
print("media de rng.gamma(3, scale=0.5): ", round(rng.gamma(3, scale=0.5, size=200_000).mean(), 3), " (forma 3, tasa 2, media 1.5)")
print("mínimo de rng.geometric(0.3): ", rng.geometric(0.3, size=1000).min(), " (cuenta ensayos: empieza en 1)")
print("mínimo de rng.pareto(1.5): ", round(rng.pareto(1.5, size=1000).min(), 4), " (Lomax: empieza en 0; la Pareto es 1 + Lomax)")In PyTorch the same laws live in torch.distributions, with rsample for differentiable sampling (reparameterization: is simulated as , and gradients pass through and ). With the table above, these two lines are equivalent to SciPy’s:
import torch
from torch import distributions as D
espera = D.Exponential(rate=torch.tensor(0.5)) # media 2, tasa 0.5 (scipy: expon(scale=2))
gam = D.Gamma(concentration=torch.tensor(3.0), rate=torch.tensor(2.0)) # media 1.5
prop = D.Dirichlet(torch.tensor([2.0, 3.0, 5.0])).rsample((1000,)) # filas en el símplex, con gradiente
Common mistakes
Exercises
Step 1 of 4. How is rewritten to take limits with fixed?
Step 1 of 4. What follows from the equation at and ?
More than one answer may be correct.
sample_dirichlet(alpha, n, rng), returning an array of shape (n, K) with n samples from (each row sums to ), using normalized gammas. It must work with very small parameters: with NumPy gammas underflow toward (almost all are exactly ), and normalization gives nan. To avoid this, work with logarithms: for , , with uniform , and normalize by subtracting the maximum before exponentiating. Verify means are and covariances match the theorem.import numpy as np
def sample_dirichlet(alpha, n, rng):
"""n muestras de Dirichlet(alpha) como gammas independientes normalizadas."""
alpha = np.asarray(alpha, dtype=float)
g = rng.gamma(shape=alpha, size=(n, alpha.size))
# esta versión ingenua falla con alpha pequeño: reescríbela con logaritmos
return g / g.sum(axis=1, keepdims=True)Summary
- Bernoulli, binomial, geometric, negative binomial and multinomial count outcomes of independent trials; hypergeometric is the no-replacement version, with variance reduced by and a binomial limit as .
- , with total-variation error at most (Le Cam); Poisson has equal mean and variance, and overdispersed counts (variance exceeding mean) are modeled by negative binomial.
- The exponential is the unique continuous memoryless law (constant hazard); sums of gammas with the same rate are gamma, and ratio is beta independent of the sum. Thus , Dirichlet is a normalized gamma vector, and duality links waiting times and counts.
- Laplace is the difference of two exponentials; its likelihood leads to absolute value: the median estimates location, and lasso and the differential-privacy Laplace mechanism follow.
- All normals are standard up to location and scale (standardization, ); normal has all moments and tail . Rate versus scale, failure-counting versus trial-counting geometrics, and arguments of
hypergeom,lognormandparetoare the most frequent code errors. - In heavy tails, moment of order exists if and only if : Pareto with index , ; , ; Cauchy, only , hence no mean. Without a mean, the average does not converge; and because log-normal with large mimics a straight log–log line, a line does not prove a power law.