lm: linear models (statsmodels)

The user guide of this module: lm.

apatools.lm.vif(results, sort=False, decimal=2)[source]

Variance inflation factors (VIF), a measure of multicollinearity.

The VIF of a predictor is 1 / (1 - R²_j), where R²_j is the R² of the regression of that column of the design matrix on all the other columns (see statsmodels.stats.outliers_influence.variance_inflation_factor()). As a rule of thumb, VIF > 5 (some authors use 10) indicates that the variable is highly collinear with the other input variables. The VIF is computed for every column of results.model.exog, including the constant; the VIF of the constant is not interpretable as a collinearity diagnostic (and is large when the predictors are not centered), ignore it.

Parameters:
  • results (statsmodels results object) – Fitted model (OLS, RLM, GLM, QuantReg, MixedLM) with results.model.exog and results.model.exog_names.

  • sort (bool, default False) – If True, sort the rows by VIF in ascending order.

  • decimal (int or None, default 2) – Round the VIFs to this number of decimals; None or 0 keeps the full precision.

Returns:

pandas.DataFrame or None – A single column vif, indexed by the names of the design matrix columns (results.model.exog_names). If the calculation fails for any reason, a UserWarning is issued and None is returned.

References

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

apatools.lm.mlm_wrapper(Y, X, **kwargs)[source]

Constructor of statsmodels.regression.mixed_linear_model.MixedLM with groups as a keyword.

MixedLM(endog, exog, groups, ...) takes the grouping variable as the third positional argument, whereas fit_model() calls every model class as model(Y, X, **model_kwargs). This wrapper makes groups an ordinary keyword argument (mlm_model_groups in lm()).

Parameters:
  • Y (array-like or pandas.Series) – Dependent variable.

  • X (array-like or pandas.DataFrame) – Design matrix of the fixed effects (include the constant yourself if wanted).

  • **kwargs – groups (required, array-like of group labels, one per row; KeyError if missing), and any other keyword argument of MixedLM (e.g. exog_re, re_formula, use_sqrt).

Returns:

statsmodels.regression.mixed_linear_model.MixedLM – The unfitted model.

apatools.lm.fit_model(model, Y, X, **kwargs)[source]

Generator that fits one or several statsmodels models and yields the fitted results.

Parameters:
  • model (str, statsmodels model class, or list/tuple of them) – A string is one of "ols" (sm.OLS), "rlm" (sm.RLM), "glm" (sm.GLM), "qlm" (sm.QuantReg) or "mlm" (sm.MixedLM, built with mlm_wrapper()); anything else raises NotImplementedError. A class (e.g. a custom model with the signature model(Y, X, **kw).fit(**kw)) is used as is. A list or tuple yields one result per entry, in order.

  • Y (array-like or pandas.Series) – Dependent variable.

  • X (array-like or pandas.DataFrame) – Design matrix (the constant is not added here).

  • **kwargs – verbose (bool, default False) prints the model name and the arguments passed on. Arguments for statsmodels are selected by prefix, <model>_<stage>_<argument>: <model> is ols, rlm, glm, qlm or mlm (the prefix is dropped first; for a custom class the keywords are used without a model prefix), <stage> is model (passed to the constructor, e.g. glm_model_family or mlm_model_groups) or fit (passed to .fit(), e.g. ols_fit_cov_type="HC1", qlm_fit_q=0.5). Keywords that match none of the prefixes are ignored.

Yields:

statsmodels results object – The result of model(Y, X, **model_kwargs).fit(**fit_kwargs).

Raises:

NotImplementedError – For an unknown model name.

apatools.lm.pred_metrics(model, Y, X, **kwargs)[source]

Leave-one-out prediction metrics (R²pred, MAEpred, MADpred) of statsmodels models.

A cross-validation-style metric: every observation i is held out in turn, the model is refitted on the remaining n - 1 rows and y_i is predicted from x_i (the prediction error is the PRESS residual; for OLS see Allen, 1974). It needs one refit per observation and model (n fits). Refits that fail are skipped and reported in a single UserWarning.

The metrics are, with e_i = y_i - ŷ_(i) the leave-one-out errors:

  • pred_loo_r_sq = 1 - Σ e_i² / (n · var(y)), i.e. 1 - PRESS / SST with the total sum of squares around the mean of all y, clipped to [-1, 1] (also known as predicted R² or Q²);

  • pred_loo_mae = mean of |e_i|;

  • pred_loo_mad = median of |e_i - median(e)| (median absolute deviation, not rescaled to the normal SD).

