Logo

Generalized Linear ModelsΒΆ

Link to Notebook GitHub

In [1]:
from __future__ import print_function
import numpy as np
import statsmodels.api as sm
from scipy import stats
from matplotlib import pyplot as plt

GLM: Binomial response data

Load data

In this example, we use the Star98 dataset which was taken with permission from Jeff Gill (2000) Generalized linear models: A unified approach. Codebook information can be obtained by typing:

In [2]:
print(sm.datasets.star98.NOTE)
::

    Number of Observations - 303 (counties in California).

    Number of Variables - 13 and 8 interaction terms.

    Definition of variables names::

        NABOVE   - Total number of students above the national median for the
                   math section.
        NBELOW   - Total number of students below the national median for the
                   math section.
        LOWINC   - Percentage of low income students
        PERASIAN - Percentage of Asian student
        PERBLACK - Percentage of black students
        PERHISP  - Percentage of Hispanic students
        PERMINTE - Percentage of minority teachers
        AVYRSEXP - Sum of teachers' years in educational service divided by the
                number of teachers.
        AVSALK   - Total salary budget including benefits divided by the number
                   of full-time teachers (in thousands)
        PERSPENK - Per-pupil spending (in thousands)
        PTRATIO  - Pupil-teacher ratio.
        PCTAF    - Percentage of students taking UC/CSU prep courses
        PCTCHRT  - Percentage of charter schools
        PCTYRRND - Percentage of year-round schools

        The below variables are interaction terms of the variables defined
        above.

        PERMINTE_AVYRSEXP
        PEMINTE_AVSAL
        AVYRSEXP_AVSAL
        PERSPEN_PTRATIO
        PERSPEN_PCTAF
        PTRATIO_PCTAF
        PERMINTE_AVTRSEXP_AVSAL
        PERSPEN_PTRATIO_PCTAF


Load the data and add a constant to the exogenous (independent) variables:

In [3]:
data = sm.datasets.star98.load()
data.exog = sm.add_constant(data.exog, prepend=False)

The dependent variable is N by 2 (Success: NABOVE, Failure: NBELOW):

In [4]:
print(data.endog[:5,:])
[[ 452.  355.]
 [ 144.   40.]
 [ 337.  234.]
 [ 395.  178.]
 [   8.   57.]]

The independent variables include all the other variables described above, as well as the interaction terms:

In [5]:
print(data.exog[:2,:])
[[    34.3973     23.2993     14.2353     11.4111     15.9184     14.7065
      59.1573      4.4452     21.7102     57.0328      0.         22.2222
     234.1029    941.6881    869.9948     96.5066    253.5224   1238.1955
   13848.8985   5504.0352      1.    ]
 [    17.3651     29.3284      8.2349      9.3149     13.6364     16.0832
      59.504       5.2676     20.4428     64.6226      0.          0.
     219.3169    811.4176    957.0166    107.6843    340.4061   1321.0664
   13050.2233   6958.8468      1.    ]]

Fit and summary

In [6]:
glm_binom = sm.GLM(data.endog, data.exog, family=sm.families.Binomial())
res = glm_binom.fit()
print(res.summary())
                 Generalized Linear Model Regression Results
==============================================================================
Dep. Variable:           ['y1', 'y2']   No. Observations:                  303
Model:                            GLM   Df Residuals:                      282
Model Family:                Binomial   Df Model:                           20
Link Function:                  logit   Scale:                             1.0
Method:                          IRLS   Log-Likelihood:                -2998.6
Date:                Tue, 02 Dec 2014   Deviance:                       4078.8
Time:                        12:53:50   Pearson chi2:                 4.05e+03
No. Iterations:                     7
==============================================================================
                 coef    std err          z      P>|z|      [95.0% Conf. Int.]
