Skip to content

PoissonZiGMLE : predict not implemented? #3496

Open

Description

@chiaral

I successfully run PoissonZiGMLE:

PZI = PoissonZiGMLE(df_zip['obs'],Xmat,offset=df_zip['offsetv'])
result = PZI.fit(maxiter = 1000)
print result.summary()

however when I try:

result.predict(df_zip, offset=offsetv)

I get this error:

---------------------------------------------------------------------------
NotImplementedError                       Traceback (most recent call last)
<ipython-input-83-bfcfbc12df01> in <module>()
----> 1 result.predict(df_zip, offset=offsetv)

/software/centos6/x86_64/canopy-1.7.4/Canopy_64bit/User/lib/python2.7/site-packages/statsmodels/base/model.py in predict(self, exog, transform, *args, **kwargs)
    747             exog = np.atleast_2d(exog)  # needed in count model shape[1]
    748 
--> 749         return self.model.predict(self.params, exog, *args, **kwargs)
    750 
    751 

/software/centos6/x86_64/canopy-1.7.4/Canopy_64bit/User/lib/python2.7/site-packages/statsmodels/base/model.py in predict(self, params, exog, *args, **kwargs)
    175         This is a placeholder intended to be overwritten by individual models.
    176         """
--> 177         raise NotImplementedError
    178 
    179 

NotImplementedError: 

Thanks!

Activity

  1. added this to the 0.9 milestone on Feb 22, 2017
  2. josef-pkt commented on Feb 22, 2017

    @josef-pkt
    Member

    (aside we don't have a issue label for miscmodels)

    some discussion for ZIP is in #1086 with a link to another version by Skipper, which doesn't have predict either, but it has a few other things like zero truncated Poisson pmf

    AFAIR, we don't have a good keyword for which prediction or what to return
    We will need options for what to predict, i.e. expected value/mean (default), mean of Poisson, linear predictor of poisson or maybe truncated mean conditional on not zero.
    In the extended version with explanatory variables for the inflation or zero modification part, we will also need to predict the mixture probability.

    Note, those classes in miscmodels.count were written as example and test cases for the GenericLikelihoodModel framework and are not fully or efficiently implemented models. e.g. no analytical derivatives.

  3. josef-pkt commented on Feb 24, 2017

    @josef-pkt
    Member

    here is a draft
    I'm not a fan of "which"
    results look correct in the large sample behavior

    # -*- coding: utf-8 -*-
    """
    Created on Fri Feb 24 16:12:50 2017
    
    Author: Josef Perktold
    """
    
    import numpy as np
    from numpy.testing import assert_almost_equal
    import statsmodels.api as sm
    from statsmodels.miscmodels.count import (PoissonGMLE, PoissonOffsetGMLE,
                            PoissonZiGMLE)
    from statsmodels.discrete.discrete_model import Poisson
    
    # copied from discrete_model.CountModel and adjusted
    def predict(self, params, exog=None, exposure=None, offset=None,
                which='mean'):
        """
        Predict response variable of a count model given exogenous variables.
    
        Notes
        -----
        If exposure is specified, then it will be logged by the method.
        The user does not need to log it first.
        """
        #TODO: add offset tp
        if exog is None:
            exog = self.exog
            offset = getattr(self, 'offset', 0)
            exposure = getattr(self, 'exposure', 0)
    
        else:
            if exposure is None:
                exposure = 0
            else:
                exposure = np.log(exposure)
            if offset is None:
                offset = 0
                
        lin_pred = np.dot(exog, params[:exog.shape[1]]) + exposure + offset
        prob_poisson =  1 / (1 + np.exp(-params[-1]))
        prob_zero = (1 - prob_poisson)  + prob_poisson * np.exp(-np.exp(lin_pred))
    
        if which == 'mean':
            return prob_poisson * np.exp(lin_pred)
        elif which == 'poisson-mean':
            return np.exp(lin_pred)
        elif which == 'linear':
            return lin_pred
        elif which == 'mean-nonzero':
            return prob_poisson * np.exp(lin_pred) / (1 - prob_zero)
        elif which == 'prob-zero':
            return  prob_zero
        
        else:
            raise ValueError('keyword `which` not recognized')
                          
                          
    # monkey patch during development
    PoissonZiGMLE.predict = predict
    
    np.random.seed(987656)
    nobs = 50000
    rvs = np.random.randn(nobs,6)
    data_exog = rvs
    data_exog = sm.add_constant(data_exog, prepend=True)
    xbeta = 1 + 0.1*rvs.sum(1)
    data_endog = np.random.poisson(np.exp(xbeta))
    n_infl = nobs//5
    n_infl = np.random.binomial(nobs, 0.2)
    data_endog[:n_infl] = 0   # artificially set to zero
    
    
    mod_glm = sm.GLM(data_endog, data_exog, family=sm.families.Poisson())
    res_glm = mod_glm.fit()
    
    #estimate generic MLE
    #self.mod = PoissonGMLE(data_endog, data_exog)
    #res = self.mod.fit()
    
    #create offset variable based on first exog
    res_discrete = Poisson(data_endog, data_exog).fit(disp=0)
    offset = res_discrete.params[0] * data_exog[:,0]  #1d ???
    
    #estimate discretemod.Poisson as benchmark, now has offset
    res_discrete = Poisson(data_endog, data_exog[:,1:], offset=offset).fit(disp=0)
    
    # Note : ZI has one extra parameter
    res = PoissonZiGMLE(data_endog, data_exog[:,:]#, offset=offset
                        ).fit(
                        start_params=np.r_[0.1, 0.9*res_discrete.params, 1],
                        method='bfgs', disp=0)
    
    print(res.summary())
    
    print()
    print(res.predict())
    print(res.predict(which='linear'))
    print(res.predict(which='poisson-mean'))
    print(res.predict(which='mean-nonzero'))
    
    print()
    
    prob_poisson =  1 / (1 + np.exp(-res.params[-1]))
    
    print('mix-prob poisson', prob_poisson)
    print('count zeros', res.predict(which='prob-zero').mean(), (data_endog == 0).mean())
    
    print('mean nonzeros', res.predict(which='mean-nonzero').mean(), 
                     data_endog[data_endog > 0].mean())
    
    print('mean', res.predict(which='mean').mean(), data_endog.mean())
    
    print('mean poisson', res.predict(which='poisson-mean').mean(), 
                          np.exp(xbeta).mean())
    print('mean linear', res.predict(which='linear').mean(), 
                         (xbeta).mean())
    
  4. josef-pkt commented on Jul 16, 2018

    @josef-pkt
    Member

    A predict function similar to the one in my previous comment has been added to the new count models in discrete including zero-inflated.

    I think we don't need to add this to the misc models version.
    However, the doc string of the miscmodel should point to the discrete version, and we keep the miscmodels version just as example and test case for GenericLikelihoodModel.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions