Statistical models and sampling distributions
Establish the language of inference: a statistical model is a family of distributions indexed by a parameter, and a statistic is a sample function whose sampling distribution quantifies variation when the experiment is repeated. Construct sampling distributions by simulation and derive exact ones for normal samples (χ², Student’s t, and F), the basis of classical intervals and tests.
After this lesson you can
- Formulate an applied problem as a parametric, semiparametric, or nonparametric statistical model and check parameter identifiability.
- Simulate an arbitrary statistic’s sampling distribution and estimate its standard error with its own Monte Carlo error.
- Derive χ², t, and F distributions from normals and prove independence of X̄ and S² in normal samples.
- Explain why studentization changes the normal to a t distribution and when this matters in practice.
Before you start
- 05Summary statistics
- 04Independent random variablesChange of variables for densitiesLaw of a random variable (pushforward measure)Multivariate Gaussian distributionAffine transformations of GaussiansWeak law of large numbersStrong law of large numbersCentral limit theorem
- 02Orthogonal matrixOrthogonal projectionProjection matrix
Motivation: a number is not a conclusion
You train two variants of a model and evaluate them on the same validation set of examples. Variant A gets mean loss and B gets . Is B better? Would A have won on another validation sample? The mean of numbers is a number, but one depending on which examples were drawn, and the question cannot be answered until we know how much it would have changed with another sample.
That is inferential statistics in a sentence: quantify the variability of what you calculate so you can distinguish information in the observations from sampling chance. The entire module (intervals, tests, bootstrap, Bayesian methods, linear models) rests on two objects fixed in this lesson:
- a statistical model, stating which probability laws we consider possible for the data and which part of the law we want to know (the parameter);
- the sampling distribution of a statistic, describing how the calculated number would be distributed if we repeated the experiment. From it comes the standard error, the error bar accompanying any serious figure.
A third, subtler thread: under normality, these sampling distributions can be calculated exactly for any , not just in the limit. They yield , Student’s , and , the basis of classical intervals and tests, all obtained from one geometric idea: an orthogonal rotation.
Four questions structure the lesson.
- What exactly is a model, and when is a parameter recoverable from data (identifiability)?
- What is a sampling distribution, and how can simulation obtain it for any statistic?
- What is the standard error, and what is it not (it is not the spread of the data)?
- What changes when is unknown and estimated from the same sample?
A note on prerequisites. We expect the descriptive statistics review (mean, sample variance, median) and probability from module 4: independence, change of variables for densities, multivariate Gaussian and its affine transformations. Data will always be independent and identically distributed (iid), and , unless otherwise stated.
Intuition: repeat the experiment
Before definitions, a thought experiment. A population (a probability law) supplies observations. From these observations calculate a number: a mean, maximum, or percentile. Record it, discard the sample, draw another, and repeat. The recorded numbers form a histogram, and this histogram, never actually seen in practice (there is only one sample), governs how much the observed number can be trusted.
What you should have seen:
- A normal mean narrows as . With the histogram centers near with standard deviation . On the lower graph points follow slope : whenever is multiplied by , spread is divided by . For the graph (with replicates per point, or about relative error) gives , while gives .
- Each statistic has its own sampling distribution, and its width depends on the population. The normal median behaves like the mean, but worse: its standard deviation is versus . For the exponential, mean and median tie. For a bimodal population (two separated peaks), the median is much worse than the mean: at median standard deviation is about and mean standard deviation about , because the median lies in the valley between peaks, where data are scarce, and jumps from one to the other.
- Some statistics’ variability does not decrease as . The maximum of a rate- exponential has variance exactly , increasing toward : its standard deviation rises from at to almost (, that of the Gumbel law) and stays there. The maximum grows (as ), but does not concentrate. The normal maximum narrows, but exasperatingly slowly: its standard deviation falls from at to at (asymptotically, , giving at ).
- In some cases there is not even a width to measure. Pareto with has finite mean and infinite variance. Simulated standard deviation of the mean does not stabilize (it jumps across and seeds): there is no standard error to report because the sample mean has no variance. The maximum is worse: its scale grows with , as , and also has no finite variance, so its simulated standard deviation grows in jumps. The mean’s histogram nevertheless exists and is an asymmetric law with a long tail.
- The 95th percentile and sample variance narrow with slope (sample variance if the population has a finite fourth moment; percentile if density is positive at the quantile), but starting with greater spread. Sample-variance standard deviation for an exponential at is (simulation gives with replicates), almost three times that of the mean (): estimating variance is harder than estimating a mean.
The figure gives an operational lesson. A number calculated from a sample is one draw from the sampling distribution, whose width depends on three things: statistic, population, and . The rest of the lesson formalizes this idea (sections on models, sampling distributions, and standard error), learns to calculate widths by simulation and, for the normal case, exactly.
Statistical model: a family of possible laws
An observation is a realization of random variable whose law is unknown. A model explicitly states which laws are candidates. It is not a claim that nature is like this: it is the set of hypotheses among which data will choose.
Classification by the size of organizes the module.
- Parametric model: with finite . Examples: Bernoulli with ; normal with ; exponential with rate ; logistic regression with ; a neural network with , where comprises millions of weights. There is much to learn from few numbers.
- Nonparametric model: is infinite-dimensional. The basic example is = all laws on with finite second moment. Mean is no longer a coordinate of but a functional of the law. Few assumptions are made at the cost of precision.
- Semiparametric model: a finite-dimensional parameter of interest and an infinite-dimensional nuisance parameter. A typical example is with and unspecified law of ; is of interest and the error law is nuisance. Another is Cox’s proportional hazards model, estimating effect without modeling the baseline hazard function.
Fixing the model is the most important modeling decision because it determines which questions can be answered. Two nuances recur later. First, the parameter of interest may be only part or a function of : for a normal, but often only matters (with as nuisance). Second, “well specified” is an idealization: “all models are wrong, but some are useful” (Box). What happens to an estimator when the true law is not in is the subject of lesson 8 (sandwich variance, misspecified MLE).
A model is more than a family: it also fixes data structure. The iid assumption itself is part of the model and the first violated in practice (time series, repeated users, grouped data). The following sections assume iid; whenever they do, they use a model assumption, not a fact.
Identifiability: can data distinguish two parameters?
A parameter is useful if data can, at least in principle, distinguish it from another. If two different values give exactly the same data law, no amount of data can decide between them.
The key phrase is “data law,” not “data.” This is not a small-data problem: it is a property of the parameterization and more samples do not fix it. Examples:
- Redundant parameters. In only product matters. Pairs and give the same law, so is not identifiable; is. This is the same phenomenon as ReLU-network scale symmetry: multiplying one layer by and the next by leaves the function intact, so individual network weights have no separate “meaning.”
- Mixtures with interchangeable labels. In , parameters and give the same law (label switching). The parameterization is identifiable only up to permutation, fixed by imposing an order such as .
- Signs and scales. parameterized by with is not identifiable: and yield the same law. With it is identifiable.
- Collinearity. In with linearly dependent columns of , is not identifiable: and , with , give the same mean. The combinations are identifiable, that is, estimable.
- An identifiable case. An exponential with rate : is injective, because recovers .
The important consequence is an impossibility result.
Proof
Since , also , and the law of is the same under both parameters. If under , then for every , and that probability depends only on the law of : the same holds under . If also under , the probability limit of would be both and , and probability limits are unique up to probability-zero sets: , a contradiction.
∎The next figure makes this visible with model . The sum of squares depends only on : it is , with and the least-squares estimate of .
What you should have seen:
- All descents end on the hyperbola, at different points. The table’s “c = ab” column is the same (to three decimals) in every row, as is final SSE: it is minimal. But “final a” and “final b” change between runs; what changes is the starting point, not data. There is not one minimum but a curve of minima.
- The optimizer does not choose randomly: it preserves an invariant. The gradient flow of preserves , because and give . Small-step descent nearly preserves it (visible in the “ (invariant)” readout, stable near its starting value). Thus initialization decided the reported pair. Publishing “, ” publishes an artifact.
- The Hessian exposes it. At the optimum, , a rank-one matrix: eigenvalues and . The zero eigenvalue is the tangent direction to the ridge, where loss does not change. With parameter , the Hessian is scalar : positive curvature, unique minimum, standard error (the readout updates when noise or data change).
- What to do. Switch to an identifiable parameterization (), impose a constraint selecting one point (, or with ), or add information (a prior or penalty selecting within the ridge). What cannot be done is interpret and separately.
There is a local version of this idea, developed with Fisher information: a parameter is locally identifiable if the information matrix is regular. In the figure, the rank-one Hessian signals that it is not.
Statistics and sampling distributions
A statistic is a function of data that does not depend on the unknown parameter: with measurable . Mean , median, maximum, , and a percentile are statistics. Difference is not, because is unknown (it is called a pivotal quantity when its law does not depend on the parameter, the subject of lesson 9).
Since the data are random, is a random variable and its law depends on the true parameter.
It is a theoretical object: it describes what would do in infinitely many repetitions of the experiment, while in practice only one value is observed. There are only three ways to know it.
- Exactly, by calculation. Possible in few cases: the normal mean (with , immediate from affine transformations) and the normal theory below.
- Approximately, by asymptotic theory. By the central limit theorem, for large , for any finite-variance population. This is generalized (MLE, delta method) in lesson 8.
- By simulation, generating many samples from the model at a parameter value and calculating the statistic on each. This is what the figure above did, formalized in the simulation section.
The dependence on deserves a warning: the sampling distribution is calculated assuming is known (or using a candidate value), whereas in practice is what we want to discover. All inference is an organized way around that circle: estimate missing (plug-in), find a pivot independent of it ( intervals), evaluate every candidate (tests), or replace the population law with the empirical one (bootstrap).
Standard error
Of the whole sampling distribution, width is most needed: it says how far the statistic would typically deviate from its central value on repetition of the experiment.
The fundamental case is the mean. If are iid with mean and variance , the variance of a sum of independent variables gives
This is the figure’s slope. Since is unknown, estimate it with and report . The justification is that unbiasedly estimates . (Caution: is biased as an estimator of ; by Jensen’s inequality, . Relative bias is order and vanishes as grows, but “unbiased” describes , not .)
Proof
With , . Since and ,
Dividing by gives . (Dividing by would give : the sample mean fits data better than the true mean, so residuals underestimate spread.)
∎Two common mistakes recur in the exercises. First, data standard deviation and standard error are different things.
| (sample standard deviation) | (standard error) | |
|---|---|---|
| Measures | how much observations vary from each other | how much the mean would vary across samples |
| As grows | converges to and stays there | shrinks as |
| Doubling | unchanged (except noise) | divided by |
| Used to | describe data | quantify estimator uncertainty |
With observations and (for example, latencies in milliseconds), each observation deviates about ms from the mean, but the mean of is ms from the true mean. To halve standard error requires four times more data, not twice as much.
Second, not all standard errors are . Each statistic has its own. For the mean it is exact; for others it is known only asymptotically. The key example is the median.
Proof
Fix and let . Then is equivalent to except on an event whose probability tends to zero (depending on how median is defined for even , the threshold is or , and ). Since with ,
The right side of the inner inequality converges to . The left side is a standardized sum of Bernoulli variables with parameter (a triangular array of bounded variables), converging to by Lindeberg-Feller. Thus , the distribution function of .
∎For a normal, and : more than the mean, as shown in the figure. For the bimodal, is tiny (the median is in the valley), asymptotic spread is enormous, and the formula describes median behavior only from a very large : at it predicts while simulation gives . A useful warning: do not blindly apply an asymptotic standard-error formula at moderate .
Simulation: the general recipe and its own precision
When no formula exists (a ratio of means, maximum, machine-learning statistic, evaluation metric), simulate. The recipe is always the same.
Recipe. Fix a parameter value (or a law ). For : generate and calculate . The values are an iid sample from the sampling distribution, and everything desired about it is estimated from them: mean, standard deviation (simulated standard error), and quantiles.
This is the figure above. A frequently forgotten point: simulation has its own error. With finite , simulated standard error is another statistic with its own sampling distribution. Its precision can be quantified.
Three practical consequences. (i) Simulated SE precision improves as : one more digit of precision requires times more replicates. (ii) The heavier the sampling-distribution tails (larger kurtosis ), the worse the estimate. (iii) Every simulated figure needs its Monte Carlo error: error of a simulated mean is , that of a probability is , and that of a standard deviation is above. “It came out ” without precision is an anecdote, not a measurement. (Fixing the generator seed is also a matter of reproducibility.)
Implementation from scratch
The function below is the generic simulator: it receives how to generate the population, which statistic to calculate, and , and returns the simulated sampling distribution, its standard error, and the latter’s Monte Carlo error. It is vectorized by generating the matrix at once, one sample per row. Use it for a consequential question: among mean, median, and trimmed mean, which has the smallest standard error? Five populations, each with variance for a common comparison.
import numpy as np
from scipy import stats
def distribucion_muestral(generador, estadistico, n, B=10000, rng=None):
"""Simula la distribución muestral de un estadístico.
generador(rng, size) devuelve datos de la población con la forma pedida; estadistico recibe una matriz (B, n)
(una muestra por fila) y devuelve B valores. Devuelve (valores, error estándar simulado, error Monte Carlo del SE)."""
rng = np.random.default_rng() if rng is None else rng
valores = np.asarray(estadistico(generador(rng, (B, n))), dtype=float)
se = valores.std(ddof=1)
kurt = stats.kurtosis(valores, fisher=False) # curtosis (no en exceso) de la distribución muestral
mc = se * np.sqrt((kurt - 1) / (4 * B)) # SE del propio SE: sd(ŝ) ≈ τ·√((κ − 1)/(4B))
return valores, se, mc
s3 = np.sqrt(3)
poblaciones = { # todas con media 0 y varianza 1 (la exponencial, con media 1)
"normal": lambda r, size: r.normal(size=size),
"uniforme": lambda r, size: r.uniform(-s3, s3, size=size),
"Laplace": lambda r, size: r.laplace(scale=1 / np.sqrt(2), size=size),
"t de Student 3": lambda r, size: r.standard_t(3, size=size) / s3,
"exponencial": lambda r, size: r.exponential(size=size),
}
dens_mediana = {"normal": stats.norm.pdf(0), "uniforme": 1 / (2 * s3), "Laplace": 1 / np.sqrt(2),
"t de Student 3": stats.t.pdf(0, 3) * s3, "exponencial": 0.5}
estadisticos = {
"media": lambda m: m.mean(axis=1),
"mediana": lambda m: np.median(m, axis=1),
"media recortada 20 %": lambda m: stats.trim_mean(m, 0.2, axis=1),
}
n, B = 50, 10000
rng = np.random.default_rng(2024)
print(f"√n·SE simulado (n = {n}, B = {B}); entre paréntesis, el error Monte Carlo de esa cifra")
print(f"{'población':16s}" + "".join(f"{e:>24s}" for e in estadisticos) + " 1/(2f(m)) teórico")
for nombre, gen in poblaciones.items():
fila = f"{nombre:16s}"
for est in estadisticos.values():
_, se, mc = distribucion_muestral(gen, est, n, B, rng)
fila += f"{se * np.sqrt(n):17.3f} ({mc * np.sqrt(n):.3f})"
print(fila + f"{1 / (2 * dens_mediana[nombre]):14.3f}")Multiply by so figures can be compared with asymptotic values. The mean column is in every population (Monte Carlo error to ): and by construction. The other columns tell the interesting part.
- No estimator is best for every population. For uniform (no tails) the mean wins easily ( versus for trimmed and for median). For heavy-tailed laws (Laplace and ), median and trimmed mean win by to ( and versus for Laplace; and for ). For normal the mean is best and median loses that ( versus theoretical ).
- The asymptotic formula works reasonably at : it agrees with simulation to or digits for normal ( versus ), exponential ( and ), and ( versus ), with the largest difference for Laplace ( versus ), whose density peaks at the median and whose asymptotic approximation thus takes longer.
- The trimmed mean is insurance: it is never worst of the three, best for and exponential, and loses little to the best ( for normal, for Laplace) except uniform without tails, where it loses . Ranking estimators by variance under different populations is the subject of lesson 4.
Monte Carlo error of to in the table lets us say and are compatible (about two Monte Carlo errors apart, and the formula is only asymptotic), while and (Laplace, over ten Monte Carlo errors) are not.
Exact normal theory: χ², t, and F
Everything above applies to any population. With normal data there is a gift: sampling distributions of , , and studentized statistic can be calculated exactly for every , not just as . Three laws built from the normal are called , , and .
These constructive definitions are useful because they show where the laws come from: a statistic that is a sum of squared normals is ; a ratio of a normal to the square root of an independent is ; a ratio of variances is . Their densities follow from the module 4 catalog.
Proof
(a) For : with , , and differentiating gives , the formula at because . The moment generating function is for . For independent summands the product is , that of , and the moment generating function determines the law.
(b) Let independent and and . Conditioning on , is multiplied by constant , with density . Integrating against the density of ,
The integral is gamma-type: it equals . Simplifying powers of ( in numerator, in denominator) leaves the stated formula.
(c) The same trick: condition on the denominator and integrate a gamma. With , , and independent and , ratio has density conditional on , so
because the integral equals . Since , rescaling yields , the stated formula.
∎Most-used properties, following from the definitions or density:
- is the Cauchy, with no mean; has moments only through order . For , . Tails decay as a power, , not exponentially: has heavier tails than the normal.
- as : because , or because (law of large numbers for , a sum of iid squares).
- , and . Thus a two-tailed test is a one-tailed test.
The fundamental theorem: sample mean and variance
Here is the result making all the above useful.
Proof
A rotation. Let . Complete unit vector to an orthonormal basis of (by Gram-Schmidt) and let be the orthogonal matrix with rows . Vector is Gaussian with mean and covariance (affine transformations, or rotational invariance of the standard Gaussian). Its components are therefore : for a Gaussian, uncorrelated means independent.
The first coordinate is the mean. . It is the projection of onto diagonal .
The remaining coordinates are spread. Since preserves norm, . And (decomposition into a part relative to the mean and one for the mean), where . Therefore,
Conclusion. (1) is the affine transformation . (2) is a sum of independent standard normal squares: by definition. (3): is a function of and of , and those coordinates are independent. (4): , with independent of the denominator’s : this defines .
∎The proof is a rotation. In , the cloud of samples is a spherical ball centered at ; the coordinate along the diagonal is , and is squared distance to the diagonal axis. A spherical Gaussian does not distinguish directions (no rotation changes it), so height along the axis and distance from it do not inform one another. See it with , the smallest dimension with something to see.
What you should have seen:
- For normal, the cloud is a ball from every view. Looking along the diagonal (“Along the diagonal”) it is a round disk, and from the side (“Vertical diagonal”) the same disk: the cloud is spherical without preferred direction. The distribution inside the band matches outside regardless of band center: mean is around everywhere (the band captures from about samples at extremes to at the center, so mean noise ranges from to ), and Kolmogorov distance between the two usually stays below the threshold. Also follows an exponential of mean ( with , dashed line).
- For exponential, the cloud has three tails, one per axis, and is round from no view. With centered coordinates, the vertex is at (the minimum possible), and the band changes the distribution. With near its minimum, all three observations hug the floor and is nearly zero; with high one observation must be huge and is large. This can be calculated exactly: conditional on the sum, an exponential sample is uniform on the simplex, yielding in centered coordinates, equal to at and at (the -wide band averages this value: it gives and ). Readouts reflect it: at ( at in the cell below).
- Uncorrelated is insufficient, illustrated by uniform. Uniform is symmetric, so (the readout is near zero), but they are not independent: as approaches an extreme (, with ) all data press against the edge and is small, so , versus at (the band gives and ). Readout detects that nonlinear dependence, and Kolmogorov distance comparing full distributions confirms it.
- What normality is. Independence of and characterizes the normal (Geary-Lukacs theorem): if for iid samples from a finite-variance law and are independent, the law is normal. This is related to Maxwell’s (or Herschel-Maxwell) characterization: among laws with independent coordinates, only the centered Gaussian yields a spherical, rotation-invariant cloud.
One final step, . Given two independent normal samples of sizes and variances , then , by theorem part (2) and the definition of . This gives the variance-equality test, and in the linear model (module 5, lesson 19) the regression-significance .
Numerical verification
Check all this experimentally. Simulate samples of normals with and , and compare with and the statistic with , using densities written from scratch from the theorem’s formulas (no scipy.stats in density calculations) and trapezoidal integration. Then check independence with three populations.
import numpy as np
from math import lgamma, log, pi
from scipy import stats
def densidad_chi2(x, k):
"""χ²_k desde la definición como Gamma(k/2, escala 2)."""
return np.exp((k / 2 - 1) * np.log(x) - x / 2 - (k / 2) * log(2) - lgamma(k / 2))
def densidad_t(x, nu):
"""t de Student: la fórmula que se deduce en la lección."""
c = lgamma((nu + 1) / 2) - lgamma(nu / 2) - 0.5 * log(nu * pi)
return np.exp(c - (nu + 1) / 2 * np.log1p(x ** 2 / nu))
def prob_numerica(dens, a, b, m=4001):
"""∫ dens entre a y b por la regla del trapecio (suficiente aquí)."""
x = np.linspace(a, b, m)
y = dens(x)
return float(np.sum((y[1:] + y[:-1]) / 2 * np.diff(x)))
rng = np.random.default_rng(7)
n, B = 8, 40000
mu, sigma = 3.0, 2.0
X = rng.normal(mu, sigma, size=(B, n))
xbar, s2 = X.mean(axis=1), X.var(axis=1, ddof=1)
Q = (n - 1) * s2 / sigma ** 2 # debería ser χ² con n−1 = 7 grados de libertad
T = np.sqrt(n) * (xbar - mu) / np.sqrt(s2) # debería ser t con 7 grados de libertad
print("χ²_7: media %.3f (teoría 7), varianza %.3f (teoría 14)" % (Q.mean(), Q.var()))
for a, b in [(0, 4), (4, 10), (10, 40)]:
print(f" P({a} < Q < {b}): simulada {np.mean((Q > a) & (Q < b)):.4f} integral de mi densidad {prob_numerica(lambda x: densidad_chi2(x, 7), max(a, 1e-9), b):.4f}")
print("t_7: P(|T| > 2.5): simulada %.4f integral de mi densidad %.4f" % (np.mean(np.abs(T) > 2.5), 1 - 2 * prob_numerica(lambda x: densidad_t(x, 7), 0, 2.5)))
print("p-valor de Kolmogorov-Smirnov frente a χ²_7: %.3f, frente a t_7: %.3f" % (stats.kstest(Q, "chi2", args=(7,)).pvalue, stats.kstest(T, "t", args=(7,)).pvalue))
def correlaciones(gen, mu, B=200000, n=8):
"""corr(X̄, S²) y corr((X̄−μ)², S²) con B muestras de tamaño n."""
x = gen((B, n))
m, v = x.mean(axis=1), x.var(axis=1, ddof=1)
return np.corrcoef(m, v)[0, 1], np.corrcoef((m - mu) ** 2, v)[0, 1]
print("\n corr(X̄, S²) corr((X̄−μ)², S²)")
for nombre, gen, m0 in [("normal", lambda s: rng.normal(size=s), 0.0),
("uniforme", lambda s: rng.uniform(size=s), 0.5),
("exponencial", lambda s: rng.exponential(size=s), 1.0)]:
r1, r2 = correlaciones(gen, m0)
print(f"{nombre:12s} {r1:12.3f} {r2:16.3f}")The output says: simulated has mean and variance (theory: and ), interval probabilities agree with integration of the scratch-written density to two or three digits (Monte Carlo error with is ), tail is simulated and by integration, and neither Kolmogorov-Smirnov test rejects ( and ). The last table is the figure in numbers: for normal, both correlations are zero ( and ); for uniform, linear is zero and nonlinear is (at ); for exponential, both are clearly positive ( and ).
Studentization: why the normal becomes a t
In practice is unknown. If it were known, exactly and interval would cover with probability exactly . Replacing with is studentization (after “Student”), and the ratio’s law ceases to be normal: it is by Fisher’s theorem. The difference is two sources of randomness: numerator and denominator . When happens to be small, the ratio shoots up, and this fluctuation fattens the tails.
The correction is simple: use quantile instead of . For (nine degrees of freedom) it is , more. Coverage of the interval falls short and is calculated exactly: .
What you should have seen:
- With small the difference is huge. At () the quantile is and -interval coverage falls to : intervals advertised as “” fail almost one time in five. At , ; , ; , ; , and , . The correction disappears slowly: coverage error is order .
- The tail is responsible. is for (Cauchy), for , for , for , and for . Normal gives .
- Studentization is not the whole story. With exponential (skewed) data and , even the -quantile interval covers only (and covers ). Exact theory assumes normality: when it fails, and are no longer independent (as the preceding figure showed), and the ratio is no longer . At coverage is () and () for exponentials, and at , and . The CLT and Slutsky’s lemma (continuous mapping) guarantee for any finite-variance population, but not the rate; that depends on skewness, as seen in the CLT.
- Degrees of freedom. is not magic. is squared norm of residual vector , living in the subspace orthogonal to (dimension ): one degree of freedom was spent estimating . It is the same as in unbiasedness of , returning in the linear model as with estimated parameters.
With libraries
scipy.stats implements all three laws with pdf, cdf, ppf (quantiles), and rvs (samples). The next cell checks what we saw: quantiles approach , relationships between laws ( and ), and coverage of pivot-based intervals. Besides one for the mean using , there is one for using , an example of a good pivot yielding an interval.
import numpy as np
from scipy import stats
# 1) Cuantiles: la t se acerca a la normal desde fuera
print(f"{'ν':>5s} {'t_0.975':>9s} {'P(|T|>1.96)':>12s}")
for nu in (1, 2, 4, 9, 29, 99, 1000):
print(f"{nu:5d} {stats.t.ppf(0.975, nu):9.3f} {2 * stats.t.sf(1.96, nu):12.4f}")
print(f"{'∞':>5s} {stats.norm.ppf(0.975):9.3f} {2 * stats.norm.sf(1.96):12.4f}")
# 2) Relaciones entre las tres leyes: T² ~ F(1, ν) y 1/F(d1, d2) ~ F(d2, d1)
nu = 7
print("\nT²~F(1,7): t.ppf(0.975, 7)² = %.5f f.ppf(0.95, 1, 7) = %.5f" % (stats.t.ppf(0.975, nu) ** 2, stats.f.ppf(0.95, 1, nu)))
print("1/F(4,9): 1/f.ppf(0.05, 4, 9) = %.5f f.ppf(0.95, 9, 4) = %.5f" % (1 / stats.f.ppf(0.05, 4, 9), stats.f.ppf(0.95, 9, 4)))
# 3) Cobertura de dos intervalos al 95 % para una media y una varianza normales (n = 10, 20000 muestras)
rng = np.random.default_rng(11)
n, B, mu, sigma = 10, 20000, 5.0, 3.0
X = rng.normal(mu, sigma, (B, n))
xbar, s = X.mean(axis=1), X.std(axis=1, ddof=1)
q = stats.t.ppf(0.975, n - 1)
cubre_mu = np.abs(xbar - mu) <= q * s / np.sqrt(n)
cubre_z = np.abs(xbar - mu) <= 1.96 * s / np.sqrt(n)
lo = (n - 1) * s ** 2 / stats.chi2.ppf(0.975, n - 1) # (n−1)S²/σ² ~ χ²_{n−1}: pivote para σ²
hi = (n - 1) * s ** 2 / stats.chi2.ppf(0.025, n - 1)
cubre_var = (lo <= sigma ** 2) & (sigma ** 2 <= hi)
print(f"\ncobertura del intervalo de μ con t (q = {q:.3f}): {cubre_mu.mean():.4f}")
print(f"cobertura del intervalo de μ con z = 1.96: {cubre_z.mean():.4f} (exacta: {2 * stats.t.cdf(1.96, n - 1) - 1:.4f})")
print(f"cobertura del intervalo de σ² con χ²: {cubre_var.mean():.4f}")
# 4) Y con datos exponenciales (asimétricos) la t de n = 10 ya no es exacta
Xe = rng.exponential(1.0, (B, n))
xe, se = Xe.mean(axis=1), Xe.std(axis=1, ddof=1)
print(f"cobertura del intervalo con t para datos exponenciales, n = 10: {np.mean(np.abs(xe - 1) <= q * se / np.sqrt(n)):.4f}")The first table is the figure’s number column. Both identities in the second part hold to five digits: they are exact identities, not simulations. The third checks the theory’s promise: the interval covers of the time, the interval (exact coverage is , and simulated has error points), and the interval based on the pivot covers . The final line, for exponential data, gives : exact theory is a property of normality, not of .
Common mistakes
Exercises
Step 1 of 5. How are and the residual vector expressed in terms of ?
More than one answer may be correct.
se_mediana(generador, n, B=4000, seed=0): simulate B samples of size n with generador(rng, size) (which returns population data of shape size, with rng a numpy.random.Generator), compute each sample median, and return the standard deviation of those B medians (with ddof=1). Use np.random.default_rng(seed). Tests check that, for n = 200, it approximates in several populations.import numpy as np
def se_mediana(generador, n, B=4000, seed=0):
# generador(rng, size) -> datos de la población con forma size
# devuelve la desviación típica (ddof=1) de las B medianas
pass