lm: linear models

OLS, RLM (robust), GLM, QuantReg and MixedLM models with statsmodels, reported as APA tables, with the specification tests that suit each kind of model collected in one table.

import statsmodels.api as sm
from apatools.lm import lm, lm_report, lm_tests

results, metrics = lm(
    data,
    y,
    x,
    model=["ols", "rlm", "glm"],
    vif=True,
    pred_r_sq=True,
    ols_fit_cov_type="HC1",  # <model>_<stage>_<argument>
    rlm_model_M=sm.robust.norms.RamsayE(),
    glm_model_family=sm.families.Gaussian(),
)
print(lm_report(results, metrics))
print(lm_tests(results, format_pval=True, add_stars=True, decimal=3))

Arguments of the model constructor and of .fit() are passed as <model>_<stage>_<argument>: the model prefix (ols_, rlm_, glm_, qlm_, mlm_), then model_ (constructor) or fit_ (the .fit() call). Extra parameters: qlm_fit_q (the quantile), mlm_model_groups (the grouping variable), vif, formula and pred_r_sq.

Design choices and caveats

The coefficient table.

  • It is built from the fitted results at full precision.

  • The confidence level is 95 % (the statsmodels default), and the statistic column is called t or z as in the statsmodels summary (t for OLS, z for RLM and GLM). For mixed models the table also contains the variance parameters as rows.

  • Only the intercept is renamed to Intercept (intercept_name=); a regressor that merely contains const in its name is left alone.

Prediction metrics. pred_metrics and pred_r_sq hold every observation out in turn and refit the model (n fits): predicted R² is 1 - PRESS/SST, clipped to [-1, 1]. It is a cross-validation statistic, not a test.

lm_tests: what each kind of model gets. The classical OLS tests are not valid for the other models, so every model gets the diagnostics that are meaningful for it; QuantReg models are skipped with a warning. The tests check assumptions, specification and influence, not the quality of the fit. With many observations nearly every test rejects: look at the size of the departure, not only at the p-value.

  • OLS. Normality (Jarque–Bera, omnibus, Shapiro–Wilk); heteroskedasticity (Breusch–Pagan in Koenker’s studentized version, which is what R’s bptest does by default, and White’s test, whose degrees of freedom are the rank of the auxiliary regression, so dummy variables do not inflate them); functional form (Ramsey’s RESET with powers 2 to reset_power, default 3, as resettest in R); autocorrelation (Breusch–Godfrey and Durbin–Watson, only with lags, for data ordered in time); the Bonferroni outlier test (computed in closed form from the studentized residuals, without refitting the model n times) and the largest Cook’s distance; the largest VIF and the condition number of the design matrix (without p-values; the condition number is that of the raw design, not of a scaled one). The tests use the residuals, so they do not depend on the covariance estimator chosen for the standard errors.

  • GLM. Dispersion (Pearson χ²/df), the Cameron–Trivedi overdispersion test (Poisson), Pearson and deviance goodness of fit (Poisson, grouped binomial; not for ungrouped binary data, where they are meaningless), the Hosmer–Lemeshow test (binary), Pregibon’s link test, and Shapiro–Wilk of the randomized quantile residuals of Dunn and Smyth (normal under the fitted model for the Gaussian, Gamma, inverse Gaussian, Poisson, negative binomial and binary binomial families; seed makes the randomization reproducible), plus leverage, studentized residuals, Cook’s distance and the multicollinearity diagnostics.

  • RLM. Descriptive diagnostics without p-values: the smallest robust weight, the ratio of the robust scale to the OLS residual SD, the largest RLM–OLS coefficient difference in OLS standard errors, the leverage of the design and the multicollinearity diagnostics. A Hausman-type test against OLS is not offered: in simulations it was unreliable (its covariance difference is not positive semidefinite and the test rejected 16 % of correct models at the 5 % level). With approximate=True the classical tests are added on the robust residuals (Breusch–Pagan, White, RESET as a robust Wald test and, with lags, Breusch–Godfrey) and labelled approx.: their theory is for OLS, and in simulations they rejected about 4–8 % of correct models at the 5 % level.

  • MixedLM. The ICC and the likelihood-ratio test of the random effect for models with one random effect (with the boundary-corrected p-value, a 50:50 mixture of χ²(0) and χ²(1)), Shapiro–Wilk tests of the predicted random effects and of the conditional residuals (labelled approx.: both are confounded or shrunken), the Cook’s distance of deleting whole groups (one refit per group, up to max_refits groups) and the multicollinearity diagnostics. The ICC and mlm_r_sq use the same random-effects variance, including the variance components of vc_formula.

