Estimators: bias, variance, MSE, consistency and the method of moments
Define what makes an estimator good: bias, variance, mean squared error and its decomposition, consistency, and relative efficiency. Introduce the first general construction method, the method of moments, and a tool used throughout the module: ADEMP simulation studies for honest evaluation of procedures.
After this lesson you can
- Calculate bias, variance, and MSE of simple estimators and prove MSE = bias² + variance.
- Prove estimator consistency with the law of large numbers and mean-square convergence.
- Construct moment estimators for gamma, beta, and uniform distributions and detect estimates outside parameter space.
- Compare estimators by relative efficiency (mean versus median under normal, Laplace, and t).
- Design and run an ADEMP simulation study reporting bias, variance, and MSE with Monte Carlo error.
- Explain why a biased estimator may have lower MSE than an unbiased one.
Before you start
- 05Statistical modelSampling distributionStandard errorNormal sampling theory: chi-squared, Student t and F distributions
- 04Convergence in probabilityConvergence in LpWeak law of large numbersSlutsky's lemma and continuous mapping theoremExponential, gamma and chi-squared distributionsBeta and Dirichlet distributionsPoisson distribution
Motivation: three numbers for the same latency
You measured service response time for requests. You want one number summarizing “typical latency” and have three calculators: the mean of 40 times, median, and trimmed mean (discard the lowest and highest and average the rest). On the same sample they produce three numbers. Another sample of 40 requests gives three more. None exactly matches the value you want to know, so the useful question is not “which number is right?” but “which procedure errs least when applied repeatedly to new samples?”
That sentence hides three decisions turned into mathematics here. What does error mean? A loss; squared error is convenient. What does “repeatedly” mean? The procedure’s sampling distribution, already seen last lesson. What does “least” mean? Average loss over that distribution, yielding mean squared error. This language explains why the answer changes with data tail weight, why a biased estimator can be useful, why an unbiased estimator can be useless, and how to build a first general estimator, the method of moments, which sometimes fails instructively.
A qualification for a meaningful comparison: mean, median, and trimmed mean estimate the same thing only if the distribution is symmetric about a center . Under skewness (as with real right-tailed latency) they are three distinct estimands and comparing their error makes no sense; this common mistake appears in the warnings. Here assume symmetry and ask about efficiency.
The lesson also introduces a tool you will use through the module and research work: the simulation study with ADEMP structure. Every claim about bias, variance, or coverage can be checked with a short experiment, using the rigor (seeds, Monte Carlo error, multiple data mechanisms) serious papers require.
Estimator, estimand, and estimate
Work within a statistical model : data are for unknown . What we want is not always all of ; it is a function (mean, variance, quantile, event probability…).
These three levels differ, and confusing them causes constant reasoning errors:
| Object | What it is | Random? | Example |
|---|---|---|---|
| estimand | a number of interest | no, fixed and unknown | typical latency |
| estimator | a rule, a random variable | yes | |
| estimate | the rule’s value on actual data | no, it already occurred |
An estimator is a random variable and thus has sampling distribution, expectation, variance, and standard deviation. An estimator’s standard deviation is called its standard error. Properties studied here (bias, variance, consistency) all describe the procedure, averaged over samples that could have been observed. None says whether this particular estimate is near or far from ; that needs inference in later lessons (intervals, tests).
For large-sample limits consider a sequence of estimators , one per sample size, treated as one object.
Bias, variance, and mean squared error
The first desirable quality is accuracy “on average.”
Zero bias for every is essential: an estimator right on average at only one particular (for example constant estimator when ) is not unbiased. But bias is not the whole story: (use only the first observation) is unbiased for yet ignores observations. An error measure must also penalize spread.
This is squared loss averaged over the sampling distribution. Its root, , has the estimand’s units. Squaring is a convenient convention (differentiable, permits decomposition), not a law of nature; the decision theory lesson shows each loss defines its own “best estimator.”
Proof
This is the bias-variance decomposition of MSE. Write and , and add and subtract inside the square:
The cross term vanishes because , and is constant. This leaves .
∎The decomposition says estimator error has two sources added in squares: bias (the shots’ center is far from the target) and variance (shots scatter). For an unbiased estimator MSE is variance, and typical error is standard error.
The dartboard
To feel bias and variance together, fire many shots. Each shot in the next figure is a estimate calculated on a new sample using estimator with divisor you choose. The target is at .
With and normal data the figures are clear: with MSE is (in units), all variance; with it falls to , and with to , less than the unbiased estimator. The next section proves this.
Biased can be better
Proof
Under normality, with , so and , hence . Then
This is a parabola in minimized where its derivative vanishes: , or . Substitution gives . The other two values evaluate the parabola at and .
∎For : versus versus . Bessel’s correction produces the highest MSE of the three. The breakdown explains it: the unbiased estimator pays in variance for what it gains in bias. Multiplying by a factor below 1 (shrinking toward zero) introduces downward bias but reduces variance by the factor squared; the balance favors it while bias is small relative to spread.
Divisor is a normal-theory result. Under other laws, variance of is , where is excess kurtosis (0 for normal, 3 for Laplace, 6 for exponential, for uniform), and the same calculation gives optimal divisor
Positive kurtosis (heavier tails than normal) calls for more shrinkage, and negative kurtosis such as uniform calls for less. Check by changing the law in the previous figure: for exponential with the minimum is , farther from than under normality. This is the kurtosis defined in the probability lesson on skewness and kurtosis.
When unbiasedness is absurd
Sometimes the only unbiased estimator is useless. Observe one variable and estimate , always in .
The lesson is not that unbiasedness is bad, but that it is a constraint like any other: sometimes cheap (mean), sometimes expensive (variance with small ), sometimes leaving one absurd solution. Look at MSE or the loss you actually care about.
Consistency
Everything above fixes . A second minimum requirement is that enough data eventually make the estimator accurate.
This definition applies convergence in probability from probability to an estimator sequence. Mean-square consistency is convergence in , and is stronger:
Proof
By Markov’s inequality applied to , which is Chebyshev’s inequality for error, . Equivalence of the two assumption formulations follows from MSE decomposition. A counterexample to the converse appears below.
∎Four estimators of illustrate all combinations, with data:
| Estimator | Bias | Variance | Consistent? |
|---|---|---|---|
| yes | |||
| (first observation only) | , does not tend to 0 | no | |
| yes, though biased | |||
| mean of first observations | yes, but very slowly |
With and , estimator has fixed probability of falling outside the band for every : unbiased but never converging. For the mean this is , falling from at to at . And is initially worse than the mean (its center is , far from for small ), but catches up as bias dissolves.
Two observations on what consistency does not mean.
It says nothing about speed. Consistency of is true and almost useless: typical error needs , or observations instead of . Error rate and limiting shape are studied in asymptotic theory with the CLT.
It does not imply bias tends to zero. Let be independent of the data with with probability and otherwise. Then is consistent (because ), but for every : bias is always and MSE grows as . Rare events with huge consequences move expectation without moving probability. (With uniform integrability, consistency does imply asymptotically zero bias.)
How to prove an estimator consistent
There are two paths. First, the criterion above: calculate bias and variance. Second, the law of large numbers combined with continuity.
Thus is consistent for without calculating its variance: by continuity of , and factor tends to . Only a finite second moment is needed (not the fourth, which calculating would require). And is consistent for , though biased, by continuity of square root. Consistency is therefore the “cheap” property satisfied by almost any reasonable estimator.
Consistency also fails in pathological cases. If are Cauchy, sample mean has the same distribution as for every (Cauchy is stable) and converges to nothing, although sample median is consistent for the center. This connects to the next section.
Relative efficiency
Between two consistent estimators, which is better? If both are well centered, the one with less variance.
The asymptotic version has a practical reading: to match error, needs times the data used by . Under normality , so the median needs times the mean’s data, more, for equal precision.
The limiting variances we need are classical (M-estimator theory proves them; here we use and simulate them). If data have density symmetric about , continuous and positive at , and finite variance (the last is only needed for the mean):
For normal, and : efficiency of median relative to mean is . For Laplace with scale , , and : median is twice as efficient as mean (it is the maximum-likelihood estimator in that family). For Student’s with degrees of freedom,
and the mean loses everything when , because its variance is infinite.
The trimmed mean with proportion is the natural compromise: is mean and is median. For a symmetric law with quantile , its asymptotic variance is (the numerator is variance of “winsorized” data: extremes replaced by ).
Figures (asymptotic, exact):
| best | ||||
|---|---|---|---|---|
| 1 (Cauchy) | 2.467 | 2.872 | median | |
| 2 | 2.000 | 1.767 | trimmed | |
| 3 | 3.000 | 1.851 | 1.520 | trimmed |
| 5 | 1.667 | 1.735 | 1.353 | trimmed |
| 10 | 1.250 | 1.651 | 1.243 | trimmed (narrowly) |
| 30 | 1.071 | 1.597 | 1.176 | mean |
| (normal) | 1.000 | 1.571 | 1.145 | mean |
Median beats mean when ; trimmed mean beats mean when . For normal, trimmed retains of mean efficiency (), a small price for strong protection from outliers (the first lesson’s robust measures). For Cauchy, trimming loses to median: with tails this heavy, trim almost everything.
The method of moments
So far we evaluated estimators given to us. How do we construct one when the model is and is not simply a mean? The oldest idea matches model predictions to observations.
Model moments are parameter functions: , . Sample moments are , estimating the former (consistently by the law of large numbers).
Three explicit examples
Gamma. Let (shape , rate ; exponential-gamma family). The first two moments are and . With and (second central moment, divisor ), matching gives
Beta. Let (beta), with mean and variance . Solving gives
with estimating . For to be valid parameters requires , or . With data in and divisor this always holds because implies . With divisor (used by and many packages by default) it can fail: for and , and “parameters” become negative. A divisor detail leaves the estimator undefined.
Uniform. Let . The first moment is , so . It is the simplest example and, as we shall see, teaches the most about the method’s limitations.
Consistency
Proof
By the weak law, for each , and componentwise convergence in probability is equivalent to vector convergence. By continuous mapping, .
∎This four-line proof explains the method’s attraction: it almost always gives a consistent estimator. But consistency is all it guarantees.
Limits of the method
- It can leave parameter space. This occurs with divisor for beta, and with uniform, shown next.
- It needs moments. If (heavy-tailed Pareto, Cauchy) sample moments do not converge and the method does not exist.
- Moment choice is not unique. For both mean and variance are : and are different moment estimators of the same parameter. The lowest order is usually used, but this is a convention, not a theorem. With more moment conditions than parameters, generalized method of moments (GMM) combines them with optimal weights; see econometrics (m27).
- It is not efficient. For gamma shape, asymptotic variance of is (calculation with the delta method in lesson 8); with it is . The next lesson’s maximum-likelihood estimator achieves , and for small shapes the difference is huge: with moments have only efficiency relative to likelihood.
The next interactive shows the first limitation in its most striking form (uniform).
Exact facts for (maximum by order statistics):
- is unbiased with .
- Maximum has and : downward biased but MSE .
- Corrected maximum is unbiased with .
The MSE ratio between and corrected maximum is : at the correction is 4 times better, at it is 34 times better. Moment-method error decreases as and maximum error as .
Probability of an impossible estimate, , is zero for (because for positive data), for , and… tends to :
Proof
Write with . By the CLT, . Meanwhile has mean , so by Markov , or . By Slutsky’s lemma, . Since the limiting law is continuous at , .
∎The underlying reason is scale: error of is order and maximum error order . Nearly all fluctuation is in , and it is symmetric, so half the time it falls left of a maximum already close to . The estimator ignores information that all observations are below . This information, summarized in the maximum, is a sufficient statistic, and the estimator using it is maximum likelihood: concepts from lessons 5 and 7.
Simulation studies
Exact bias, variance, and MSE are rarely calculable. They are for a normal sample mean or variance, but not for median of a with 5 degrees of freedom, an M-estimator, or a neural network. The general tool is simulation: generate many samples from a known mechanism, apply the procedure to each, and summarize errors. Carelessly done it produces many false literature claims; methodically done it is a research tool.
The now-standard structure is ADEMP (Morris, White, and Crowther, 2019), five questions to answer before running anything:
| Letter | Question | In this lesson |
|---|---|---|
| Aims | What do you want to know? | Which center estimator loses least under heavy tails? |
| Data-generating mechanisms | What data test it? Several, not one | normal, Laplace, ; multiple |
| Estimands | What exactly is estimated? | symmetry center |
| Methods | Which procedures are compared? | mean, median, trimmed |
| Performance measures | How are they judged? | bias, empirical variance, MSE, coverage |
An ADEMP simulation study is also an experiment: it has error. Each performance measure averages replicates and has Monte Carlo error to report:
| Measure | Estimate | Monte Carlo error |
|---|---|---|
| bias | , with empirical variance of estimates | |
| variance | if are normal (otherwise, use empirical fourth moment) | |
| MSE | standard deviation of divided by | |
| interval coverage | proportion of replicates covering |
The bias formula gives a rule for choosing : for Monte Carlo error in bias of an estimator with standard deviation , replicates are needed. For a interval’s coverage with Monte Carlo error , . Error decreases only as : halving it costs four times as many replicates.
Four good habits:
- Reproducible seeds and generators, so anyone can reproduce your table bit for bit (
numpy.random.Generatorwith explicit seed). - Common random numbers: all methods see the same samples. Then the difference between methods has much less noise than each separately.
- Multiple data mechanisms, including those unfavorable to your method. A proposed method tested only where it excels proves nothing.
- Count failures (nonconvergence, out-of-range estimates) instead of discarding them, and report each figure’s Monte Carlo error.
Implementation from scratch
Before the general framework, directly check decomposition with three divisors: bias, variance, and MSE of , using standard normal samples of size , compared with exact theorem values.
import numpy as np
rng = np.random.default_rng(0)
n, R = 10, 200_000
X = rng.normal(0.0, 1.0, size=(R, n)) # sigma^2 = 1
SS = ((X - X.mean(axis=1, keepdims=True)) ** 2).sum(axis=1)
print(f"{'divisor':>8} {'sesgo':>8} {'varianza':>9} {'sesgo²+var':>11} {'ECM':>8} {'ECM exacto':>11}")
for nombre, d in [("n-1", n - 1), ("n", n), ("n+1", n + 1)]:
est = SS / d
sesgo = est.mean() - 1.0
var = est.var(ddof=1)
ecm = ((est - 1.0) ** 2).mean()
c = (n - 1) / d
exacto = (c - 1) ** 2 + 2 * (n - 1) / d**2
print(f"{nombre:>8} {sesgo:8.4f} {var:9.4f} {sesgo**2 + var:11.4f} {ecm:8.4f} {exacto:11.4f}")Columns “bias² + variance” and “MSE” agree to four digits: decomposition is an algebraic fact, not an approximation (the small difference between variance with divisor and MSE with divisor appears only in the fifth). Simulated MSE also agrees with exact up to Monte Carlo error.
Now the general framework. It is deliberately small, four pieces corresponding to ADEMP letters. A mechanism (D and E) can generate a data block of shape and knows the true estimand; a method (M) receives the block and returns each replicate’s estimate and optionally standard error; function resumen (P) calculates measures with Monte Carlo error; and simular makes all methods see exactly the same samples.
import zlib
import numpy as np
from scipy import stats
def _rng(semilla, *claves):
"""Un generador por (semilla, n, mecanismo): reproducible e independiente de R y del orden."""
return np.random.default_rng([semilla, *claves])
class Mecanismo:
"""D y E de ADEMP: cómo se generan los datos y qué se estima."""
def __init__(self, nombre, muestrear, estimando):
self.nombre, self.muestrear, self.estimando = nombre, muestrear, estimando
def resumen(est, se=None, theta=0.0, z=1.96):
"""P de ADEMP: sesgo, varianza empírica, ECM y cobertura, cada uno con su error Monte Carlo."""
est = np.asarray(est, dtype=float)
R = len(est)
err = est - theta
var = est.var(ddof=1)
m4 = ((est - est.mean()) ** 4).mean()
out = dict(
sesgo=err.mean(), ee_sesgo=np.sqrt(var / R),
var=var, ee_var=np.sqrt(max(m4 - var**2 * (R - 3) / (R - 1), 0.0) / R),
ecm=(err**2).mean(), ee_ecm=(err**2).std(ddof=1) / np.sqrt(R),
cob=np.nan, ee_cob=np.nan,
)
if se is not None:
cob = np.mean(np.abs(err) <= z * se)
out.update(cob=cob, ee_cob=np.sqrt(cob * (1 - cob) / R))
return out
def simular(mec, metodos, n, R, semilla=2024):
"""M de ADEMP: todos los métodos ven las MISMAS R muestras (números aleatorios comunes)."""
x = mec.muestrear(_rng(semilla, n, zlib.crc32(mec.nombre.encode())), (R, n))
res = {}
for nombre, f in metodos.items():
salida = f(x)
est, se = salida if isinstance(salida, tuple) else (salida, None)
res[nombre] = (np.asarray(est), se)
return res
def tabla(mec, res):
for nombre, (est, se) in res.items():
r = resumen(est, se, mec.estimando)
cob = " -" if np.isnan(r["cob"]) else f"{100 * r['cob']:5.1f}%"
print(f"{mec.nombre:>8} {nombre:>10} sesgo {r['sesgo']:+.4f} ({r['ee_sesgo']:.4f}) "
f"var {r['var']:.4f} ({r['ee_var']:.4f}) ECM {r['ecm']:.4f} ({r['ee_ecm']:.4f}) cob {cob}")
# métodos para estimar el centro de una ley simétrica
def media(x):
return x.mean(axis=1), x.std(axis=1, ddof=1) / np.sqrt(x.shape[1])
def mediana(x):
# error estándar «de manual» (válido solo bajo normalidad): sqrt(pi/2) * s / sqrt(n)
return np.median(x, axis=1), 1.2533 * x.std(axis=1, ddof=1) / np.sqrt(x.shape[1])
def recortada(x):
return stats.trim_mean(x, 0.2, axis=1)
METODOS = {"media": media, "mediana": mediana, "recort.20%": recortada}
MECANISMOS = [ # las tres leyes tienen varianza 1 y centro 0
Mecanismo("normal", lambda g, s: g.standard_normal(s), 0.0),
Mecanismo("laplace", lambda g, s: g.laplace(0, 1 / np.sqrt(2), s), 0.0),
Mecanismo("t3", lambda g, s: g.standard_t(3, s) / np.sqrt(3), 0.0),
]
n, R = 20, 4000
for mec in MECANISMOS:
tabla(mec, simular(mec, METODOS, n, R))Read the table as a research result, with Monte Carlo errors in parentheses. Under normality mean MSE is (exact: ), median , and trimmed mean between; under Laplace and the order changes: median and trimmed win, with trimmed best for . Differences are several times their Monte Carlo errors, not noise. Two subtler points. First, all biases are compatible with zero (within a couple of Monte Carlo errors), as expected for a symmetry center. Second, mean coverage is with Monte Carlo error around points: it misses nominal and the difference is not noise; ignores that is estimated (at use a quantile, ; interval lessons develop this). Median overcovers under Laplace and () because its “textbook” standard error is designed for normality: coverage evaluates the pair (estimator, standard error), not estimator alone.
Monte Carlo error and common random numbers are clearer in two further experiments with the same framework: difference in MSE between median and mean measured paired and unpaired, and how error shrinks with .
# Números aleatorios comunes: la diferencia de ECM entre dos métodos se mide mucho mejor emparejando
mec = MECANISMOS[0]
res = simular(mec, METODOS, n, R)
a, b = res["media"][0], res["mediana"][0]
d = (b - mec.estimando) ** 2 - (a - mec.estimando) ** 2 # ECM(mediana) - ECM(media), réplica a réplica
ee_pareado = d.std(ddof=1) / np.sqrt(R)
ee_indep = np.sqrt(((a - 0) ** 2).std(ddof=1) ** 2 / R + ((b - 0) ** 2).std(ddof=1) ** 2 / R)
print(f"normal, n={n}: ECM(mediana) - ECM(media) = {d.mean():.4f}")
print(f" error Monte Carlo emparejado: {ee_pareado:.4f}")
print(f" error Monte Carlo sin emparejar: {ee_indep:.4f}")
print(f" teoría asintótica: (pi/2 - 1)/n = {(np.pi / 2 - 1) / n:.4f}")
# El error Monte Carlo baja como 1/sqrt(R): ECM de la media bajo la normal, exacto = 1/n
print("\nR ECM estimado ± EE (exacto 1/n = %.4f)" % (1 / n))
for R_ in (100, 1000, 10_000, 100_000):
est = simular(mec, {"media": media}, n, R_)["media"][0]
r = resumen(est, None, 0.0)
print(f"{R_:>6} {r['ecm']:.4f} ± {r['ee_ecm']:.4f}")Pairing reduces Monte Carlo error of the difference (from to ) because mean and median use the same samples and their errors are strongly correlated. The last table’s error falls as : at the interval of Monte Carlo errors spans to ( of the value), while at it is below . Asymptotic difference is somewhat larger than at (): is not yet asymptotic, another reason to simulate instead of trusting the limit.
With libraries
scipy.stats already implements moment fitting for each distribution: rv_continuous.fit(datos, method="MM"). Fix parameters not being estimated, because scipy’s gamma has three parameters (shape, location, scale) and the method uses as many moments as free parameters. With floc=0 (and fscale=1 for beta) this becomes the lesson’s two-parameter case. Compare our formulas with the library.
def mom_gamma(x):
"""Gamma(forma a, tasa b) por momentos; x tiene forma (..., n)."""
m = x.mean(axis=-1)
v = x.var(axis=-1) # segundo momento central: divisor n
return m**2 / v, m / v
def mom_beta(x):
m = x.mean(axis=-1)
v = x.var(axis=-1)
s = m * (1 - m) / v - 1 # a + b
return m * s, (1 - m) * s
rng = np.random.default_rng(7)
xg = rng.gamma(shape=3.0, scale=2.0, size=500) # a = 3, b = 1/2
a, b = mom_gamma(xg)
ah, loc, esc = stats.gamma.fit(xg, floc=0, method="MM")
print(f"gamma propio: a = {a:.6f}, b = {b:.6f}")
print(f"gamma scipy: a = {ah:.6f}, b = {1 / esc:.6f} (scale = {esc:.6f})")
xb = rng.beta(2.0, 5.0, size=500)
a, b = mom_beta(xb)
ah, bh, _, _ = stats.beta.fit(xb, floc=0, fscale=1, method="MM")
print(f"beta propio: a = {a:.6f}, b = {b:.6f}")
print(f"beta scipy: a = {ah:.6f}, b = {bh:.6f}")Gamma agrees to all displayed digits; beta to four decimal places (the library numerically solves what we rearranged by hand, and scipy gamma parameterizes with scale ). With these and ADEMP, the natural question is moment-method error as a function of :
# ECM del estimador por momentos de la forma de una gamma(3, tasa 1/2) en función de n
alfa, R = 3.0, 2000
print(f"{'n':>5} {'sesgo':>8} {'ECM':>8} {'n*ECM':>8} (2a(a+1) = {2 * alfa * (alfa + 1):.0f})")
for n in (10, 30, 100, 300, 1000):
x = np.random.default_rng([11, n]).gamma(alfa, 2.0, size=(R, n))
ah, _ = mom_gamma(x)
r = resumen(ah, None, alfa)
print(f"{n:>5} {r['sesgo']:+8.3f} {r['ecm']:8.3f} {n * r['ecm']:8.1f}")Three readings. Bias is positive and large for small ( at , of true value ): gamma shape’s moment estimator overestimates, giving MSE at . Still it is consistent: bias falls as and so does MSE. Product stabilizes around as grows, the asymptotic variance value . Simulation confirms the delta-method calculation you have not yet done.
Finally, a preview of next lesson: the same shape’s maximum-likelihood estimator, with the same and comparison framework.
# Un adelanto de la lección siguiente: la máxima verosimilitud para la misma forma
n, R = 100, 150
x = np.random.default_rng([5, n]).gamma(alfa, 2.0, size=(R, n))
mm = mom_gamma(x)[0]
ml = np.array([stats.gamma.fit(f, floc=0)[0] for f in x])
print(f"n = {n}, {R} réplicas, forma verdadera {alfa}")
print(f" momentos: ECM = {np.mean((mm - alfa) ** 2):.3f}")
print(f" verosimilitud: ECM = {np.mean((ml - alfa) ** 2):.3f}")With only 150 replicates the result is indicative (Monte Carlo error is order of MSE) but agrees with asymptotic theory: for moments and for likelihood.
Common mistakes
Exercises
Step 1 of 4. How do you start the decomposition?
More than one answer may be correct.
More than one answer may be correct.
mom_beta(x, ddof=0), accepting a 1D sample x from a and returning (a_hat, b_hat) by moments: , , , where v is sample variance with divisor n - ddof. Raise ValueError with a clear message if any value is not strictly in , variance is , or (sample moments incompatible with beta). Tests also check consistency in simulation.import numpy as np
def mom_beta(x, ddof=0):
"""Estimador por momentos de (a, b) de una beta. Devuelve (a_hat, b_hat)."""
x = np.asarray(x, dtype=float)
# tu código: valida los datos, calcula media y varianza (divisor n - ddof),
# s = m (1 - m) / v - 1 y comprueba que s > 0 antes de devolver (m s, (1 - m) s)
return 1.0, 1.0Summary
- Distinguish estimand (unknown number), estimator (random variable), and estimate (observed number). Bias, variance, and consistency describe the estimator.
- . Bessel’s correction makes unbiased, but under normality minimum MSE occurs at biased divisor : at , versus . With heavy tails the optimum divisor is higher, .
- Consistency (convergence in probability) and unbiasedness are independent. MSE tending to zero suffices for consistency but is not necessary. Consistency says nothing about speed.
- Relative efficiency depends on tails: under normality median has asymptotic efficiency relative to mean; under Laplace, 2; under , median wins if and trimmed mean if .
- Method of moments equates population and sample moments and is consistent by the law of large numbers and continuous mapping. It can leave parameter space (uniform: ), needs finite moments, and is inefficient (gamma: versus for ).
- A simulation study uses ADEMP, seeds and common random numbers, multiple mechanisms, and reports Monte Carlo error ( for bias, for coverage; for at ).