Generalized least squares: GLS, WLS and FGLS
Develop GLS, WLS, feasible GLS, AR(1) corrections and seemingly unrelated regressions, and weigh efficiency from modeling covariance against robust inference.
After this lesson you can
- Prove Aitken's theorem by reducing GLS to OLS on a whitened model.
- Implement WLS and FGLS with parametric variance and compare efficiency with OLS plus HC3.
- Implement Cochrane-Orcutt and Prais-Winsten and explain the role of strict exogeneity.
- Estimate SUR and show coefficient equivalence to OLS when equations share regressors.
- Choose between modeling variance with GLS and robustifying OLS inference.
Before you start
How much weight does each mean get?
Compare mean response times of teams with very different sample sizes. If each mean comes from independent observations with the same individual variance, a large group’s mean has lower variance. Treating all means equally can waste information. But if members of a team share shocks, variance of the mean need not remain inversely proportional to size.
Modeling covariance can gain efficiency when its structure is correct. That promise depends on error assumptions and target: weighting groups can also change the population represented by the coefficient when relationships differ across groups.
Aitken and the change in geometry
Let , with full-column-rank , and , where is known, symmetric and positive definite. Generalized least squares is
If is a Cholesky factorization, satisfies . Transformed model has spherical errors and OLS on it gives the preceding formula. Symmetric root is another valid whitening: it need not equal , but both transformations give the same estimator.
To prove optimality, write any conditionally unbiased linear estimator as with . Let and . Then and cross terms vanish:
This is the Loewner order of Aitken’s theorem: the difference is positive semidefinite; it does not mean every GLS realization is closer to . The result compares unbiased linear estimators with correctly specified covariance; it claims neither normality nor efficiency against every biased or nonlinear estimator.
Conditional GLS covariance is . The figure uses two observations and one design column: its axes describe errors across observations, not two explanatory variables. Changing ellipse orientation or length changes the metric and can change the fitted slope. The same covariance algebra appears in Gaussian processes, although the chosen joint distribution also matters there.
Prediction is an idempotent projection, generally oblique for the Euclidean product. Its residual satisfies : it is orthogonal in the weighted product. Spherical covariance recovers ordinary geometry.
Precision weights and estimand
In WLS, is diagonal and minimizing weights each squared residual by inverse variance. Units matter: precision weight is proportional to , not . If an observation is a mean of iid data with common variance , its variance is and weight proportional to is justified.
With within-group correlation that rule can fail. With heterogeneous effects, weighting by size also changes the group average approximated by regression. Specify whether you care about a team or individual mean before choosing weights.
For example, if a group contains observations with individual variance and common correlation , its mean variance is . The equicorrelation matrix requires and is singular at endpoints. With , multiplying the same group’s sample does not make the shared component disappear. If means of different groups are uncorrelated with positive variances, precision weight is inversely proportional to that whole expression; with between-group correlation full covariance is needed, not just its diagonal.
Even with positive weights, WLS and OLS need not share the same projection if the CEF is nonlinear. Retaining the same requires conditions such as ; a correctly linear CEF with conditional exogeneity suffices for suitable weights depending on . A counterexample: , and . With intercept, OLS slope is zero by symmetry; under the distribution tilted by , and weighted slope is . Weights changed the question even though both calculations are consistent for their own projections.
Estimating variance
Feasible GLS replaces with an estimate. One heteroskedasticity strategy fits OLS, models with covariates and refits using estimated inverse weights. This is a proposed model, not an automatic correction: if variance is misspecified or the sample small, the feasible estimator can lose precision.
If and is standard normal, regressing on the model of shifts the intercept by . A common multiplicative factor does not change WLS coefficients, but matters when interpreting variance scale. Zero residuals require an explicit truncation policy whose influence should be studied.
The lab first estimates the mean and uses its residuals, not true errors. That adds uncertainty and makes the auxiliary regression different from observing . In the experiment oracle WLS knows generator variance; it is an inaccessible reference when that variance is unknown. The figure distinguishes it from FGLS and the fit with deliberately opposite weights.
When weights converge to an incorrect positive function, naive variance based on that model can be miscalibrated even if the coefficient retains its target. For independent observations, a sandwich for the weighted equation can use scores ; temporal or clustered dependence also requires adapting the meat. OLS with HC3 or HAC may be a more robust reference if covariance structure is uncertain.
AR(1) errors: keep or discard the first observation
Suppose , , spherical innovations and a stationary initial condition. For , quasi-differencing gives
Cochrane-Orcutt discards the first transformed observation. Prais-Winsten retains it by multiplying and by under the stationary-variance convention. If is unknown, transformed regression and a residual-based update can alternate. Document initialization, convergence, constraint and first-observation treatment; iteration does not guarantee a unique optimum.
Strict exogeneity is a common sufficient condition for conditional interpretation of these transformations. If is a regressor and AR errors are correlated, the lagged term is often correlated with current error and naive fitting can be inconsistent. Not every model with a lagged dependent variable fails: with iid innovations and suitable assumptions, an autoregression can be consistently estimated.
For given , Prais-Winsten is checked against GLS with full AR(1) covariance. statsmodels GLSAR removes initial observations when whitening; it is not the same transformation as Prais-Winsten and exact equality should not be required.
The first-observation transformation follows from the stationary distribution: if innovation variance is , that of is , and multiplying by matches its variance to subsequent innovations. If that initial condition fails, the first row must change. Autoregressive models permit study of structures more general than AR(1), at the cost of estimating more covariance components.
A system of seemingly unrelated regressions
In SUR, each equation has its own regressors, but errors can be correlated at the same date. If equations share aligned times and cross-equation covariance is , with serial independence and constant contemporaneous covariance, covariance stacked by equation is . GLS exploits contemporaneous correlation; FGLS estimates from initial residuals.
If all regressor blocks equal the same matrix , SUR equals equation-by-equation OLS. The GLS normal matrix is , its inverse is and factors cancel. If is diagonal, equations also decouple even if regressors differ. Otherwise, a possible efficiency gain depends on covariance and regressor overlap; it is not guaranteed for a finite feasible estimator.
The contemporaneous-independence LM test is commonly expressed as and uses an asymptotic reference under its assumptions. It does not demonstrate absence of temporal dependence. Zellner’s method assumes corresponding observations are aligned; in Grunfeld match years before stacking firms and recognize these are observational data.
A practical SUR review compares three distinct objects: equation-level OLS predictions, SUR coefficients and uncertainty matrices associated with the chosen model. A difference in standard errors alone does not prove the system is better specified. In the lab, cross-equation covariance is estimated from the same data and the time dimension is small, so displayed errors should be read as model-dependent .
Labs: from transformation to system
First check Cholesky GLS and WLS against statsmodels; then estimate exponential weights from residuals. The simulation’s CEF is linear: in this case the considered weights share an estimand. Comparisons are paired and variance fitting uses the same sample; results are not a guarantee for other models.
"""GLS por Cholesky, WLS, FGLS de varianza exponencial y comparación simulada."""
import numpy as np
import statsmodels.api as sm
from scipy.special import digamma
assert np.allclose(digamma(.5)+np.log(2),-np.euler_gamma-np.log(2))
print('Desplazamiento E[log χ²(1)]:',digamma(.5)+np.log(2))
def fit_weighted(y, X, weights):
"""QR de sqrt(w)X; devuelve beta y covarianzas modelada, HC0 y HC3."""
y=np.asarray(y,float); X=np.asarray(X,float); weights=np.asarray(weights,float)
n,p=X.shape
if len(y)!=n or weights.shape!=(n,) or n<=p or np.any(weights<=0) or not np.isfinite(weights).all():
raise ValueError('Pesos, datos o dimensiones inválidos')
if np.linalg.matrix_rank(X)!=p: raise ValueError('Diseño sin rango completo')
root=np.sqrt(weights)
Z=X*root[:,None]; z=y*root
Q,R=np.linalg.qr(Z,mode='reduced')
beta=np.linalg.solve(R,Q.T@z)
error=y-X@beta
invR=np.linalg.solve(R,np.eye(p)); [email protected]
classic=bread*np.sum(weights*error**2)/(n-p)
score=X*(weights*error)[:,None]
robust=bread@(score.T@score)@bread
leverage=np.sum(Q*Q,axis=1)
if np.any(leverage>=1-1e-12): raise ValueError('Apalancamiento demasiado alto')
adjusted=score/(1-leverage)[:,None]
hc3=bread@(adjusted.T@adjusted)@bread
return beta,classic,robust,hc3,error
def gls_cholesky(y,X,omega):
"""omega=LLᵀ, blanqueo mediante L⁻¹, sin formar Ω⁻¹."""
L=np.linalg.cholesky(omega)
Xw=np.linalg.solve(L,X); yw=np.linalg.solve(L,y)
Q,R=np.linalg.qr(Xw,mode='reduced')
return np.linalg.solve(R,Q.T@yw)
rng=np.random.default_rng(270301)
n=120
x=rng.uniform(-1,1,n)
X=np.column_stack((np.ones(n),x))
variance=np.exp(1.5*x)
y=1+2*x+np.sqrt(variance)*rng.normal(size=n)
omega=np.diag(variance)
b_gls=gls_cholesky(y,X,omega)
b_wls,c_wls,c_robust,c_hc3,resid=fit_weighted(y,X,1/variance)
assert np.allclose(b_gls,sm.GLS(y,X,sigma=omega).fit().params,rtol=1e-10,atol=1e-10)
reference=sm.WLS(y,X,weights=1/variance).fit()
assert np.allclose(b_wls,b_gls) and np.allclose(b_wls,reference.params)
assert np.allclose(c_wls,reference.cov_params())
assert np.allclose(c_robust,reference.get_robustcov_results(cov_type='HC0').cov_params())
assert np.allclose(c_hc3,reference.get_robustcov_results(cov_type='HC3').cov_params())
print('GLS, WLS y statsmodels, coeficientes:',b_gls,b_wls,reference.params)
print('EE WLS modelo / HC0 transformado:',np.sqrt(np.diag(c_wls)),np.sqrt(np.diag(c_robust)))
# El modelo condicional es lineal; la media OLS y las medias ponderadas tienen
# el mismo parámetro. La varianza verdadera solo se usa como oráculo.
REPS=400
errors=[]
cover=[]
for _ in range(REPS):
x=rng.uniform(-1,1,n)
X=np.column_stack((np.ones(n),x))
y=1+2*x+np.exp(.75*x)*rng.normal(size=n)
b0,c0,h0,h3,e0=fit_weighted(y,X,np.ones(n))
be,ce,he,he3,_=fit_weighted(y,X,np.exp(-1.5*x))
bw,cw,hw,hw3,_=fit_weighted(y,X,np.exp(1.5*x))
# E[log(u²)|x]=log σ²(x)+E[log ε²]; la constante común cancela en WLS.
# El suelo limita log(0), y puede introducir sesgo en muestras finitas.
logvariance=np.linalg.lstsq(X,np.log(np.maximum(e0**2,1e-12)),rcond=None)[0]
bf,cf,hf,hf3,_=fit_weighted(y,X,np.exp(-X@logvariance))
estimates=np.array([b0[1],be[1],bw[1],bf[1]])
errors.append((estimates-2)**2)
z=1.959963984540054
cover.append([abs(b0[1]-2)<=z*np.sqrt(h3[1,1]),abs(bw[1]-2)<=z*np.sqrt(cw[1,1]),abs(bw[1]-2)<=z*np.sqrt(hw3[1,1])])
errors=np.asarray(errors); cover=np.asarray(cover)
print('Réplica:',REPS,'ECM pendiente OLS / WLS oráculo / WLS inverso / FGLS:',errors.mean(axis=0))
print('Cobertura normal: OLS HC3 / WLS inverso modelo / WLS inverso HC3:',cover.mean(axis=0),
'EE Monte Carlo:',np.sqrt(cover.mean(axis=0)*(1-cover.mean(axis=0))/REPS))
print('Comparaciones emparejadas; la eficiencia estimada es de esta simulación, no una garantía finita.')With fixed ρ, compare Prais-Winsten with full GLS and Cochrane-Orcutt with GLSAR; then run the iteration. The next simulation cell reuses those functions: run them in order.
"""Prais-Winsten y Cochrane-Orcutt, mismos datos y convenciones explícitas."""
import numpy as np
import statsmodels.api as sm
def pw_at_rho(y,X,rho):
if not -1<rho<1: raise ValueError('Prais-Winsten requiere |rho|<1')
y_t=np.r_[np.sqrt(1-rho*rho)*y[0],y[1:]-rho*y[:-1]]
X_t=np.vstack((np.sqrt(1-rho*rho)*X[0],X[1:]-rho*X[:-1]))
return np.linalg.lstsq(X_t,y_t,rcond=None)[0]
def co_at_rho(y,X,rho):
return np.linalg.lstsq(X[1:]-rho*X[:-1],y[1:]-rho*y[:-1],rcond=None)[0]
def prais_winsten(y,X,tol=1e-8,maxiter=200):
beta=np.linalg.lstsq(X,y,rcond=None)[0]
rho=0.
for iteration in range(1,maxiter+1):
resid=y-X@beta
denom=resid[:-1]@resid[:-1]
if denom<=1e-14: raise ValueError('No se puede estimar rho')
newrho=(resid[1:]@resid[:-1])/denom
if abs(newrho)>=1: raise ValueError('Estimación de rho fuera de (−1,1)')
updated=pw_at_rho(y,X,newrho)
if abs(newrho-rho)<tol and np.linalg.norm(updated-beta)<tol:
return updated,float(newrho),iteration,True
beta,rho=updated,newrho
return beta,float(rho),maxiter,False
gen=np.random.default_rng(270302)
n=140; rho_true=.65
x=gen.normal(size=n)
error=np.empty(n); error[0]=gen.normal()
for i in range(1,n):
error[i]=rho_true*error[i-1]+np.sqrt(1-rho_true**2)*gen.normal()
X=np.column_stack((np.ones(n),x)); y=1+1.5*x+error
omega=rho_true**np.abs(np.arange(n)[:,None]-np.arange(n)[None,:])
pw=pw_at_rho(y,X,rho_true)
ref=sm.GLS(y,X,sigma=omega).fit().params
co=co_at_rho(y,X,rho_true)
glsar=sm.GLSAR(y,X,rho=[rho_true]).fit().params
assert np.allclose(pw,ref,atol=1e-10) and np.allclose(co,glsar,atol=1e-10)
print('ρ fijado, PW y GLS con covarianza completa:',pw,ref)
print('ρ fijado, Cochrane-Orcutt y GLSAR (primera observación excluida):',co,glsar)
bp,rhop,niter,converged=prais_winsten(y,X)
assert converged
other=sm.GLSAR(y,X,rho=1); fitted=other.iterative_fit(maxiter=200,rtol=1e-8)
print('Prais-Winsten iterado: coeficientes, ρ, pasos, convergió:',bp,rhop,niter,converged)
print('GLSAR iterado: coeficientes, ρ:',fitted.params,other.rho)
print('Las diferencias reflejan primera observación y actualización: no se presupone igualdad de las iteraciones.')
print('ρ fijado blanquea solo bajo el modelo AR(1) estacionario; la interpretación requiere exogeneidad del diseño.')"""ECM emparejado para OLS, PW oráculo y PW iterado con regresor exógeno."""
gen_eff=np.random.default_rng(270303)
replicas=240
size=80
rho_data=.65
squared=[]
failed=0
for _ in range(replicas):
xe=gen_eff.normal(size=size)
ue=np.empty(size); ue[0]=gen_eff.normal()
for j in range(1,size):
ue[j]=rho_data*ue[j-1]+np.sqrt(1-rho_data**2)*gen_eff.normal()
Xe=np.column_stack((np.ones(size),xe))
ye=1+1.5*xe+ue
bol=np.linalg.lstsq(Xe,ye,rcond=None)[0]
b_oracle=pw_at_rho(ye,Xe,rho_data)
try:
b_iter,_,_,converged=prais_winsten(ye,Xe)
except ValueError:
converged=False
if not converged:
failed+=1
continue
squared.append((np.array([bol[1],b_oracle[1],b_iter[1]])-1.5)**2)
squared=np.asarray(squared)
print('ECM de pendiente OLS, PW con ρ verdadero y PW iterado:',squared.mean(axis=0))
print('EE Monte Carlo de cada ECM:',squared.std(axis=0,ddof=1)/np.sqrt(len(squared)))
print('Réplicas completas / totales; fallidas:',len(squared),replicas,failed)
print('Se usan las mismas réplicas y el mismo subconjunto; resultados condicionados a convergencia.')In Grunfeld, years of three firms are aligned and contemporaneous covariance is estimated using OLS residuals. Standard errors depend on the time model and do not imply causality.
"""SUR factible de tres empresas de Grunfeld y propiedades verificables."""
import numpy as np
import statsmodels.api as sm
from scipy.stats import chi2
data=sm.datasets.grunfeld.load_pandas().data
firms=['General Motors','General Electric','US Steel']
frames=[data.loc[data.firm==name].sort_values('year').reset_index(drop=True) for name in firms]
years=frames[0].year.to_numpy()
assert all(np.array_equal(frame.year.to_numpy(),years) for frame in frames)
T=len(years); K=len(firms)
# Cambiar unidades afecta coeficientes numéricos, no al ajuste.
X=[np.column_stack([np.ones(T),frame.value.to_numpy()/1000,frame.capital.to_numpy()/1000]) for frame in frames]
y=[frame.invest.to_numpy()/1000 for frame in frames]
betas_ols=[np.linalg.lstsq(X[i],y[i],rcond=None)[0] for i in range(K)]
resid=np.column_stack([y[i]-X[i]@betas_ols[i] for i in range(K)])
sigma=resid.T@resid/T
if np.min(np.linalg.eigvalsh(sigma))<=0: raise ValueError('Covarianza entre ecuaciones singular')
def sur(designs,outcomes,covariance):
"""GLS del sistema con Ω=Σ⊗I_T, ordenado por ecuaciones."""
eqs=len(designs); n=len(outcomes[0])
if any(len(v)!=n for v in outcomes): raise ValueError('Panel no balanceado')
rows=eqs*n; p_total=sum(x.shape[1] for x in designs)
stacked=np.zeros((rows,p_total))
pos=0
for i,x in enumerate(designs):
p=x.shape[1]; stacked[i*n:(i+1)*n,pos:pos+p]=x; pos+=p
vector=np.concatenate(outcomes)
omega=np.kron(covariance,np.eye(n))
L=np.linalg.cholesky(omega)
weighted=np.linalg.solve(L,stacked); transformed=np.linalg.solve(L,vector)
Q,R=np.linalg.qr(weighted,mode='reduced')
beta=np.linalg.solve(R,Q.T@transformed)
invR=np.linalg.solve(R,np.eye(p_total))
return beta,[email protected]
bsur,covsur=sur(X,y,sigma)
bd,cd=sur(X,y,np.diag(np.diag(sigma)))
stacked_ols=np.concatenate(betas_ols)
assert np.allclose(bd,stacked_ols,atol=1e-9,rtol=1e-9)
# Con mismo diseño en cada ecuación, GLS equivale a OLS para Σ no diagonal.
shared=[X[0]]*K
common_ols=np.concatenate([np.linalg.lstsq(X[0],yi,rcond=None)[0] for yi in y])
common_sur,_=sur(shared,y,sigma)
assert np.allclose(common_sur,common_ols,atol=1e-9,rtol=1e-9)
print('Grunfeld:',firms,'años:',int(years[0]),int(years[-1]),'observaciones por ecuación:',T)
print('Σ de residuos OLS dividida por T:\n',sigma)
for i,name in enumerate(firms):
se_ols=np.sqrt(np.diag(cd)[3*i:3*i+3])
se_sur=np.sqrt(np.diag(covsur)[3*i:3*i+3])
print(name,'coef. OLS:',betas_ols[i],'coef. FGLS SUR:',bsur[3*i:3*i+3])
print('EE modelo diagonal y SUR, escala Σ/T:',se_ols,se_sur)
print('Máx. diferencia OLS/SUR con Σ diagonal:',np.max(np.abs(bd-stacked_ols)))
print('Máx. diferencia OLS/SUR con regresores comunes:',np.max(np.abs(common_sur-common_ols)))
# LM de independencia contemporánea bajo hipótesis del contraste clásico.
corr=np.corrcoef(resid,rowvar=False)
lm=T*sum(corr[i,j]**2 for i in range(K) for j in range(i+1,K))
df=K*(K-1)//2
print('BP entre ecuaciones: LM, gl, p:',lm,df,chi2.sf(lm,df))
print('Referencia χ²: hipótesis iid temporal apropiadas; no prueba ausencia de dependencia temporal.')
print('Datos observacionales, T pequeño y covarianza estimada: EE modelados no prueban eficiencia ni causalidad.')Exercises
Step 1 of 3. What follows from AX=A_GX=I?
Step 1 of 2. What is the system normal matrix?
import numpy as np
def prais_winsten(y,X,tol=1e-8,maxiter=200):
passimport numpy as np
sizes=np.array([4.,16.,64.])
weights=sizes/sizes.sum()
print('Pesos de precisión normalizados:',weights,'suma:',weights.sum())
# Compara la varianza teórica de una media equicorrelacionada con la suma matricial.
m,rho=10,.2
cov=np.full((m,m),rho)
np.fill_diagonal(cov,1.)
variance_matrix=np.ones(m)@[email protected](m)/m**2
variance_formula=(1+(m-1)*rho)/m
assert np.allclose(variance_matrix,variance_formula)
print('Varianza de media equicorrelacionada: matriz y fórmula:',variance_matrix,variance_formula)