Skip to content

get_margeff raises an IndexError for negative binomial regression results when at='all' #6763

Closed

Description

@cczhu

Describe the bug

I'm fitting data using statsmodels.api.NegativeBinomial. When attempting to get the marginal effects from the results using results.get_margeff(at='all', method='eyex'), Statsmodels raises an IndexError, I think due to the mismatch between the exogenous variables matrix and effects_idx.

Code Sample, a copy-pastable example if possible

import pandas as pd
import numpy as np
import statsmodels.api as sm

high = 5.
n_obs = 5000
alpha = 6.5
const = 0.

np.random.seed(42)

betas = pd.Series([0.62, -1.71], index=['aa', 'bb'])

df_exog = pd.DataFrame(np.random.uniform(high=high, size=(n_obs, 2)),
                       columns=betas.keys())
lambda_expected = np.exp(df_exog.dot(betas) + const)
gamma_draws = np.random.gamma(1. / alpha, alpha, size=n_obs)
endog = np.random.poisson(lam=(lambda_expected * gamma_draws))

model = sm.NegativeBinomial(
    endog=endog, exog=sm.add_constant(df_exog))
results = model.fit(maxiter=100, disp=False)
#  This raises the error.
results.get_margeff(at='all', method='eyex')

Expected Output

An array of marginal effects for all exogenous variables at each observation.

Output of import statsmodels.api as sm; sm.show_versions()

I get an IndexError

IndexError: boolean index did not match indexed array along dimension 1; dimension is 3 but corresponding boolean dimension is 4

In line 728 of discrete_margins.py it looks like effects_idx is corrected for this dimension mismatch, but only when at is not equal to 'all'.

From import statsmodels.api as sm; sm.show_versions() :


INSTALLED VERSIONS
------------------
Python: 3.6.9.final.0
OS: Linux 4.4.0-18362-Microsoft #836-Microsoft Mon May 05 16:04:00 PST 2020 x86_64
byteorder: little
LC_ALL: None
LANG: C.UTF-8

statsmodels
===========

Installed: 0.11.1 (/home/czhu/pythonenv/bditto/lib/python3.6/site-packages/statsmodels)

Required Dependencies
=====================

cython: 0.29.15 (/home/czhu/pythonenv/bditto/lib/python3.6/site-packages/Cython)
numpy: 1.18.4 (/home/czhu/pythonenv/bditto/lib/python3.6/site-packages/numpy)
scipy: 1.4.1 (/home/czhu/pythonenv/bditto/lib/python3.6/site-packages/scipy)
pandas: 1.0.3 (/home/czhu/pythonenv/bditto/lib/python3.6/site-packages/pandas)
    dateutil: 2.8.1 (/home/czhu/pythonenv/bditto/lib/python3.6/site-packages/dateutil)
patsy: 0.5.1 (/home/czhu/pythonenv/bditto/lib/python3.6/site-packages/patsy)

Optional Dependencies
=====================

matplotlib: 3.2.0 (/home/czhu/pythonenv/bditto/lib/python3.6/site-packages/matplotlib)
    backend: module://ipykernel.pylab.backend_inline 
cvxopt: Not installed
joblib: 0.15.1 (/home/czhu/pythonenv/bditto/lib/python3.6/site-packages/joblib)

Developer Tools
================

IPython: 7.14.0 (/home/czhu/pythonenv/bditto/lib/python3.6/site-packages/IPython)
    jinja2: 2.11.2 (/home/czhu/pythonenv/bditto/lib/python3.6/site-packages/jinja2)
sphinx: Not installed
    pygments: 2.6.1 (/home/czhu/pythonenv/bditto/lib/python3.6/site-packages/pygments)
pytest: 5.4.1 (/home/czhu/pythonenv/bditto/lib/python3.6/site-packages/pytest)
virtualenv: 20.0.5 (/home/czhu/pythonenv/bditto/lib/python3.6/site-packages/virtualenv)

I've also tried building statsmodels v0.12.0.dev0+326.g856385ac1 from source and running the code snippet, and find the same error.

Activity

  1. josef-pkt commented on May 29, 2020

    @josef-pkt
    Member

    PR #3811 fixed the margins for the extra params as in NegBin or GP, but looks like it missed this case.

    Thanks for the report and for providing an example that can be run immediately

    The exception is raised on line 711 in current code

            else:
                    self.margeff = effects[:, effects_idx]
    
  2. josef-pkt commented on May 30, 2020

    @josef-pkt
    Member

    I don't see why I needed to extend the effects_idx for extra params in #3811.
    unit tests and examples that I tried run fine without that part.

    indexing into effects and exog, only require index with len equal to exog.shape[1}.
    indexing into params and cov_params will need full indexing including the extra

            if hasattr(model, 'k_extra') and model.k_extra > 0:
                effects_idx = np.concatenate((effects_idx, np.zeros(model.k_extra, np.bool_)))
    
  3. josef-pkt commented on May 30, 2020

    @josef-pkt
    Member

    AFAIU now

    the only relevant change is in _derivative_exog in the case when that is available
    https://github.com/statsmodels/statsmodels/pull/3811/files#diff-a494553e88130577065e0b012246ca51L806

    margeff_cov_params uses the jacobian (from _derivative_exog ) in the dot product with cov_params, so this reduces the size of cov_params to the number of exog, i.e. rows in jacobian.
    So margeff_cov should have size without k_extra, and original bug in #3809 shouldn't show up.

    Not adding k_extra zeros to effects_idx works for all method and at in the NegativeBinomial.
    Still need to check other count models, GPP, NBP. I guess zeroinflated is not supported.

    Question is what happens if model does not specify _derivative_exog. In that case numerical derivative is used in margeff_cov_params

    we need at least smoke tests for all cases

    methods = ["dydx", "eyex", "dyex", "eydx"]
    at_all = ["overall", "mean", "median", "zero", "all"]
    for m in methods:
        for a in at_all:
            marge = results.get_margeff(at=a, method=m)
            print(marge.margeff_options)
    
  4. josef-pkt commented on Sep 14, 2020

    @josef-pkt
    Member

    quickfix merged in #6939 for 0.12

    no unit tests added, added to summ issue #2154

  5. added this to the 0.13 milestone on Sep 9, 2021
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