এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।
University Economics — Year 2 · স্নাতক দ্বিতীয় বর্ষ
31Inference in Regression
A regression coefficient is an estimate; its standard error says how far it might be from what it estimates. The standard errors printed by default rest on assumptions about the errors that real data often break: that they all have the same variance, and that they are independent of each other. This chapter states those assumptions, shows why least squares is the best linear estimator when they hold, and builds the standard errors that remain valid when they do not. The chart shows how much the answer can change.
For most coefficients the two standard errors are within 10 per cent of each other. For four they are not: the robust standard error is 1.55 times the classical one for poor self-rated health, 1.29 times for the number of chronic diseases, 1.25 times for a physical limitation and 1.18 times for fair health. The classical formula assumes that every person’s visits are equally unpredictable; the sick are much less predictable than the healthy.
You already know
From the Year 1 volume: estimators, unbiased and consistent estimators, standard errors, confidence intervals, the and distributions, tests and -values, and the central limit theorem. From Chapter 30: the matrix form, the normal equations and the Frisch–Waugh–Lovell theorem.
31.1 The Gauss–Markov theorem
Definition 31.1 (Gauss–Markov assumptions)
The Gauss–Markov assumptions for are: has full column rank; ; and , so that the errors are uncorrelated with each other and all have the same variance.
Definition 31.2 (Homoskedasticity)
Errors are homoskedastic if their variance given the regressors is the same for every observation, ; they are heteroskedastic if it varies across observations.
Under the first two assumptions is unbiased. Under the third, , and is estimated by . These are the classical standard errors.
Definition 31.3 (Best linear unbiased estimator)
An estimator of is the best linear unbiased estimator if it is linear in , unbiased, and has a variance matrix no larger, in the sense of positive semi-definite matrices, than that of any other linear unbiased estimator.
Theorem 31.4 (Gauss–Markov)
Under the Gauss–Markov assumptions, the least-squares estimator is the best linear unbiased estimator of .
Proof. Let be linear, and write . Then , so unbiasedness for every requires . Then , and , since . The difference from the least-squares variance is , which is positive semi-definite. ∎
The listing compares least squares with another linear unbiased estimator of a slope: the difference between the mean outcomes of the upper and lower halves of the regressor, divided by the difference of their mean regressors.
"""Least squares against another linear unbiased estimator of the slope."""
import numpy as np
rng = np.random.default_rng(31)
n, sigma = 40, 2.0
x = np.linspace(0, 10, n) # fixed regressor
low, high = x < np.median(x), x >= np.median(x)
def ols_slope(y):
xd = x - x.mean()
return xd @ y / (xd @ xd)
def group_slope(y):
"""Difference of group means: linear in y and unbiased, but not least squares."""
return (y[high].mean() - y[low].mean()) / (x[high].mean() - x[low].mean())
samples = 1 + 0.5 * x + sigma * rng.standard_normal((20000, n))
draws = np.array([[ols_slope(y), group_slope(y)] for y in samples])
print(" mean variance (simulated) variance (formula)")
var_ols = sigma**2 / ((x - x.mean()) @ (x - x.mean()))
gap = x[high].mean() - x[low].mean()
var_group = sigma**2 * (1 / high.sum() + 1 / low.sum()) / gap**2
for name, col, v in (("OLS", 0, var_ols), ("groups", 1, var_group)):
print(f"{name:8s} {draws[:, col].mean():7.4f} {draws[:, col].var():12.5f}"
f" {v:20.5f}") # fmt: skip
$ python gauss_markov_sim.py
mean variance (simulated) variance (formula)
OLS 0.5006 0.01145 0.01141
groups 0.4998 0.01508 0.01521
The variances are 0.01145 and 0.01508 in the simulation, against 0.01141 and 0.01521 by the formulas. The theorem says nothing about estimators that are biased or non-linear, and nothing at all once the errors are heteroskedastic.
31.2 Normal errors: and
If, in addition, the errors are normal given , then has a distribution with degrees of freedom, and confidence intervals and tests on one coefficient follow as in the Year 1 volume. Several restrictions at once need another statistic.
Definition 31.5 (Joint hypothesis)
A joint hypothesis is a set of restrictions on the coefficients tested together, such as .
Definition 31.6 (F statistic)
The F statistic for linear restrictions is , where and are the sums of squared residuals of the regressions with and without the restrictions. Under the classical assumptions with normal errors it has an distribution when the restrictions hold.
The statistic asks whether imposing the restrictions raises the sum of squared residuals by more than chance would. The listing applies it to the RAND Health Insurance Experiment, in which families were assigned at random to insurance plans that made them pay different shares of their medical bills.
"""Doctor visits in the RAND experiment: t statistics, and an F test by hand."""
import numpy as np
import statsmodels.api as sm
from scipy import stats
from econdata import sm_dataset
d = sm_dataset("randhie")
y = d.mdvis
X = sm.add_constant(d.drop(columns="mdvis"))
fit = sm.OLS(y, X).fit()
table = np.column_stack([fit.params, fit.bse, fit.tvalues])
for name, (b, se, t) in zip(X.columns, table):
print(f"{name:8s} {b:8.4f} {se:7.4f} {t:7.2f}")
# H0: the three self-rated health dummies have zero coefficients
health = ["hlthg", "hlthf", "hlthp"]
restricted = sm.OLS(y, X.drop(columns=health)).fit()
n, k, q = len(y), X.shape[1], len(health)
ssr_u, ssr_r = fit.ssr, restricted.ssr
F = ((ssr_r - ssr_u) / q) / (ssr_u / (n - k))
print(f"SSR restricted {ssr_r:.1f}, unrestricted {ssr_u:.1f}")
F_sm = fit.f_test(" = ".join(health) + " = 0").fvalue
print(f"F by hand {F:.3f}; statsmodels {F_sm:.3f}")
print(f"5 % critical value F({q}, {n - k}): {stats.f.ppf(0.95, q, n - k):.3f}")
$ python t_and_f.py
const 1.7379 0.0842 20.65
lncoins -0.1695 0.0202 -8.41
idp -0.7533 0.0753 -10.00
lpi 0.1066 0.0136 7.86
fmde -0.1001 0.0115 -8.71
physlm 1.0658 0.1033 10.32
disea 0.1217 0.0049 25.01
hlthg -0.0487 0.0667 -0.73
hlthf 0.2201 0.1218 1.81
hlthp 1.4410 0.2607 5.53
SSR restricted 382137.5, unrestricted 381469.6
F by hand 11.778; statsmodels 11.778
5 % critical value F(3, 20180): 2.605
Each unit of log coinsurance goes with 0.17 fewer visits, holding the other plan variables and health fixed (). The health dummies, measured against excellent health, have statistics of , and ; jointly they raise the sum of squared residuals by 667.9 and give , far above the 5 per cent critical value of 2.605. Both calculations used the classical variance. The next section asks whether it was right to.
31.3 Unequal error variances
Among the person-years with the fewest predicted visits the residuals have a standard deviation of 2.44; among those with the most, 8.20. The errors are heteroskedastic, and the classical variance formula does not apply. Least squares is still unbiased, but its variance is now
with the th row of and (Exercise 11). Its shape gives it the name of a sandwich.
Definition 31.7 (Heteroskedasticity-robust standard error)
A heteroskedasticity-robust standard error is the square root of a diagonal element of (31.1) with each replaced by the squared residual (HC0), often multiplied by (HC1).
Each is a poor estimate of its , but the sum in the middle averages over many observations, and in large samples the robust variance is consistent whatever the form of heteroskedasticity.
"""Heteroskedasticity-robust standard errors by hand, against statsmodels."""
import numpy as np
import statsmodels.api as sm
from econdata import sm_dataset
d = sm_dataset("randhie")
y = d.mdvis.to_numpy(float)
X = sm.add_constant(d.drop(columns="mdvis")).to_numpy(float)
n, k = X.shape
A = np.linalg.inv(X.T @ X)
b = A @ X.T @ y
e = y - X @ b
classical = A * (e @ e) / (n - k)
meat = (X * e[:, None] ** 2).T @ X # sum of e_i^2 x_i x_i'
hc0 = A @ meat @ A # the sandwich
hc1 = hc0 * n / (n - k)
sm_hc1 = sm.OLS(y, X).fit(cov_type="HC1").cov_params()
print("same HC1 as statsmodels:", np.allclose(hc1, sm_hc1))
names = ["const", "lncoins", "idp", "lpi", "fmde", "physlm", "disea", "hlthg", "hlthf"]
names.append("hlthp")
print("term classical HC0 HC1 ratio")
for j, name in enumerate(names):
se = [np.sqrt(v[j, j]) for v in (classical, hc0, hc1)]
print(f"{name:8s} {se[0]:8.4f} {se[1]:8.4f} {se[2]:8.4f} {se[2] / se[0]:6.2f}")
$ python robust_se.py
same HC1 as statsmodels: True
term classical HC0 HC1 ratio
const 0.0842 0.0884 0.0885 1.05
lncoins 0.0202 0.0188 0.0188 0.93
idp 0.0753 0.0719 0.0720 0.95
lpi 0.0136 0.0134 0.0134 0.99
fmde 0.0115 0.0112 0.0112 0.98
physlm 0.1033 0.1293 0.1293 1.25
disea 0.0049 0.0063 0.0063 1.29
hlthg 0.0667 0.0616 0.0616 0.92
hlthf 0.1218 0.1434 0.1434 1.18
hlthp 0.2607 0.4029 0.4030 1.55
What happens to a test when the wrong standard error is used? The next listing draws samples in which the true slope is zero and the error spread grows with the regressor, and counts how often a nominal 5 per cent test rejects.
"""How often a nominal 5 % test rejects a true null, with unequal error variances."""
import numpy as np
import statsmodels.api as sm
rng = np.random.default_rng(31)
n, reps = 200, 4000
reject = {"classical": 0, "robust": 0}
for _ in range(reps):
x = rng.standard_normal(n)
u = np.abs(x) * rng.standard_normal(n) # error spread grows with |x|
y = 1 + 0 * x + u # the true slope is zero
model = sm.OLS(y, sm.add_constant(x))
reject["classical"] += abs(model.fit().tvalues[1]) > 1.96
reject["robust"] += abs(model.fit(cov_type="HC1").tvalues[1]) > 1.96
for name, count in reject.items():
print(f"{name:9s} rejection rate {count / reps:.3f}")
$ python size_sim.py
classical rejection rate 0.254
robust rejection rate 0.057
The classical test rejects in 25.4 per cent of samples, five times as often as it claims; the robust test in 5.7 per cent. With a joint hypothesis the robust version of the statistic uses the robust variance matrix; on the RAND data the test of the health dummies falls from 11.78 to 5.40, still above the critical value (Exercise 6).
31.4 Clustered errors
Observations often come in groups: pupils in a class, workers in a firm, families in a town, the same person in several years. Anything shared by the group (a teacher, a manager, a local shock) puts a common component in the errors of its members. If the regressor is also shared within the group, the sample contains much less independent information than its size suggests.
Suppose there are groups of members, the regressor is the same for every member of a group, and the errors have variance and correlation between members of the same group. Then (Exercise 12)
Definition 31.8 (Moulton factor)
The Moulton factor is the ratio of the true standard error of a coefficient to the classical one when errors are correlated within groups; for groups of equal size , a regressor constant within groups and an error correlation , it is .
With groups of 20 and a correlation of only 0.2, the factor is 2.19: classical standard errors are less than half what they should be.
Definition 31.9 (Cluster-robust standard error)
A cluster-robust standard error replaces the middle of the sandwich by , summing within each group first, so that the errors may be correlated in any way within groups but are independent across them.
"""Grouped data: classical, robust and cluster-robust standard errors."""
import numpy as np
import statsmodels.api as sm
rng = np.random.default_rng(31)
G, m, rho = 50, 20, 0.2 # groups, members per group, error correlation within group
group = np.repeat(np.arange(G), m)
slopes, se = [], {"classical": [], "robust": [], "cluster": []}
for _ in range(500):
x = rng.standard_normal(G)[group] # the regressor is the same within a group
u = np.sqrt(rho) * rng.standard_normal(G)[group]
u += np.sqrt(1 - rho) * rng.standard_normal(G * m)
model = sm.OLS(1 + 0.5 * x + u, sm.add_constant(x))
slopes.append(model.fit().params[1])
se["classical"].append(model.fit().bse[1])
se["robust"].append(model.fit(cov_type="HC1").bse[1])
fit = model.fit(cov_type="cluster", cov_kwds={"groups": group})
se["cluster"].append(fit.bse[1])
print(f"true s.d. of the slope across samples: {np.std(slopes):.4f}")
for name, values in se.items():
print(f"mean {name:9s} standard error: {np.mean(values):.4f}")
print(f"Moulton factor sqrt(1 + (m - 1) rho): {np.sqrt(1 + (m - 1) * rho):.3f}")
ratio = np.mean(se["cluster"]) / np.mean(se["classical"])
print(f"cluster over classical: {ratio:.3f}")
$ python cluster_sim.py
true s.d. of the slope across samples: 0.0696
mean classical standard error: 0.0323
mean robust standard error: 0.0322
mean cluster standard error: 0.0684
Moulton factor sqrt(1 + (m - 1) rho): 2.191
cluster over classical: 2.115
Across 500 samples the slope has a standard deviation of 0.0696. The classical standard errors average 0.0323, and the robust ones 0.0322: robustness to unequal variances does nothing for correlation within groups. The cluster-robust standard error averages 0.0684, 2.115 times the classical one, close to the Moulton factor of 2.191. Cluster-robust standard errors need many clusters: their middle term is an average over groups, and with few groups it is itself very noisy, and often too small (the weekend problem has three).
The RAND data of this chapter are such a case. The experiment assigned insurance plans to families, not to persons, and kept each family on its plan for several years, so the plan variables are the same for every member and every year of a family, and one person’s errors are correlated across years. The standard errors of the plan coefficients should then be clustered by family; the classical and the robust ones printed above are both likely too small. The file used here has no family or person identifier, so the clustering cannot be done with it.
31.5 Large-sample results
Without normal errors, the and distributions are not exact. Large samples give approximations that need neither normality nor homoskedasticity.
Definition 31.10 (Asymptotic normality)
An estimator is asymptotically normal if converges in distribution to a normal distribution with mean zero as .
Theorem 31.11 (Large-sample distribution of least squares)
If the observations are independent and identically distributed, , is invertible and the relevant moments are finite, then is consistent and converges in distribution to .
Proof. Admitted at this level. ∎
The variance in the theorem is the sandwich again; its sample version is the robust variance matrix. So statistics built with robust standard errors are approximately standard normal in large samples, which is why the robust test of the listing rejected close to 5 per cent of the time.
31.6 The bootstrap
Definition 31.12 (Bootstrap)
The bootstrap estimates the sampling distribution of a statistic by recomputing it on many samples drawn with replacement from the data, treating the sample as if it were the population.
To bootstrap a regression coefficient, draw observations (rows) with replacement, run the regression, keep the coefficient, and repeat a thousand times or more; the standard deviation of the kept coefficients is a standard error. Drawing rows keeps each observation’s regressors and error together, so the result is robust to heteroskedasticity; with grouped data whole groups must be drawn. The bootstrap is useful for statistics without a simple variance formula. It does not repair a bad design: drawing from a sample that has three clusters still gives three clusters.
Model — The classical linear model
Assumes. The Gauss–Markov assumptions and, for exact and distributions, normal errors.
Predicts. Least squares is the best linear unbiased estimator; classical standard errors and and tests have their stated properties in any sample size.
Tested. The spread of residuals against fitted values, and the comparison of classical with robust and cluster-robust standard errors: on the RAND data the residual spread rises more than threefold across fitted values.
Breaks. Heteroskedasticity makes classical standard errors wrong in either direction (25.4 per cent rejections in the simulation); correlation within groups makes them too small by the Moulton factor; robust and cluster-robust standard errors repair these in large samples and with many clusters, not with few.
31.7 Exercises
Exercise 31.1 ★
Read the opening chart. For which coefficients is the robust standard error larger than the classical one by more than 20 per cent? For which is it smaller?
Solution
Solution of Exercise 31.1.
More than 20 per cent larger: poor health (1.55), chronic diseases (1.29) and physical limitation (1.25). Smaller: good health (0.92), log coinsurance (0.93), the deductible plan (0.95), log maximum expense (0.98) and log incentive (0.99).
Exercise 31.2 ★
In the regression of the listing t_and_f.py, interpret the coefficient on physlm and its statistic, with classical and with robust standard errors.
Solution
Solution of Exercise 31.2.
A person with a physical limitation has 1.07 more visits than one without, with the plan variables, chronic diseases and self-rated health fixed. The classical is 10.32; the robust one is . Both reject a zero coefficient by far; the robust interval is a quarter wider.
Exercise 31.3 ★
A test at the 5 per cent level rejects a true null in 25.4 per cent of simulated samples. What does that mean for a researcher who reports a “significant” coefficient with classical standard errors in such data?
Solution
Solution of Exercise 31.3.
A “significant” result would appear in a quarter of samples even if the coefficient were zero, five times the stated risk: the reported -values are much too small, and many of the findings would be false.
Exercise 31.4 ★
Pupils are taught in classes of 25, and the error correlation within a class is 0.1. A regressor is the same for every pupil in a class. Compute the Moulton factor, and say how many independent pupils the sample is worth per class.
Solution
Solution of Exercise 31.4.
. The variance is 3.4 times the classical one, so a class of 25 carries the information of about independent pupils.
Exercise 31.5 ★★
From the listing’s output, compute the statistic of the health dummies by hand from the two sums of squared residuals.
Solution
Solution of Exercise 31.5.
.
Exercise 31.6 ★★
(D) With the RAND data, test jointly that the three health dummies are zero and, separately, that the four plan variables are zero, with classical and with robust variance matrices.
Solution
Solution of Exercise 31.6.
Health dummies: 11.78 classical, 5.40 robust; the 5 per cent critical value of is 2.605, so both reject. Plan variables: 82.26 classical, 80.80 robust, against a critical value of 2.372 for : both reject by far. The robust test changes the health statistic much more, as the opening chart suggests.
Exercise 31.7 ★★
In the Gauss–Markov listing, use the bottom and top quarters of instead of the halves. Predict, then compute, the variance of the grouping estimator. Does it beat least squares?
Solution
Solution of Exercise 31.7.
With quarters the gap between the group means of widens from 5.128 to 7.692, but each group has 10 observations instead of 20: the variance is , smaller than 0.01521 with halves but still above least squares, 0.01141.
Exercise 31.8 ★★
Change the size listing so that the errors are homoskedastic. Predict, then compute, the two rejection rates.
Solution
Solution of Exercise 31.8.
Both should be close to 5 per cent: the classical test is exact in that case up to normality, and the robust one is valid in large samples. The simulation gives 0.054 and 0.056.
Exercise 31.9 ★★
In the cluster listing, what would the Moulton factor be if the errors were uncorrelated within groups? If the regressor varied within groups and were uncorrelated between members of a group?
Solution
Solution of Exercise 31.9.
With the factor is . More generally the factor is , with the correlation of the regressor within groups; with it is 1 again: correlated errors matter only when the regressor is correlated within groups too.
Exercise 31.10 ★★★
Show that the least-squares estimator of in is a linear function of the with weights that sum to zero and satisfy , and show directly that any other set of such weights gives a larger variance under homoskedasticity.
Solution
Solution of Exercise 31.10.
with ; and . A linear estimator has expectation , so it is unbiased for every if and only if and . Write : then and , so since is linear in . The variance is , with equality only if every .
Exercise 31.11 ★★★
Derive (31.1) from , and show that it reduces to under homoskedasticity.
Solution
Solution of Exercise 31.11.
With , . With independent errors and , which gives the sandwich. If , the middle is and the product is .
Exercise 31.12 ★★★
Derive (31.2).
Solution
Solution of Exercise 31.12.
With one regressor, , . Let be the value in group . Then , and the group sums are independent with variance . So the variance is ; since , this is .
31.8 Problem: Brenland’s census of firms
Problem 31.1
Weekend problem — Brenland’s census of firms: a log production function, robust and clustered intervals, the test of constant returns, and three clusters
Brenland’s census of 2025 covers 500 firms in three sectors: 51 in farming, 123 in manufacturing and 326 in services. Let be log output, log workers and log capital, and estimate .
Part I — A log production function.
- What production function does the regression correspond to?
- What do and measure?
- Give the estimates and .
- What does measure?
- Why might firms with a high error also choose more workers, and what would that do to ?
Part II — Robust and clustered intervals.
- Give the classical standard error of .
- Give the heteroskedasticity-robust one, and a 95 per cent interval.
- Give the standard error clustered by sector.
- With three clusters, which critical value should the interval use?
- Give the clustered 95 per cent interval.
- Compare the three standard errors. Which is smallest, and should that reassure?
Part III — The test of constant returns.
- Write the hypothesis of constant returns as a restriction.
- Write the restricted regression.
- Give the two sums of squared residuals.
- Compute the statistic.
- Compare it with the 5 per cent critical value of , 3.86.
- Give the robust version of the test.
- State the verdict.
Part IV — What changes with three clusters.
- Why is a cluster-robust variance from three clusters unreliable?
- How many degrees of freedom does a test with three clusters have?
- Why can the clustered standard error be smaller than the robust one here?
- What could replace sector clustering with so few sectors?
- If the census had 300 villages, each with a few firms, would clustering by village help?
- Does the bootstrap solve the problem of three clusters?
- State the result: the capital elasticity with robust and clustered intervals, and the verdict on constant returns.
Solution
Solution of Problem 31.1.
Part I. 1. A Cobb–Douglas function . 2. Elasticities: the per cent change in output for a 1 per cent change in workers, or in capital, the other fixed. 3. , , ; . 4. Returns to scale: 1.0014 here, close to one. 5. A firm that knows it is productive hires more; is then correlated with , and is biased upward. Part II. 6. 0.0124. 7. 0.0120; interval , from 0.328 to 0.375. 8. 0.0044. 9. The distribution with degrees of freedom: 4.303. 10. , from 0.333 to 0.371. 11. The clustered one is the smallest, about a third of the others. It should not reassure: with three clusters the middle of the sandwich is a sum of three terms, and can be far too small by chance. Part III. 12. . 13. : log output per worker on log capital per worker. 14. 11.0341 restricted, 11.0329 unrestricted. 15. from the rounded sums, 0.053 from the unrounded ones: about 0.05. 16. Far below 3.86. 17. 0.055. 18. Constant returns are not rejected: the estimated sum is 1.0014. Part IV. 19. The cluster-robust variance is an average over clusters; with three it rests on three numbers. 20. Two. 21. Three sums of can happen to be small, or to cancel, so the estimate of the middle can fall below the robust one. 22. Robust standard errors with sector indicators in the regression, which remove anything shared by a sector from the error. 23. Yes, if errors are correlated within villages: 300 clusters are enough for the large-sample results. 24. No: drawing whole sectors with replacement from three sectors still gives only a handful of distinct samples. 25. Brenland’s capital elasticity is 0.352, with a robust 95 per cent interval of 0.328 to 0.375 and a sector-clustered one of 0.333 to 0.371 that should not be trusted with three clusters; constant returns to scale are not rejected ().