typestar

Generalised linear models in Python

One framework, a family per response type: binomial, Poisson, Gaussian.

import numpy as np
import statsmodels.api as sm

rng = np.random.default_rng(9)
sessions = rng.uniform(1, 10, size=200)
errors = rng.poisson(np.exp(0.2 + 0.15 * sessions))

X = sm.add_constant(sessions)
poisson = sm.GLM(errors, X, family=sm.families.Poisson()).fit()

print(poisson.params.round(4))
print(round(poisson.deviance, 2), poisson.df_resid)
print(round(poisson.pearson_chi2 / poisson.df_resid, 3), "dispersion")

binomial = sm.GLM(rng.binomial(1, 0.4, 200), X,
                  family=sm.families.Binomial()).fit()
print(round(binomial.aic, 2))

How it works

  1. The family sets the link and the variance function.
  2. Poisson suits counts; binomial suits proportions.
  3. Deviance and Pearson chi-square judge the fit.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
537
Tokens
172
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 94 seconds.

Type this snippet

Step 2 of 4 in Beyond least squares, step 10 of 19 in Statistics with statsmodels.

← Previous Next →