Formulas and groups. lm(formula=..., model="mlm", mlm_model_groups=...) aligns the groups with the rows that patsy kept when the data have missing values.

Where it differs from R

what

apatools

R

difference

Breusch–Pagan

Koenker’s studentized version

lmtest::bptest (studentized by default)

none (statistics agree to 1e-6)

RLM

statsmodels’ RLM (Huber)

MASS::rlm

coefficients within 0.2 %, standard errors within 2 %: different convergence rules and scale updates

MixedLM

statsmodels’ REML optimizer

lme4::lmer

fixed effects within about 0.5 %, standard errors and ICC within 2 %, the likelihood-ratio test within 1 %: statsmodels stops at a looser optimizer tolerance

GLM leverage, Cook’s distance

from statsmodels’ IRLS fit

hatvalues, cooks.distance

within 1e-4: the IRLS stops at a looser tolerance

Pregibon’s link test

refits with the squared linear predictor

the same, by hand

within 1e-3 (a refit)

Jarque–Bera

from the moments of the residuals

no function in base R

the same formula as the R packages that have one

Checked against

tests/test_r_lm.py compares with R (base R, lmtest, MASS, lme4), the numbers in the table above being the tolerances used. The test statistics, degrees of freedom and p-values of the OLS diagnostics, the dispersion and the Pearson and deviance goodness of fit of a Poisson GLM agree with R to 1e-5 or better. Not compared with R (there is no standard implementation to compare with): the Hosmer–Lemeshow and Cameron–Trivedi tests, the quantile-residual test, the group Cook’s distance of mixed models and the approximate tests of RLM; they are validated by their definitions and by simulations of their size and power.

Literature

