Maximum Likelihood Estimation (Generic models)
This tutorial explains how to quickly implement new maximum likelihood models in statsmodels
. We give two examples:
- Probit model for binary dependent variables
- Negative binomial model for count data
The GenericLikelihoodModel
class eases the process by providing tools such as automatic numeric differentiation and a unified interface to scipy
optimization functions. Using statsmodels
, users can fit new MLE models simply by "plugging-in" a log-likelihood function.
Example 1: Probit model
1 2 3 4 5 | <span class = "kn" > from < / span> <span class = "nn" >__future__< / span> <span class = "kn" > import < / span> <span class = "n" >print_function< / span> <span class = "kn" > import < / span> <span class = "nn" >numpy< / span> <span class = "kn" >as< / span> <span class = "nn" >np< / span> <span class = "kn" > from < / span> <span class = "nn" >scipy< / span> <span class = "kn" > import < / span> <span class = "n" >stats< / span> <span class = "kn" > import < / span> <span class = "nn" >statsmodels.api< / span> <span class = "kn" >as< / span> <span class = "nn" >sm< / span> <span class = "kn" > from < / span> <span class = "nn" >statsmodels.base.model< / span> <span class = "kn" > import < / span> <span class = "n" >GenericLikelihoodModel< / span> |
The Spector
dataset is distributed with statsmodels
. You can access a vector of values for the dependent variable (endog
) and a matrix of regressors (exog
) like this:
1 2 3 4 5 | <span class = "n" >data< / span> <span class = "o" > = < / span> <span class = "n" >sm< / span><span class = "o" >.< / span><span class = "n" >datasets< / span><span class = "o" >.< / span><span class = "n" >spector< / span><span class = "o" >.< / span><span class = "n" >load_pandas< / span><span class = "p" >()< / span> <span class = "n" >exog< / span> <span class = "o" > = < / span> <span class = "n" >data< / span><span class = "o" >.< / span><span class = "n" >exog< / span> <span class = "n" >endog< / span> <span class = "o" > = < / span> <span class = "n" >data< / span><span class = "o" >.< / span><span class = "n" >endog< / span> <span class = "k" > print < / span><span class = "p" >(< / span><span class = "n" >sm< / span><span class = "o" >.< / span><span class = "n" >datasets< / span><span class = "o" >.< / span><span class = "n" >spector< / span><span class = "o" >.< / span><span class = "n" >NOTE< / span><span class = "p" >)< / span> <span class = "k" > print < / span><span class = "p" >(< / span><span class = "n" >data< / span><span class = "o" >.< / span><span class = "n" >exog< / span><span class = "o" >.< / span><span class = "n" >head< / span><span class = "p" >())< / span> |
Them, we add a constant to the matrix of regressors:
1 | <span class = "n" >exog< / span> <span class = "o" > = < / span> <span class = "n" >sm< / span><span class = "o" >.< / span><span class = "n" >add_constant< / span><span class = "p" >(< / span><span class = "n" >exog< / span><span class = "p" >,< / span> <span class = "n" >prepend< / span><span class = "o" > = < / span><span class = "bp" > True < / span><span class = "p" >)< / span> |
To create your own Likelihood Model, you simply need to overwrite the loglike method.
1 2 3 4 5 6 | <span class = "k" > class < / span> <span class = "nc" >MyProbit< / span><span class = "p" >(< / span><span class = "n" >GenericLikelihoodModel< / span><span class = "p" >):< / span> <span class = "k" > def < / span> <span class = "nf" >loglike< / span><span class = "p" >(< / span><span class = "bp" > self < / span><span class = "p" >,< / span> <span class = "n" >params< / span><span class = "p" >):< / span> <span class = "n" >exog< / span> <span class = "o" > = < / span> <span class = "bp" > self < / span><span class = "o" >.< / span><span class = "n" >exog< / span> <span class = "n" >endog< / span> <span class = "o" > = < / span> <span class = "bp" > self < / span><span class = "o" >.< / span><span class = "n" >endog< / span> <span class = "n" >q< / span> <span class = "o" > = < / span> <span class = "mi" > 2 < / span> <span class = "o" > * < / span> <span class = "n" >endog< / span> <span class = "o" > - < / span> <span class = "mi" > 1 < / span> <span class = "k" > return < / span> <span class = "n" >stats< / span><span class = "o" >.< / span><span class = "n" >norm< / span><span class = "o" >.< / span><span class = "n" >logcdf< / span><span class = "p" >(< / span><span class = "n" >q< / span><span class = "o" > * < / span><span class = "n" >np< / span><span class = "o" >.< / span><span class = "n" >dot< / span><span class = "p" >(< / span><span class = "n" >exog< / span><span class = "p" >,< / span> <span class = "n" >params< / span><span class = "p" >))< / span><span class = "o" >.< / span><span class = "n" > sum < / span><span class = "p" >()< / span> |
Estimate the model and print a summary:
1 2 | <span class = "n" >sm_probit_manual< / span> <span class = "o" > = < / span> <span class = "n" >MyProbit< / span><span class = "p" >(< / span><span class = "n" >endog< / span><span class = "p" >,< / span> <span class = "n" >exog< / span><span class = "p" >)< / span><span class = "o" >.< / span><span class = "n" >fit< / span><span class = "p" >()< / span> <span class = "k" > print < / span><span class = "p" >(< / span><span class = "n" >sm_probit_manual< / span><span class = "o" >.< / span><span class = "n" >summary< / span><span class = "p" >())< / span> |
Compare your Probit implementation to statsmodels
' "canned" implementation:
1 | <span class = "n" >sm_probit_canned< / span> <span class = "o" > = < / span> <span class = "n" >sm< / span><span class = "o" >.< / span><span class = "n" >Probit< / span><span class = "p" >(< / span><span class = "n" >endog< / span><span class = "p" >,< / span> <span class = "n" >exog< / span><span class = "p" >)< / span><span class = "o" >.< / span><span class = "n" >fit< / span><span class = "p" >()< / span> |
1 2 | <span class = "k" > print < / span><span class = "p" >(< / span><span class = "n" >sm_probit_canned< / span><span class = "o" >.< / span><span class = "n" >params< / span><span class = "p" >)< / span> <span class = "k" > print < / span><span class = "p" >(< / span><span class = "n" >sm_probit_manual< / span><span class = "o" >.< / span><span class = "n" >params< / span><span class = "p" >)< / span> |
1 2 | <span class = "k" > print < / span><span class = "p" >(< / span><span class = "n" >sm_probit_canned< / span><span class = "o" >.< / span><span class = "n" >cov_params< / span><span class = "p" >())< / span> <span class = "k" > print < / span><span class = "p" >(< / span><span class = "n" >sm_probit_manual< / span><span class = "o" >.< / span><span class = "n" >cov_params< / span><span class = "p" >())< / span> |
Notice that the GenericMaximumLikelihood
class provides automatic differentiation, so we didn't have to provide Hessian or Score functions in order to calculate the covariance estimates.
Example 2: Negative Binomial Regression for Count Data
Consider a negative binomial regression model for count data with log-likelihood (type NB-2) function expressed as:
L(βj;y,α)=n∑i=1yiln(αexp(X′iβ)1+αexp(X′iβ))−1αln(1+αexp(X′iβ))+lnΓ(yi+1/α)−lnΓ(yi+1)−lnΓ(1/α)
with a matrix of regressors $X$, a vector of coefficients $\beta$, and the negative binomial heterogeneity parameter $\alpha$.
Using the nbinom
distribution from scipy
, we can write this likelihood simply as:
1 2 | <span class = "kn" > import < / span> <span class = "nn" >numpy< / span> <span class = "kn" >as< / span> <span class = "nn" >np< / span> <span class = "kn" > from < / span> <span class = "nn" >scipy.stats< / span> <span class = "kn" > import < / span> <span class = "n" >nbinom< / span> |
1 2 3 4 5 6 | <span class = "k" > def < / span> <span class = "nf" >_ll_nb2< / span><span class = "p" >(< / span><span class = "n" >y< / span><span class = "p" >,< / span> <span class = "n" >X< / span><span class = "p" >,< / span> <span class = "n" >beta< / span><span class = "p" >,< / span> <span class = "n" >alph< / span><span class = "p" >):< / span> <span class = "n" >mu< / span> <span class = "o" > = < / span> <span class = "n" >np< / span><span class = "o" >.< / span><span class = "n" >exp< / span><span class = "p" >(< / span><span class = "n" >np< / span><span class = "o" >.< / span><span class = "n" >dot< / span><span class = "p" >(< / span><span class = "n" >X< / span><span class = "p" >,< / span> <span class = "n" >beta< / span><span class = "p" >))< / span> <span class = "n" >size< / span> <span class = "o" > = < / span> <span class = "mi" > 1 < / span><span class = "o" > / < / span><span class = "n" >alph< / span> <span class = "n" >prob< / span> <span class = "o" > = < / span> <span class = "n" >size< / span><span class = "o" > / < / span><span class = "p" >(< / span><span class = "n" >size< / span><span class = "o" > + < / span><span class = "n" >mu< / span><span class = "p" >)< / span> <span class = "n" >ll< / span> <span class = "o" > = < / span> <span class = "n" >nbinom< / span><span class = "o" >.< / span><span class = "n" >logpmf< / span><span class = "p" >(< / span><span class = "n" >y< / span><span class = "p" >,< / span> <span class = "n" >size< / span><span class = "p" >,< / span> <span class = "n" >prob< / span><span class = "p" >)< / span> <span class = "k" > return < / span> <span class = "n" >ll< / span> |
New Model Class
We create a new model class which inherits from GenericLikelihoodModel
:
1 | <span class = "kn" > from < / span> <span class = "nn" >statsmodels.base.model< / span> <span class = "kn" > import < / span> <span class = "n" >GenericLikelihoodModel< / span> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <span class = "k" > class < / span> <span class = "nc" >NBin< / span><span class = "p" >(< / span><span class = "n" >GenericLikelihoodModel< / span><span class = "p" >):< / span> <span class = "k" > def < / span> <span class = "nf" >__init__< / span><span class = "p" >(< / span><span class = "bp" > self < / span><span class = "p" >,< / span> <span class = "n" >endog< / span><span class = "p" >,< / span> <span class = "n" >exog< / span><span class = "p" >,< / span> <span class = "o" > * * < / span><span class = "n" >kwds< / span><span class = "p" >):< / span> <span class = "nb" > super < / span><span class = "p" >(< / span><span class = "n" >NBin< / span><span class = "p" >,< / span> <span class = "bp" > self < / span><span class = "p" >)< / span><span class = "o" >.< / span><span class = "n" >__init__< / span><span class = "p" >(< / span><span class = "n" >endog< / span><span class = "p" >,< / span> <span class = "n" >exog< / span><span class = "p" >,< / span> <span class = "o" > * * < / span><span class = "n" >kwds< / span><span class = "p" >)< / span> <span class = "k" > def < / span> <span class = "nf" >nloglikeobs< / span><span class = "p" >(< / span><span class = "bp" > self < / span><span class = "p" >,< / span> <span class = "n" >params< / span><span class = "p" >):< / span> <span class = "n" >alph< / span> <span class = "o" > = < / span> <span class = "n" >params< / span><span class = "p" >[< / span><span class = "o" > - < / span><span class = "mi" > 1 < / span><span class = "p" >]< / span> <span class = "n" >beta< / span> <span class = "o" > = < / span> <span class = "n" >params< / span><span class = "p" >[:< / span><span class = "o" > - < / span><span class = "mi" > 1 < / span><span class = "p" >]< / span> <span class = "n" >ll< / span> <span class = "o" > = < / span> <span class = "n" >_ll_nb2< / span><span class = "p" >(< / span><span class = "bp" > self < / span><span class = "o" >.< / span><span class = "n" >endog< / span><span class = "p" >,< / span> <span class = "bp" > self < / span><span class = "o" >.< / span><span class = "n" >exog< / span><span class = "p" >,< / span> <span class = "n" >beta< / span><span class = "p" >,< / span> <span class = "n" >alph< / span><span class = "p" >)< / span> <span class = "k" > return < / span> <span class = "o" > - < / span><span class = "n" >ll< / span> <span class = "k" > def < / span> <span class = "nf" >fit< / span><span class = "p" >(< / span><span class = "bp" > self < / span><span class = "p" >,< / span> <span class = "n" >start_params< / span><span class = "o" > = < / span><span class = "bp" > None < / span><span class = "p" >,< / span> <span class = "n" >maxiter< / span><span class = "o" > = < / span><span class = "mi" > 10000 < / span><span class = "p" >,< / span> <span class = "n" >maxfun< / span><span class = "o" > = < / span><span class = "mi" > 5000 < / span><span class = "p" >,< / span> <span class = "o" > * * < / span><span class = "n" >kwds< / span><span class = "p" >):< / span> <span class = "c" > # we have one additional parameter and we need to add it for summary</span> <span class = "bp" > self < / span><span class = "o" >.< / span><span class = "n" >exog_names< / span><span class = "o" >.< / span><span class = "n" >append< / span><span class = "p" >(< / span><span class = "s" > 'alpha' < / span><span class = "p" >)< / span> <span class = "k" > if < / span> <span class = "n" >start_params< / span> <span class = "o" > = = < / span> <span class = "bp" > None < / span><span class = "p" >:< / span> <span class = "c" > # Reasonable starting values</span> <span class = "n" >start_params< / span> <span class = "o" > = < / span> <span class = "n" >np< / span><span class = "o" >.< / span><span class = "n" >append< / span><span class = "p" >(< / span><span class = "n" >np< / span><span class = "o" >.< / span><span class = "n" >zeros< / span><span class = "p" >(< / span><span class = "bp" > self < / span><span class = "o" >.< / span><span class = "n" >exog< / span><span class = "o" >.< / span><span class = "n" >shape< / span><span class = "p" >[< / span><span class = "mi" > 1 < / span><span class = "p" >]),< / span> <span class = "o" >.< / span><span class = "mi" > 5 < / span><span class = "p" >)< / span> <span class = "c" > # intercept</span> <span class = "n" >start_params< / span><span class = "p" >[< / span><span class = "o" > - < / span><span class = "mi" > 2 < / span><span class = "p" >]< / span> <span class = "o" > = < / span> <span class = "n" >np< / span><span class = "o" >.< / span><span class = "n" >log< / span><span class = "p" >(< / span><span class = "bp" > self < / span><span class = "o" >.< / span><span class = "n" >endog< / span><span class = "o" >.< / span><span class = "n" >mean< / span><span class = "p" >())< / span> <span class = "k" > return < / span> <span class = "nb" > super < / span><span class = "p" >(< / span><span class = "n" >NBin< / span><span class = "p" >,< / span> <span class = "bp" > self < / span><span class = "p" >)< / span><span class = "o" >.< / span><span class = "n" >fit< / span><span class = "p" >(< / span><span class = "n" >start_params< / span><span class = "o" > = < / span><span class = "n" >start_params< / span><span class = "p" >,< / span> <span class = "n" >maxiter< / span><span class = "o" > = < / span><span class = "n" >maxiter< / span><span class = "p" >,< / span> <span class = "n" >maxfun< / span><span class = "o" > = < / span><span class = "n" >maxfun< / span><span class = "p" >,< / span> <span class = "o" > * * < / span><span class = "n" >kwds< / span><span class = "p" >)< / span> |
Two important things to notice:
-
nloglikeobs
: This function should return one evaluation of the negative log-likelihood function per observation in your dataset (i.e. rows of the endog/X matrix). -
start_params
: A one-dimensional array of starting values needs to be provided. The size of this array determines the number of parameters that will be used in optimization.
That's it! You're done!
Usage Example
The Medpar dataset is hosted in CSV format at the Rdatasets repository. We use the read_csv
function from the Pandas library to load the data in memory. We then print the first few columns:
1 | <span class = "kn" > import < / span> <span class = "nn" >statsmodels.api< / span> <span class = "kn" >as< / span> <span class = "nn" >sm< / span> |
1 2 3 | <span class = "n" >medpar< / span> <span class = "o" > = < / span> <span class = "n" >sm< / span><span class = "o" >.< / span><span class = "n" >datasets< / span><span class = "o" >.< / span><span class = "n" >get_rdataset< / span><span class = "p" >(< / span><span class = "s" > "medpar" < / span><span class = "p" >,< / span> <span class = "s" > "COUNT" < / span><span class = "p" >,< / span> <span class = "n" >cache< / span><span class = "o" > = < / span><span class = "bp" > True < / span><span class = "p" >)< / span><span class = "o" >.< / span><span class = "n" >data< / span> <span class = "n" >medpar< / span><span class = "o" >.< / span><span class = "n" >head< / span><span class = "p" >()< / span> |
The model we are interested in has a vector of non-negative integers as dependent variable (los
), and 5 regressors: Intercept
, type2
, type3
, hmo
, white
.
For estimation, we need to create two variables to hold our regressors and the outcome variable. These can be ndarrays or pandas objects.
1 2 3 | <span class = "n" >y< / span> <span class = "o" > = < / span> <span class = "n" >medpar< / span><span class = "o" >.< / span><span class = "n" >los< / span> <span class = "n" >X< / span> <span class = "o" > = < / span> <span class = "n" >medpar< / span><span class = "p" >[[< / span><span class = "s" > "type2" < / span><span class = "p" >,< / span> <span class = "s" > "type3" < / span><span class = "p" >,< / span> <span class = "s" > "hmo" < / span><span class = "p" >,< / span> <span class = "s" > "white" < / span><span class = "p" >]]< / span> <span class = "n" >X< / span><span class = "p" >[< / span><span class = "s" > "constant" < / span><span class = "p" >]< / span> <span class = "o" > = < / span> <span class = "mi" > 1 < / span> |
Then, we fit the model and extract some information:
1 2 | <span class = "n" >mod< / span> <span class = "o" > = < / span> <span class = "n" >NBin< / span><span class = "p" >(< / span><span class = "n" >y< / span><span class = "p" >,< / span> <span class = "n" >X< / span><span class = "p" >)< / span> <span class = "n" >res< / span> <span class = "o" > = < / span> <span class = "n" >mod< / span><span class = "o" >.< / span><span class = "n" >fit< / span><span class = "p" >()< / span> |
Extract parameter estimates, standard errors, p-values, AIC, etc.:
1 2 3 4 | <span class = "k" > print < / span><span class = "p" >(< / span><span class = "s" > 'Parameters: ' < / span><span class = "p" >,< / span> <span class = "n" >res< / span><span class = "o" >.< / span><span class = "n" >params< / span><span class = "p" >)< / span> <span class = "k" > print < / span><span class = "p" >(< / span><span class = "s" > 'Standard errors: ' < / span><span class = "p" >,< / span> <span class = "n" >res< / span><span class = "o" >.< / span><span class = "n" >bse< / span><span class = "p" >)< / span> <span class = "k" > print < / span><span class = "p" >(< / span><span class = "s" > 'P-values: ' < / span><span class = "p" >,< / span> <span class = "n" >res< / span><span class = "o" >.< / span><span class = "n" >pvalues< / span><span class = "p" >)< / span> <span class = "k" > print < / span><span class = "p" >(< / span><span class = "s" > 'AIC: ' < / span><span class = "p" >,< / span> <span class = "n" >res< / span><span class = "o" >.< / span><span class = "n" >aic< / span><span class = "p" >)< / span> |
As usual, you can obtain a full list of available information by typing dir(res)
. We can also look at the summary of the estimation results.
1 | <span class = "k" > print < / span><span class = "p" >(< / span><span class = "n" >res< / span><span class = "o" >.< / span><span class = "n" >summary< / span><span class = "p" >())< / span> |
Testing
We can check the results by using the statsmodels implementation of the Negative Binomial model, which uses the analytic score function and Hessian.
1 2 | <span class = "n" >res_nbin< / span> <span class = "o" > = < / span> <span class = "n" >sm< / span><span class = "o" >.< / span><span class = "n" >NegativeBinomial< / span><span class = "p" >(< / span><span class = "n" >y< / span><span class = "p" >,< / span> <span class = "n" >X< / span><span class = "p" >)< / span><span class = "o" >.< / span><span class = "n" >fit< / span><span class = "p" >(< / span><span class = "n" >disp< / span><span class = "o" > = < / span><span class = "mi" > 0 < / span><span class = "p" >)< / span> <span class = "k" > print < / span><span class = "p" >(< / span><span class = "n" >res_nbin< / span><span class = "o" >.< / span><span class = "n" >summary< / span><span class = "p" >())< / span> |
1 | <span class = "k" > print < / span><span class = "p" >(< / span><span class = "n" >res_nbin< / span><span class = "o" >.< / span><span class = "n" >params< / span><span class = "p" >)< / span> |
1 | <span class = "k" > print < / span><span class = "p" >(< / span><span class = "n" >res_nbin< / span><span class = "o" >.< / span><span class = "n" >bse< / span><span class = "p" >)< / span> |
Or we could compare them to results obtained using the MASS implementation for R:
url = 'http://vincentarelbundock.github.com/Rdatasets/csv/COUNT/medpar.csv'
medpar = read.csv(url)
f = los~factor(type)+hmo+white
library(MASS)
mod = glm.nb(f, medpar)
coef(summary(mod))
Estimate Std. Error z value Pr(>|z|)
(Intercept) 2.31027893 0.06744676 34.253370 3.885556e-257
factor(type)2 0.22124898 0.05045746 4.384861 1.160597e-05
factor(type)3 0.70615882 0.07599849 9.291748 1.517751e-20
hmo -0.06795522 0.05321375 -1.277024 2.015939e-01
white -0.12906544 0.06836272 -1.887951 5.903257e-02
Numerical precision
The statsmodels
generic MLE and R
parameter estimates agree up to the fourth decimal. The standard errors, however, agree only up to the second decimal. This discrepancy is the result of imprecision in our Hessian numerical estimates. In the current context, the difference between MASS
and statsmodels
standard error estimates is substantively irrelevant, but it highlights the fact that users who need very precise estimates may not always want to rely on default settings when using numerical derivatives. In such cases, it is better to use analytical derivatives with the LikelihoodModel
class.
Please login to continue.