{
 "metadata": {
  "name": "",
  "signature": "sha256:d3903edb7fb7da675fc25f6f8753fc1ad37719bd9ff21a0bda90d9048db2f1f0"
 },
 "nbformat": 3,
 "nbformat_minor": 0,
 "worksheets": [
  {
   "cells": [
    {
     "cell_type": "heading",
     "level": 1,
     "metadata": {},
     "source": [
      "Maximum Likelihood Estimation (Generic models)"
     ]
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "This tutorial explains how to quickly implement new maximum likelihood models in `statsmodels`. We give two examples: \n",
      "\n",
      "1. Probit model for binary dependent variables\n",
      "2. Negative binomial model for count data\n",
      "\n",
      "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. "
     ]
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "## Example 1: Probit model"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "from __future__ import print_function\n",
      "import numpy as np\n",
      "from scipy import stats\n",
      "import statsmodels.api as sm\n",
      "from statsmodels.base.model import GenericLikelihoodModel"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "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:"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "data = sm.datasets.spector.load_pandas()\n",
      "exog = data.exog\n",
      "endog = data.endog\n",
      "print(sm.datasets.spector.NOTE)\n",
      "print(data.exog.head())"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "Them, we add a constant to the matrix of regressors:"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "exog = sm.add_constant(exog, prepend=True)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "To create your own Likelihood Model, you simply need to overwrite the loglike method."
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "class MyProbit(GenericLikelihoodModel):\n",
      "    def loglike(self, params):\n",
      "        exog = self.exog\n",
      "        endog = self.endog\n",
      "        q = 2 * endog - 1\n",
      "        return stats.norm.logcdf(q*np.dot(exog, params)).sum()"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "Estimate the model and print a summary:"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "sm_probit_manual = MyProbit(endog, exog).fit()\n",
      "print(sm_probit_manual.summary())"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "Compare your Probit implementation to ``statsmodels``' \"canned\" implementation:"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "sm_probit_canned = sm.Probit(endog, exog).fit()"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "print(sm_probit_canned.params)\n",
      "print(sm_probit_manual.params)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "print(sm_probit_canned.cov_params())\n",
      "print(sm_probit_manual.cov_params())"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "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."
     ]
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "\n",
      "\n",
      "## Example 2: Negative Binomial Regression for Count Data\n",
      "\n",
      "Consider a negative binomial regression model for count data with\n",
      "log-likelihood (type NB-2) function expressed as:\n",
      "\n",
      "$$\n",
      "    \\mathcal{L}(\\beta_j; y, \\alpha) = \\sum_{i=1}^n y_i ln \n",
      "    \\left ( \\frac{\\alpha exp(X_i'\\beta)}{1+\\alpha exp(X_i'\\beta)} \\right ) -\n",
      "    \\frac{1}{\\alpha} ln(1+\\alpha exp(X_i'\\beta)) + ln \\Gamma (y_i + 1/\\alpha) - ln \\Gamma (y_i+1) - ln \\Gamma (1/\\alpha)\n",
      "$$\n",
      "\n",
      "with a matrix of regressors $X$, a vector of coefficients $\\beta$,\n",
      "and the negative binomial heterogeneity parameter $\\alpha$. \n",
      "\n",
      "Using the ``nbinom`` distribution from ``scipy``, we can write this likelihood\n",
      "simply as:\n"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "import numpy as np\n",
      "from scipy.stats import nbinom"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "def _ll_nb2(y, X, beta, alph):\n",
      "    mu = np.exp(np.dot(X, beta))\n",
      "    size = 1/alph\n",
      "    prob = size/(size+mu)\n",
      "    ll = nbinom.logpmf(y, size, prob)\n",
      "    return ll"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "### New Model Class\n",
      "\n",
      "We create a new model class which inherits from ``GenericLikelihoodModel``:"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "from statsmodels.base.model import GenericLikelihoodModel"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "class NBin(GenericLikelihoodModel):\n",
      "    def __init__(self, endog, exog, **kwds):\n",
      "        super(NBin, self).__init__(endog, exog, **kwds)\n",
      "        \n",
      "    def nloglikeobs(self, params):\n",
      "        alph = params[-1]\n",
      "        beta = params[:-1]\n",
      "        ll = _ll_nb2(self.endog, self.exog, beta, alph)\n",
      "        return -ll \n",
      "    \n",
      "    def fit(self, start_params=None, maxiter=10000, maxfun=5000, **kwds):\n",
      "        # we have one additional parameter and we need to add it for summary\n",
      "        self.exog_names.append('alpha')\n",
      "        if start_params == None:\n",
      "            # Reasonable starting values\n",
      "            start_params = np.append(np.zeros(self.exog.shape[1]), .5)\n",
      "            # intercept\n",
      "            start_params[-2] = np.log(self.endog.mean())\n",
      "        return super(NBin, self).fit(start_params=start_params, \n",
      "                                     maxiter=maxiter, maxfun=maxfun, \n",
      "                                     **kwds) "
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "Two important things to notice: \n",
      "\n",
      "+ ``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). \n",
      "+ ``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.\n",
      "   \n",
      "That's it! You're done!\n",
      "\n",
      "### Usage Example\n",
      "\n",
      "The [Medpar](http://vincentarelbundock.github.com/Rdatasets/doc/COUNT/medpar.html)\n",
      "dataset is hosted in CSV format at the [Rdatasets repository](http://vincentarelbundock.github.com/Rdatasets). We use the ``read_csv``\n",
      "function from the [Pandas library](http://pandas.pydata.org) to load the data\n",
      "in memory. We then print the first few columns: \n"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "import statsmodels.api as sm"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "medpar = sm.datasets.get_rdataset(\"medpar\", \"COUNT\", cache=True).data\n",
      "\n",
      "medpar.head()"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "The model we are interested in has a vector of non-negative integers as\n",
      "dependent variable (``los``), and 5 regressors: ``Intercept``, ``type2``,\n",
      "``type3``, ``hmo``, ``white``.\n",
      "\n",
      "For estimation, we need to create two variables to hold our regressors and the outcome variable. These can be ndarrays or pandas objects."
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "y = medpar.los\n",
      "X = medpar[[\"type2\", \"type3\", \"hmo\", \"white\"]]\n",
      "X[\"constant\"] = 1"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "Then, we fit the model and extract some information: "
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "mod = NBin(y, X)\n",
      "res = mod.fit()"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      " Extract parameter estimates, standard errors, p-values, AIC, etc.:"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "print('Parameters: ', res.params)\n",
      "print('Standard errors: ', res.bse)\n",
      "print('P-values: ', res.pvalues)\n",
      "print('AIC: ', res.aic)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "As usual, you can obtain a full list of available information by typing\n",
      "``dir(res)``.\n",
      "We can also look at the summary of the estimation results."
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "print(res.summary())"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "### Testing"
     ]
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "We can check the results by using the statsmodels implementation of the Negative Binomial model, which uses the analytic score function and Hessian."
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "res_nbin = sm.NegativeBinomial(y, X).fit(disp=0)\n",
      "print(res_nbin.summary())"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "print(res_nbin.params)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "print(res_nbin.bse)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "Or we could compare them to results obtained using the MASS implementation for R:\n",
      "\n",
      "    url = 'http://vincentarelbundock.github.com/Rdatasets/csv/COUNT/medpar.csv'\n",
      "    medpar = read.csv(url)\n",
      "    f = los~factor(type)+hmo+white\n",
      "    \n",
      "    library(MASS)\n",
      "    mod = glm.nb(f, medpar)\n",
      "    coef(summary(mod))\n",
      "                     Estimate Std. Error   z value      Pr(>|z|)\n",
      "    (Intercept)    2.31027893 0.06744676 34.253370 3.885556e-257\n",
      "    factor(type)2  0.22124898 0.05045746  4.384861  1.160597e-05\n",
      "    factor(type)3  0.70615882 0.07599849  9.291748  1.517751e-20\n",
      "    hmo           -0.06795522 0.05321375 -1.277024  2.015939e-01\n",
      "    white         -0.12906544 0.06836272 -1.887951  5.903257e-02\n",
      "\n",
      "### Numerical precision \n",
      "\n",
      "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."
     ]
    }
   ],
   "metadata": {}
  }
 ]
}