Warning

Plain leave-one-out treats rows as independent. For grouped (mlm), spatial or temporal data the rows that are held out stay correlated with the training sample, which makes the metrics optimistic; see Roberts et al. (2017) and, for spatial data, apatools.slm.pred_metrics(). For mixed models the held-out observation is predicted from the fixed effects only (results.predict) while its group stays in the training sample.

Parameters:
  • model (str, class, or list of them) – The model(s) as in fit_model().

  • Y (pandas.Series) – Dependent variable (positional indexing with .iloc is used).

  • X (pandas.DataFrame) – Design matrix, including the constant if the model has one.

  • **kwargs – The model arguments as passed to lm(), see fit_model(). verbose is switched off. mlm_model_groups must be a pandas.Series aligned with X (it is subset together with the training rows).

Returns:

list of dict – One dict per model with the keys pred_loo_r_sq, pred_loo_mae and pred_loo_mad.

References

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

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

apatools.lm.mlm_icc(results)[source]

Intraclass correlation coefficient (ICC) of a fitted mixed model (approximate).

ICC = τ² / (τ² + σ²), the share of the (non-fixed-effect) variance that lies between groups. τ² is the random-effects variance, the sum of the diagonal of the random-effects covariance matrix results.cov_re plus the variance components declared with vc_formula (results.vcomp, if any; the same τ² as in mlm_r_sq()), and σ² is the residual variance results.scale. For a random-intercept model cov_re is 1x1 and this is the usual ICC. For random-slope models the sum of the variances of intercepts and slopes is used, which is not a proper ICC (it also depends on the values of the predictors), so a UserWarning is issued whenever cov_re is not 1x1.

Parameters:

results (statsmodels.regression.mixed_linear_model.MixedLMResults) – Fitted mixed model (model="mlm" of lm()).

Returns:

float – ICC in [0, 1].

References

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

apatools.lm.mlm_r_sq(results)[source]

Marginal and conditional R² of a fitted linear mixed model (Nakagawa & Schielzeth).

With σ²_f the variance of the fixed-effects linear predictor (np.var(X @ fe_params)), σ²_r the random-effects variance (sum of the diagonal of results.cov_re plus the variance components results.vcomp, if any) and σ²_e the residual variance (results.scale):

R²_m = σ²_f / (σ²_f + σ²_r + σ²_e)
R²_c = (σ²_f + σ²_r) / (σ²_f + σ²_r + σ²_e)

R²_m is the variance explained by the fixed effects alone, R²_c the variance explained by fixed and random effects together. For random-slope models summing the diagonal of cov_re is only an approximation of the random-effects variance (the exact value depends on the predictors); Nakagawa & Schielzeth (2013) and Johnson (2014) give the full formulas.

Parameters:

results (statsmodels.regression.mixed_linear_model.MixedLMResults) – Fitted mixed model.

Returns:

r2_m, r2_c (float) – Marginal and conditional R².

References

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

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

apatools.lm.base_metrics(results)[source]

Calculating/retrieving R²/R²pseudo, R²adj and other fit metrics for OLS, RLM, GLM, QuantReg and MLM from statsmodels fitting results.

Every value is taken from the results object when statsmodels provides a finite one and is computed here otherwise (so the function also works for results objects that lack some attributes). Non-finite values from statsmodels are replaced by the computed ones.

  • r_sq: for mixed models the conditional R² (r_sq_c, see mlm_r_sq()); for other models pseudo_rsquared (QuantReg, GLM where available) or prsquared, then rsquared (OLS, RLM), else 1 - SSe / SSt with the (weighted) sums of squares of the residuals and of the observed values around their mean.

  • r_sq_adj: rsquared_adj if available, else 1 - (1 - R²)(n - c) / df_resid with c = 1 if the model has a constant, else 0.

  • f_stat / f_pvalue: fvalue / f_pvalue of the results, else (R² / df_model) / ((1 - R²) / df_resid) and its F-distribution p-value.

  • df_model and df_resid are corrected to be at least the number of predictors (without constant) and n - df_model, respectively.

Parameters:

results (statsmodels results object) – Fitted OLS, RLM, GLM, QuantReg or MixedLM results.

Returns:

dict – Always present: r_sq, r_sq_adj, df_model, df_resid, f_stat, f_pvalue, n_obs, n_params (predictors without the constant), mae (mean absolute residual) and mad (median absolute deviation of the residuals: median(|e - median(e)|), not rescaled). Present when finite/available: aic, bic (bic_llf if the results have it, else bic), llf. Mixed models add r_sq_c (= r_sq), r_sq_m (marginal R²) and, if the model has that attribute, n_groups.

Warns:

UserWarning – If the model has no predictors or zero model degrees of freedom.

Notes

For robust (RLM) and weighted models there is no single accepted R²; the value reported is the one returned by statsmodels (see Rousseeuw & Leroy, 1987, p. 42, and https://stats.stackexchange.com/questions/83826). The F statistic of a mixed model is only a rough heuristic computed from the conditional R².

References

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

apatools.lm.lm(data, y=None, x=None, model='ols', formula=None, **kwargs)[source]

Fit OLS, RLM, GLM, QuantReg or MixedLM models with statsmodels.

Parameters:
  • data (pandas.DataFrame) – The data.

  • y (str) – Dependent variable (column name). Not used if formula is given.

  • x (list of str) – Predictor column names (without the constant). Not used if formula is given.

  • model (str or list of str) – "ols", "rlm" (robust linear model), "glm" (generalized linear model), "qlm" (quantile regression) or "mlm" (linear mixed model), or a list of them. Every entry is fitted on the same data.

  • formula (str, optional) – statsmodels/patsy formula; overrides y/x, intercept and dropna (patsy always drops rows with NAs and adds an intercept unless - 1 is used).

  • **kwargs – Options of this function (below) and arguments for statsmodels, named <model>_<stage>_<argument>: <model> is ols/rlm/glm/qlm/mlm; <stage> is model (passed to the constructor) or fit (passed to .fit()), e.g. ols_fit_cov_type or glm_model_family. mlm_model_groups may be a column name of data (required for "mlm").

  • verbose (bool, default True) – Print the sample size, the formula and the statsmodels summary of every model.

  • dropna (bool, default True) – Drop rows with NAs in y/x (a UserWarning reports it). Ignored with formula.

  • intercept (bool, default True) – Add a constant to x. Ignored with formula.

  • standardize (False, True/"z" or callable, default False) – z-transform (or apply the callable to) every numeric/boolean column; other columns are dropped. The constant is left untouched. Combined with an intercept, z-scored data give an intercept estimate of zero and a UserWarning is issued.

  • base_metrics (bool, default True) – Compute base_metrics() for every model.

  • pred_metrics (bool, default False) – Add leave-one-out metrics (pred_metrics()); one refit per observation and model.

  • vif (bool, default False) – Add the vif() table of every model to the metrics (key "vif").

Returns:

  • results (list) – One fitted statsmodels results object per model.

  • metrics (list of dict) – One dict per model, see base_metrics(): r_sq, r_sq_adj, f_stat, f_pvalue, df_model, df_resid, aic/bic/llf (if available), mae, mad (median absolute deviation of the residuals), n_obs, n_params; mixed models also r_sq_m, r_sq_c and n_groups. With pred_metrics=True also pred_loo_r_sq, pred_loo_mae, pred_loo_mad; with vif=True also vif (a DataFrame, or None if it failed). The list is empty if neither base_metrics nor pred_metrics nor vif is requested.

Raises:

ValueError – If neither formula nor non-empty x together with y is given.

Notes

Requires statsmodels (and pandas for lm_report()).

Examples

>>> results, metrics = lm(
...     test_data, Y, X, model=["ols", "rlm"],
...     verbose=True,
...     intercept=True,  # ignored when formula is defined
...     dropna=True,  # ignored when formula is defined
...     standardize="z",  # keeps np.number or bool columns only
...     base_metrics=True,
...     pred_metrics=False,
...     vif=False,
...     qlm_fit_q=0.5,
...     qlm_fit_cov_type="boot",
...     qlm_fit_cov_kwds={"n_boot": 100},
...     ols_fit_cov_type="HC1",
...     rlm_model_M=sm.robust.norms.RamsayE(),
... )
apatools.lm.lm_report(results, metrics=None, format_pval=True, add_stars=True, decimal=3, add_ftest=True, add_aic=True, add_bic=True, add_llf=True, add_mae=True, add_mad=True, add_pred_loo_mae=True, add_pred_loo_mad=True, add_n_obs=True, add_n_groups=True, add_vif=True, intercept_name='Intercept')[source]

Build one APA-style coefficient table per model from lm() output.

Parameters:
  • results (list) – Fitted statsmodels results (first value returned by lm()).

  • metrics (list of dict, optional) – Metrics (second value returned by lm()), matched with results by position. If None or shorter than results, the tables of the models without metrics have no model column.

  • format_pval (bool or callable, default True) – False keeps the numeric p-values. True replaces them by APA strings without the p = prefix (".009", "<.001"; apatools.format.format_p()). A callable is applied to every p-value and its return value is used. The stars are always computed from the numeric p-values, whatever the value of this argument.

  • add_stars (bool or callable, default True) – False: no sig column. True: add a sig column with significance stars (*** p < .001, ** p < .01, * p < .05, ⁺ p < .10, otherwise an empty string; apatools.format.get_stars()). A callable maps one p-value to the marker.

  • decimal (int or None, default 3) – Round the columns coef, se, cil and cir to this many decimals; the test statistic, the p-values and the VIFs are not rounded here. None or 0 switches the rounding off.

  • add_ftest (bool, default True) – Include the corresponding part (F test, AIC, BIC, log-likelihood LL, MAE, MAD, MAEpred, MADpred, number of observations N, number of groups G) in the fit summary string, if the metric is available. (R², R²adj and R²pred are always shown when available.)

  • add_aic (bool, default True) – Include the corresponding part (F test, AIC, BIC, log-likelihood LL, MAE, MAD, MAEpred, MADpred, number of observations N, number of groups G) in the fit summary string, if the metric is available. (R², R²adj and R²pred are always shown when available.)

  • add_bic (bool, default True) – Include the corresponding part (F test, AIC, BIC, log-likelihood LL, MAE, MAD, MAEpred, MADpred, number of observations N, number of groups G) in the fit summary string, if the metric is available. (R², R²adj and R²pred are always shown when available.)

  • add_llf (bool, default True) – Include the corresponding part (F test, AIC, BIC, log-likelihood LL, MAE, MAD, MAEpred, MADpred, number of observations N, number of groups G) in the fit summary string, if the metric is available. (R², R²adj and R²pred are always shown when available.)

  • add_mae (bool, default True) – Include the corresponding part (F test, AIC, BIC, log-likelihood LL, MAE, MAD, MAEpred, MADpred, number of observations N, number of groups G) in the fit summary string, if the metric is available. (R², R²adj and R²pred are always shown when available.)

  • add_mad (bool, default True) – Include the corresponding part (F test, AIC, BIC, log-likelihood LL, MAE, MAD, MAEpred, MADpred, number of observations N, number of groups G) in the fit summary string, if the metric is available. (R², R²adj and R²pred are always shown when available.)

  • add_pred_loo_mae (bool, default True) – Include the corresponding part (F test, AIC, BIC, log-likelihood LL, MAE, MAD, MAEpred, MADpred, number of observations N, number of groups G) in the fit summary string, if the metric is available. (R², R²adj and R²pred are always shown when available.)

  • add_pred_loo_mad (bool, default True) – Include the corresponding part (F test, AIC, BIC, log-likelihood LL, MAE, MAD, MAEpred, MADpred, number of observations N, number of groups G) in the fit summary string, if the metric is available. (R², R²adj and R²pred are always shown when available.)

  • add_n_obs (bool, default True) – Include the corresponding part (F test, AIC, BIC, log-likelihood LL, MAE, MAD, MAEpred, MADpred, number of observations N, number of groups G) in the fit summary string, if the metric is available. (R², R²adj and R²pred are always shown when available.)

  • add_n_groups (bool, default True) – Include the corresponding part (F test, AIC, BIC, log-likelihood LL, MAE, MAD, MAEpred, MADpred, number of observations N, number of groups G) in the fit summary string, if the metric is available. (R², R²adj and R²pred are always shown when available.)

  • add_vif (bool, default True) – Join the vif column to the table if lm(..., vif=True) was used.

  • intercept_name (str, default "Intercept") – Row label of the constant (const, Intercept or CONSTANT); other labels are unchanged.

Returns:

list of pandas.DataFrame – One table per model (as many as the longer of results and metrics), indexed by the coefficient names, with the columns

  • coef: estimate; se: standard error;

  • the test statistic, named by statsmodels: t (OLS, QuantReg) or z (RLM, GLM, MixedLM);

  • p-value: p-value (formatted, see format_pval);

  • cil, cir: lower and upper limits of the 95% confidence interval (confidence level 0.95, as in the statsmodels summary);

  • sig: significance stars (if add_stars);

  • vif: variance inflation factor (if available and add_vif);

  • model: filled in the first row only (if metrics are given), the fit summary such as R² = .34, R²adj = .34, R²pred = .34, F(1, 416) = 6.71, p = .009, N = 418.

For mixed models the table also contains the variance parameters (e.g. Group Var) as rows.

Notes

The coefficients, standard errors, test statistics, p-values and 95% confidence limits (always confidence level 0.95, as in the statsmodels summary) are taken from the results at full precision (not from the rounded summary text). For mixed models the table is the summary table of statsmodels, which also contains the variance parameters.

apatools.lm.lm_tests(results, format_pval=False, add_stars=False, decimal=None, lags=None, reset_power=3, approximate=False, seed=13, max_refits=200)[source]

Diagnostic tests of the models fitted with lm(), as a tidy DataFrame.

The tests check the assumptions of the models, the specification and the influence of single observations; they are not measures of the quality of the fit (see base_metrics and pred_metrics for those). Every kind of model gets the diagnostics that are meaningful for it (the classical OLS tests are not valid for the other models, see below). Computed for every OLS, GLM, RLM and MixedLM model of results (a list as returned by lm()); QuantReg models are skipped with a warning.

OLS ("ols")

  • Normality of the residuals (null: normally distributed errors): Jarque-Bera (skewness and kurtosis; Jarque & Bera, 1980), the omnibus test of D’Agostino & Pearson (1973; the same ingredients, different combination) and Shapiro-Wilk (1965; the statistic is W, no df).

  • Homoskedasticity (null: constant error variance): Breusch-Pagan in the studentized version of Koenker (1981), which does not assume normal errors, and White (1980), which also detects misspecification of the variance by squares and cross products of the predictors. Breusch-Pagan has power against a variance that changes linearly with the predictors, White also against curved changes (e.g. a variance that grows with the square of a predictor). Both need a constant in the model; df is the number of auxiliary regressors.

  • Functional form (null: no omitted nonlinearity): Ramsey’s RESET (1969), an F test of the powers 2 to reset_power of the fitted values added to the model.

  • Autocorrelation (only with lags; null: no autocorrelation of the errors up to lags): Breusch-Godfrey LM test (Breusch, 1978; Godfrey, 1978) and the Durbin-Watson statistic (1950, 1951; about 2 without first-order autocorrelation, below 2 for positive autocorrelation; no p-value). They are only meaningful if the rows are ordered in time.

  • Outliers and influence: the Bonferroni outlier test (statistic: the largest absolute studentized residual; null: no outlier), and the largest Cook’s distance (1977; no p-value; the report says how many observations exceed the rule of thumb 4 / n).

  • Multicollinearity (no p-values): the largest variance inflation factor of the predictors (rule of thumb: values above 10 are a concern) and the condition number of the design matrix (Belsley et al., 1980: above 30 is a concern).

GLM ("glm"): the variance of a GLM depends on its mean by design, so raw-residual tests of OLS do not apply (for the Gaussian family with identity link fit an OLS model to get them).

  • Dispersion (no p-value): Pearson chi-square / df, about 1 for the Poisson and binomial families if the variance function is right (McCullagh & Nelder, 1989).

  • Poisson: the regression-based overdispersion test of Cameron & Trivedi (1990), a t test (null: variance = mean; two-sided).

  • Goodness of fit for the Poisson family and the binomial family with non-binary responses: the Pearson and deviance chi-square tests (df = residual df). They are approximations that need not-too-small expected counts. For binary responses: the Hosmer-Lemeshow test (1980; ten groups of fitted probabilities, df = 8), with the usual caveat that it depends on the grouping.

  • Link test of Pregibon (1980): z test of the squared linear predictor added to the model (null: the link function and the linear predictor are specified correctly; like RESET).

  • Normality of the randomized quantile residuals (Dunn & Smyth, 1996): Shapiro-Wilk test of residuals that are standard normal under the fitted model for any family (Gaussian, Gamma, inverse Gaussian, Poisson, negative binomial, binary binomial; a random draw for discrete responses, fixed by seed; the rejection rate under a correct model was 3.5-5% at the 5% level in simulations with 100 to 400 observations). Other families are skipped with a warning.

  • Influence (Pregibon, 1981): largest leverage (2k / n rule of thumb), largest studentized residual and largest Cook’s distance, without p-values; and the multicollinearity diagnostics.

RLM ("rlm"): M-estimators do not assume normal errors, and the classical test statistics were derived for the OLS fit. Without approximate only descriptive diagnostics are given (no p-values; Huber & Ronchetti, 2009; Rousseeuw & Leroy, 1987): the smallest robust weight (an observation with a weight far below 1 is treated as an outlier by the fit; the report counts the weights below .5), the ratio of the robust scale to the OLS residual standard deviation (well below 1 when outliers or heavy tails inflate the OLS estimate), the largest difference between the RLM and OLS coefficients in OLS standard errors, the largest leverage of the design and the multicollinearity diagnostics. A Hausman-type test of RLM against OLS is not offered: in simulations its covariance matrix difference was not positive definite in a large share of the samples, and the size was too large.

With approximate=True also Breusch-Pagan and White tests of the robust residuals, RESET as a robust Wald test of the powers of the fitted values in a refitted RLM and, with lags, Breusch-Godfrey and Durbin-Watson. They are approximations (labelled “approx.”): their null distributions were derived for OLS. In simulations with 200 observations and normal or t(3) errors the Breusch-Pagan and White tests rejected about 4-6.5% of the samples at the 5% level and RESET about 8%.

MixedLM ("mlm"): the residuals are confounded with the random effects, so the residual tests of OLS do not apply.

  • ICC of a random-intercept model (no p-value).

  • Likelihood-ratio test of the random effect (one random effect and no variance components): the ML fit against the model without random effect; the null value of a variance is on the boundary of the parameter space, so the p-value uses the 50:50 mixture of chi-squares with 0 and 1 df (Self & Liang, 1987; Stram & Lee, 1994), half of the usual chi-square p-value.

  • Normality of the predicted random effects (Lange & Ryan, 1989) and of the conditional residuals, Shapiro-Wilk tests (labelled “approx.”): the predicted random effects are shrunken towards zero and the conditional residuals are confounded with them, so non-normality is under-detected (Nobre & Singer, 2007; Singer et al., 2017).

  • Group influence: the largest Cook’s distance of deleting a whole group, (b - b_(g))' V^-1 (b - b_(g)) / k for the fixed effects (Christensen et al., 1992; Demidenko & Stukel, 2005), needs one refit per group (skipped for more than max_refits groups or with variance components).

  • The multicollinearity diagnostics of the fixed-effects design.

Parameters:
  • results (list of statsmodels results) – As returned by lm().

  • format_pval (bool or callable, default False) – Format the p-values as strings (True: APA style without the p, "<.001"; a callable receives one p-value); False keeps the numbers.

  • add_stars (bool or callable, default False) – Add a sig column with significance stars (True: apatools.format.get_stars(); or a callable). They are computed from the unformatted p-values.

  • decimal (int, optional) – Round statistic to this many decimals (None: no rounding).

  • lags (int, optional) – Number of lags of the Breusch-Godfrey test (OLS, and RLM with approximate); None leaves the autocorrelation tests out (they are meaningless for cross-sectional data).

  • reset_power (int, default 3) – Highest power of the fitted values in RESET (3: squares and cubes, as resettest in R).

  • approximate (bool, default False) – Add the approximate classical tests for RLM models (see above).

  • seed (int, default 13) – Seed of the random generator of the quantile residuals of discrete GLMs (a local generator).

  • max_refits (int, default 200) – Largest number of groups for which the group influence of MixedLM models is computed.

Returns:

pandas.DataFrame – One row per test with the columns test, model (ols, glm, rlm, mlm; a repeated model gets the suffix _2, …), statistic (chi-square, F, W, z, the Durbin-Watson statistic, the largest studentized residual, …), df and df_denom (NaN where not applicable), p-value (NaN for the statistics without a test), optionally sig, and an APA-style string report. Use format_pval=False, add_stars=False, decimal=None for the raw numbers.

Notes

With many observations nearly every test becomes significant, and among many tests some are by chance; look at the size of the departure (plots of the residuals, the influence of single observations), not only at the p-value. The OLS tests use the residuals, so they do not depend on the covariance estimator chosen for the standard errors (ols_fit_cov_type).

References

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

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

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

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

Rousseeuw, P. J., & Leroy, A. M. (1987). Robust Regression and Outlier Detection. Wiley. https://doi.org/10.1002/0471725382

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

Examples

>>> results, metrics = lm(df, "y", ["x1", "x2"], model=["ols", "rlm"])
>>> lm_tests(results, format_pval=True, add_stars=True, decimal=3)