------------------------------------------------------------------------------
x1            -0.0168      0.000    -38.749      0.000        -0.018    -0.016
x2             0.0099      0.001     16.505      0.000         0.009     0.011
x3            -0.0187      0.001    -25.182      0.000        -0.020    -0.017
x4            -0.0142      0.000    -32.818      0.000        -0.015    -0.013
x5             0.2545      0.030      8.498      0.000         0.196     0.313
x6             0.2407      0.057      4.212      0.000         0.129     0.353
x7             0.0804      0.014      5.775      0.000         0.053     0.108
x8            -1.9522      0.317     -6.162      0.000        -2.573    -1.331
x9            -0.3341      0.061     -5.453      0.000        -0.454    -0.214
x10           -0.1690      0.033     -5.169      0.000        -0.233    -0.105
x11            0.0049      0.001      3.921      0.000         0.002     0.007
x12           -0.0036      0.000    -15.878      0.000        -0.004    -0.003
x13           -0.0141      0.002     -7.391      0.000        -0.018    -0.010
x14           -0.0040      0.000     -8.450      0.000        -0.005    -0.003
x15           -0.0039      0.001     -4.059      0.000        -0.006    -0.002
x16            0.0917      0.015      6.321      0.000         0.063     0.120
x17            0.0490      0.007      6.574      0.000         0.034     0.064
x18            0.0080      0.001      5.362      0.000         0.005     0.011
x19            0.0002   2.99e-05      7.428      0.000         0.000     0.000
x20           -0.0022      0.000     -6.445      0.000        -0.003    -0.002
const          2.9589      1.547      1.913      0.056        -0.073     5.990
==============================================================================

Quantities of interest

In [7]:
print('Total number of trials:',  data.endog[0].sum())
print('Parameters: ', res.params)
print('T-values: ', res.tvalues)
Total number of trials: 807.0
Parameters:  [-0.0168  0.0099 -0.0187 -0.0142  0.2545  0.2407  0.0804 -1.9522 -0.3341
 -0.169   0.0049 -0.0036 -0.0141 -0.004  -0.0039  0.0917  0.049   0.008
  0.0002 -0.0022  2.9589]
T-values:  [-38.7491  16.5047 -25.1822 -32.8179   8.4983   4.2125   5.775   -6.1619
  -5.4532  -5.1687   3.9212 -15.8783  -7.3909  -8.4496  -4.0592   6.3211
   6.5743   5.3623   7.4281  -6.4451   1.913 ]

First differences: We hold all explanatory variables constant at their means and manipulate the percentage of low income households to assess its impact on the response variables:

In [8]:
means = data.exog.mean(axis=0)
means25 = means.copy()
means25[0] = stats.scoreatpercentile(data.exog[:,0], 25)
means75 = means.copy()
means75[0] = lowinc_75per = stats.scoreatpercentile(data.exog[:,0], 75)
resp_25 = res.predict(means25)
resp_75 = res.predict(means75)
diff = resp_75 - resp_25

The interquartile first difference for the percentage of low income households in a school district is:

In [9]:
print("%2.4f%%" % (diff*100))
-11.8753%

Plots

We extract information that will be used to draw some interesting plots:

In [10]:
nobs = res.nobs
y = data.endog[:,0]/data.endog.sum(1)
yhat = res.mu

Plot yhat vs y:

In [11]:
from statsmodels.graphics.api import abline_plot
In [12]:
fig, ax = plt.subplots()
ax.scatter(yhat, y)
line_fit = sm.OLS(y, sm.add_constant(yhat, prepend=True)).fit()
abline_plot(model_results=line_fit, ax=ax)


ax.set_title('Model Fit Plot')
ax.set_ylabel('Observed values')
ax.set_xlabel('Fitted values');

Plot yhat vs. Pearson residuals:

In [13]:
fig, ax = plt.subplots()

ax.scatter(yhat, res.resid_pearson)
ax.hlines(0, 0, 1)
ax.set_xlim(0, 1)
ax.set_title('Residual Dependence Plot')
ax.set_ylabel('Pearson Residuals')
ax.set_xlabel('Fitted values')
Out[13]:
<matplotlib.text.Text at 0x2b147a8dc7d0>

Histogram of standardized deviance residuals:

In [14]:
from scipy import stats

fig, ax = plt.subplots()

resid = res.resid_deviance.copy()
resid_std = stats.zscore(resid)
ax.hist(resid_std, bins=25)
ax.set_title('Histogram of standardized deviance residuals');

QQ Plot of Deviance Residuals:

In [15]:
from statsmodels import graphics
graphics.gofplots.qqplot(resid, line='r')
Out[15]:

GLM: Gamma for proportional count response

Load data

In the example above, we printed the NOTE attribute to learn about the Star98 dataset. Statsmodels datasets ships with other useful information. For example:

In [16]:
print(sm.datasets.scotland.DESCRLONG)

This data is based on the example in Gill and describes the proportion of
voters who voted Yes to grant the Scottish Parliament taxation powers.
The data are divided into 32 council districts.  This example's explanatory
variables include the amount of council tax collected in pounds sterling as
of April 1997 per two adults before adjustments, the female percentage of
total claims for unemployment benefits as of January, 1998, the standardized
mortality rate (UK is 100), the percentage of labor force participation,
regional GDP, the percentage of children aged 5 to 15, and an interaction term
between female unemployment and the council tax.

The original source files and variable information are included in
/scotland/src/


Load the data and add a constant to the exogenous variables:

In [17]:
data2 = sm.datasets.scotland.load()
data2.exog = sm.add_constant(data2.exog, prepend=False)
print(data2.exog[:5,:])
print(data2.endog[:5])
[[   712.      21.     105.      82.4  13566.      12.3  14952.       1. ]
 [   643.      26.5     97.      80.2  13566.      15.3  17039.5      1. ]
 [   679.      28.3    113.      86.3   9611.      13.9  19215.7      1. ]
 [   801.      27.1    109.      80.4   9483.      13.6  21707.1      1. ]
 [   753.      22.     115.      64.7   9265.      14.6  16566.       1. ]]
[ 60.3  52.3  53.4  57.   68.7]

Fit and summary

In [18]:
glm_gamma = sm.GLM(data2.endog, data2.exog, family=sm.families.Gamma())
glm_results = glm_gamma.fit()
print(glm_results.summary())
                 Generalized Linear Model Regression Results
==============================================================================
Dep. Variable:                      y   No. Observations:                   32
Model:                            GLM   Df Residuals:                       24
Model Family:                   Gamma   Df Model:                            7
Link Function:          inverse_power   Scale:                0.00358428317349
Method:                          IRLS   Log-Likelihood:                -83.017
Date:                Tue, 02 Dec 2014   Deviance:                     0.087389
Time:                        12:53:54   Pearson chi2:                   0.0860
No. Iterations:                     6
==============================================================================
                 coef    std err          z      P>|z|      [95.0% Conf. Int.]
------------------------------------------------------------------------------
x1          4.962e-05   1.62e-05      3.060      0.002      1.78e-05  8.14e-05
x2             0.0020      0.001      3.824      0.000         0.001     0.003
x3         -7.181e-05   2.71e-05     -2.648      0.008        -0.000 -1.87e-05
x4             0.0001   4.06e-05      2.757      0.006      3.23e-05     0.000
x5         -1.468e-07   1.24e-07     -1.187      0.235     -3.89e-07  9.56e-08
x6            -0.0005      0.000     -2.159      0.031        -0.001 -4.78e-05
x7         -2.427e-06   7.46e-07     -3.253      0.001     -3.89e-06 -9.65e-07
const         -0.0178      0.011     -1.548      0.122        -0.040     0.005
==============================================================================

Artificial data

In [19]:
nobs2 = 100
x = np.arange(nobs2)
np.random.seed(54321)
X = np.column_stack((x,x**2))
X = sm.add_constant(X, prepend=False)
lny = np.exp(-(.03*x + .0001*x**2 - 1.0)) + .001 * np.random.rand(nobs2)

Fit and summary

In [20]:
gauss_log = sm.GLM(lny, X, family=sm.families.Gaussian(sm.families.links.log))
gauss_log_results = gauss_log.fit()
print(gauss_log_results.summary())
                 Generalized Linear Model Regression Results
==============================================================================
Dep. Variable:                      y   No. Observations:                  100
Model:                            GLM   Df Residuals:                       97
Model Family:                Gaussian   Df Model:                            2
Link Function:                    log   Scale:               1.05311425588e-07
Method:                          IRLS   Log-Likelihood:                 662.92
Date:                Tue, 02 Dec 2014   Deviance:                   1.0215e-05
Time:                        12:53:54   Pearson chi2:                 1.02e-05
No. Iterations:                     7
==============================================================================
                 coef    std err          z      P>|z|      [95.0% Conf. Int.]
------------------------------------------------------------------------------
x1            -0.0300    5.6e-06  -5361.316      0.000        -0.030    -0.030
x2         -9.939e-05   1.05e-07   -951.091      0.000     -9.96e-05 -9.92e-05
const          1.0003   5.39e-05   1.86e+04      0.000         1.000     1.000
==============================================================================

Previous topic

Generalized Linear Models

Next topic

Generalized Linear Models (Formula)

This Page