The references cited in the docstrings of the functions of this module (they are collected from the docstrings when the documentation is built; the software that does the work is on the software page).

  • Allen, D. M. (1974). The relationship between variable selection and data augmentation and a method for prediction. Technometrics, 16(1), 125-127. https://doi.org/10.1080/00401706.1974.10489157

  • Belsley, D. A., Kuh, E., & Welsch, R. E. (1980). Regression diagnostics: Identifying influential data and sources of collinearity. Wiley. https://doi.org/10.1002/0471725153

  • Breusch, T. S. (1978). Testing for autocorrelation in dynamic linear models. Australian Economic Papers, 17(31), 334-355. https://doi.org/10.1111/j.1467-8454.1978.tb00635.x

  • Cameron, A. C., & Trivedi, P. K. (1990). Regression-based tests for overdispersion in the Poisson model. Journal of Econometrics, 46(3), 347-364. https://doi.org/10.1016/0304-4076(90)90014-K

  • Christensen, R., Pearson, L. M., & Johnson, W. (1992). Case-deletion diagnostics for mixed models. Technometrics, 34(1), 38-51. https://doi.org/10.2307/1269550

  • Cook, R. D. (1977). Detection of influential observation in linear regression. Technometrics, 19(1), 15-18. https://doi.org/10.1080/00401706.1977.10489493

  • D’Agostino, R., & Pearson, E. S. (1973). Tests for departure from normality. Empirical results for the distributions of b2 and sqrt(b1). Biometrika, 60(3), 613-622. https://doi.org/10.1093/biomet/60.3.613

  • Demidenko, E., & Stukel, T. A. (2005). Influence analysis for linear mixed-effects models. Statistics in Medicine, 24(6), 893-909. https://doi.org/10.1002/sim.1974

  • Dunn, P. K., & Smyth, G. K. (1996). Randomized quantile residuals. Journal of Computational and Graphical Statistics, 5(3), 236-244. https://doi.org/10.1080/10618600.1996.10474708

  • Durbin, J., & Watson, G. S. (1950). Testing for serial correlation in least squares regression. I. Biometrika, 37(3-4), 409-428. https://doi.org/10.1093/biomet/37.3-4.409

  • Durbin, J., & Watson, G. S. (1951). Testing for serial correlation in least squares regression. II. Biometrika, 38(1-2), 159-178. https://doi.org/10.1093/biomet/38.1-2.159

  • Godfrey, L. G. (1978). Testing against general autoregressive and moving average error models when the regressors include lagged dependent variables. Econometrica, 46(6), 1293-1301. https://doi.org/10.2307/1913829

  • Hosmer, D. W., & Lemeshow, S. (1980). Goodness of fit tests for the multiple logistic regression model. Communications in Statistics - Theory and Methods, 9(10), 1043-1069. https://doi.org/10.1080/03610928008827941

  • Huber, P. J., & Ronchetti, E. M. (2009). Robust Statistics (2nd ed.). Wiley. https://doi.org/10.1002/9780470434697

  • Jarque, C. M., & Bera, A. K. (1980). Efficient tests for normality, homoscedasticity and serial independence of regression residuals. Economics Letters, 6(3), 255-259. https://doi.org/10.1016/0165-1765(80)90024-5

  • Johnson, P. C. D. (2014). Extension of Nakagawa & Schielzeth’s R²GLMM to random slopes models. Methods in Ecology and Evolution, 5(9), 944-946. https://doi.org/10.1111/2041-210X.12225

  • Koenker, R. (1981). A note on studentizing a test for heteroscedasticity. Journal of Econometrics, 17(1), 107-112. https://doi.org/10.1016/0304-4076(81)90062-2

  • Lange, N., & Ryan, L. (1989). Assessing normality in random effects models. The Annals of Statistics, 17(2), 624-642. https://doi.org/10.1214/aos/1176347130

  • McCullagh, P., & Nelder, J. A. (1989). Generalized Linear Models (2nd ed.). Chapman & Hall. https://doi.org/10.1007/978-1-4899-3242-6

  • Nakagawa, S., & Schielzeth, H. (2010). Repeatability for Gaussian and non-Gaussian data: A practical guide for biologists. Biological Reviews, 85(4), 935-956. https://doi.org/10.1111/j.1469-185x.2010.00141.x

  • Nakagawa, S., & Schielzeth, H. (2013). A general and simple method for obtaining R² from generalized linear mixed-effects models. Methods in Ecology and Evolution, 4(2), 133-142. https://doi.org/10.1111/j.2041-210x.2012.00261.x

  • Pregibon, D. (1980). Goodness of link tests for generalized linear models. Applied Statistics, 29(1), 15-23. https://doi.org/10.2307/2346405

  • Pregibon, D. (1981). Logistic regression diagnostics. The Annals of Statistics, 9(4), 705-724. https://doi.org/10.1214/aos/1176345513

  • Ramsey, J. B. (1969). Tests for specification errors in classical linear least-squares regression analysis. Journal of the Royal Statistical Society Series B: Statistical Methodology, 31(2), 350-371. https://doi.org/10.1111/j.2517-6161.1969.tb00796.x

  • Roberts, D. R., Bahn, V., Ciuti, S., Boyce, M. S., Elith, J., Guillera-Arroita, G., Hauenstein, S., Lahoz-Monfort, J. J., Schröder, B., Thuiller, W., Warton, D. I., Wintle, B. A., Hartig, F., & Dormann, C. F. (2017). Cross-validation strategies for data with temporal, spatial, hierarchical, or phylogenetic structure. Ecography, 40(8), 913-929. https://doi.org/10.1111/ecog.02881

  • Rousseeuw, P. J., & Leroy, A. M. (1987). Robust regression and outlier detection. Wiley. https://doi.org/10.1002/0471725382

  • Santos Nobre, J., & da Motta Singer, J. (2007). Residual analysis for linear mixed models. Biometrical Journal, 49(6), 863-875. https://doi.org/10.1002/bimj.200610341

  • Self, S. G., & Liang, K.-Y. (1987). Asymptotic properties of maximum likelihood estimators and likelihood ratio tests under nonstandard conditions. Journal of the American Statistical Association, 82(398), 605-610. https://doi.org/10.1080/01621459.1987.10478472

  • Shapiro, S. S., & Wilk, M. B. (1965). An analysis of variance test for normality (complete samples). Biometrika, 52(3-4), 591-611. https://doi.org/10.1093/biomet/52.3-4.591

  • Singer, J. M., Rocha, F. M. M., & Nobre, J. S. (2017). Graphical tools for detecting departures from linear mixed model assumptions and some remedial measures. International Statistical Review, 85(2), 290-324. https://doi.org/10.1111/insr.12178

  • Stram, D. O., & Lee, J. W. (1994). Variance components testing in the longitudinal mixed effects model. Biometrics, 50(4), 1171-1177. https://doi.org/10.2307/2533455

  • White, H. (1980). A heteroskedasticity-consistent covariance matrix estimator and a direct test for heteroskedasticity. Econometrica, 48(4), 817-838. https://doi.org/10.2307/1912934