Skip to content

BUG: discrete.discrete_model MNLogitResults.summary2() raises ValueError in new smoketest #3651

Closed

Description

@jbrockmendel

Copied over from #3649:

======================================================================
ERROR: statsmodels.discrete.tests.test_discrete.test_mnlogit_factor
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/travis/miniconda2/envs/statsmodels-test/lib/python2.7/site-packages/nose/case.py", line 197, in runTest
    self.test(*self.arg)
  File "/home/travis/miniconda2/envs/statsmodels-test/lib/python2.7/site-packages/statsmodels-0.8.0-py2.7-linux-x86_64.egg/statsmodels/discrete/tests/test_discrete.py", line 1436, in test_mnlogit_factor
    summary2 = res.summary2()
  File "/home/travis/miniconda2/envs/statsmodels-test/lib/python2.7/site-packages/statsmodels-0.8.0-py2.7-linux-x86_64.egg/statsmodels/discrete/discrete_model.py", line 3028, in summary2
    confint[i])
  File "/home/travis/miniconda2/envs/statsmodels-test/lib/python2.7/site-packages/statsmodels-0.8.0-py2.7-linux-x86_64.egg/statsmodels/iolib/summary2.py", line 339, in summary_params
    data = np.hstack([data, conf_int])
  File "/home/travis/miniconda2/envs/statsmodels-test/lib/python2.7/site-packages/numpy/core/shape_base.py", line 277, in hstack
    return _nx.concatenate(arrs, 1)
ValueError: all the input array dimensions except for the concatenation axis must match exactly

Digging into this, it looks like we're trying to concatenate arrays with shapes (6,6,4) and (6,6,2), respectively. So we can make a little bit of progress by replacing np.hstackwith np.concatenate(arrs, 2). But in the next line we try to wrap the result in a DataFrame, which breaks because it is 3D. I think the underlying issue is that summary_params doesn't play nicely with two-dimensional params.

This is a design-decision issue. I don't actually use this model often enough to have an opinion.

Activity

  1. josef-pkt commented on May 9, 2017

    @josef-pkt
    Member

    as background: for summary (not summary2)

    summary is defined in DiscreteResults, which delegates to iolib.summary.Summary.add_table_params
    which is doing the delegation to 1-D or 2D

            if res.params.ndim == 1:
                table = summary_params(res, yname=yname, xname=xname, alpha=alpha,
                                       use_t=use_t)
            elif res.params.ndim == 2:
                _, table = summary_params_2dflat(res, endog_names=yname,
                                                 exog_names=xname,
                                                 alpha=alpha, use_t=use_t)
    

    AFAIK, handling of 2-D params was never added to summary2

    (Related:
    We have related bugs for 2-D params, t_test, #669, #457, needs unique names for the flattened params to get through patsy, but summary never constructs combined names, AFAICS.
    MultinomialResults_get_endog_name(self, yname, yname_list, all=False) constructs or gets the list of endog/level names used in summary)

  2. jbrockmendel commented on May 9, 2017

    @jbrockmendel
    ContributorAuthor

    summary2's docstring says it is experimental. Is there some plan to phase out or merge summary/summary2?

  3. josef-pkt commented on May 9, 2017

    @josef-pkt
    Member

    Is there some plan to phase out or merge summary/summary2?

    Currently not, there was supposed to be some friendly competition between the two with one survivor, but that never happened. Essentially, summary is very rigid, fine tuned for the fixed font display, summary2 is more flexible, but still has open bug issues. We added them both to the initial models, so it's easier to compare them and to see whether we get any feedback on preference.

    New models get mostly whichever version the developer wants or fits better, or get both.

  4. jbrockmendel commented on May 9, 2017

    @jbrockmendel
    ContributorAuthor

    I'm having trouble tracking down this error, could use another pair of eyes. The smoke-test is tacked on to test_discrete.test_mnlogit_factor, so can be setup with:

    import statsmodels.api as sm
    dta = sm.datasets.anes96.load_pandas()
    dta['endog'] = dta.endog.replace(dict(zip(range(7), 'ABCDEFG')))
    dta.exog['constant'] = 1
    mod = sm.MNLogit(dta.endog, dta.exog)
    res = mod.fit(disp=0)
    

    Calling res.summary2() produces the error I expect:

    >>> res.summary2()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/usr/local/lib/python2.7/site-packages/statsmodels/discrete/discrete_model.py", line 3043, in summary2
        confint[i])
      File "/usr/local/lib/python2.7/site-packages/statsmodels/iolib/summary2.py", line 339, in summary_params
        data = np.hstack([data, conf_int])
      File "/usr/local/lib/python2.7/site-packages/numpy/core/shape_base.py", line 288, in hstack
        return _nx.concatenate(arrs, 1)
    ValueError: all the input array dimensions except for the concatenation axis must match exactly
    

    But when I go to step through summary2 line-by-line, it breaks before even getting to the summary_params call. Instead it raises an error in the call to self.conf_int(alpha):

    >>> res.conf_int(0.05)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/usr/local/lib/python2.7/site-packages/statsmodels/base/wrapper.py", line 95, in wrapper
        obj = data.wrap_output(func(results, *args, **kwargs), how)
      File "/usr/local/lib/python2.7/site-packages/statsmodels/base/data.py", line 407, in wrap_output
        return self.attach_columns(obj)
      File "/usr/local/lib/python2.7/site-packages/statsmodels/base/data.py", line 524, in attach_columns
        return DataFrame(result, index=self.param_names)
      File "/usr/local/lib/python2.7/site-packages/pandas/core/frame.py", line 306, in __init__
        copy=copy)
      File "/usr/local/lib/python2.7/site-packages/pandas/core/frame.py", line 463, in _init_ndarray
        values = _prep_ndarray(values, copy=copy)
      File "/usr/local/lib/python2.7/site-packages/pandas/core/frame.py", line 5688, in _prep_ndarray
        raise ValueError('Must pass 2-d input')
    ValueError: Must pass 2-d input
    

    I don't have a good explanation for this behavior, which usually suggests "user error". Can you reproduce it?

  5. jbrockmendel commented on May 9, 2017

    @jbrockmendel
    ContributorAuthor

    Tentative hypothesis: when I call res.conf_int() manually, that is the ResultsWrapper method I'm calling. But when conf_int gets called from within the summary2 call, it is the Results method.

  6. jbrockmendel commented on May 10, 2017

    @jbrockmendel
    ContributorAuthor

    The arguments being passed to summary_params look like they're intended for a different function.

  7. josef-pkt commented on May 10, 2017

    @josef-pkt
    Member

    The best would be to check the line histories/blame to see what changed.

    After debugging a bit, my guess that this never worked, or that something fundamentally changed.

    summary_params required either the results instance or all the values in a tuple

    if I delete self and use a tuple, then this part works

    coefs = summary2.summary_params((alpha, self.params[:,i],
                        self.bse[:,i], self.tvalues[:,i], self.pvalues[:,i],
                        confint[i]))
    

    However, in summary2, the tuple unpacking uses the wrong name std_err (from memory because change) instead of bse (raises later that bse is not defined)
    results, params, std_err, tvalues, pvalues, conf_int = results

    If I fix that
    results, params, bse, tvalues, pvalues, conf_int = results
    then I just get a bit further to

        data.index = results.model.exog_names
    AttributeError: 'float' object has no attribute 'mode'
    

    because if we provide a tuple with the values, then it doesn't have the names.

    etc. etc. etc.

  8. jbrockmendel commented on May 10, 2017

    @jbrockmendel
    ContributorAuthor

    I propose that this falls into the category of "clearly never used in the wild" and that at this point we're better off deprecating it than trying to fix it.

    The conf_int method also raises an Error; I'm going to spend some time on that.

  9. josef-pkt commented on May 10, 2017

    @josef-pkt
    Member

    I got the fix.

    We need results included in the tuple but the alpha needs to be a separate keyword

    i.e.

    coefs = summary2.summary_params((self, self.params[:,i],
                        self.bse[:,i], self.tvalues[:,i], self.pvalues[:,i],
                        confint[i]), alpha=alpha)
    

    and in summary_params

    if isinstance(results, tuple):
            results, params, bse, tvalues, pvalues, conf_int = results
    

    with these two changes, I get a summary table without exception

                             Results: MNLogit
    ==================================================================
    Model:              MNLogit          Pseudo R-squared: 0.165      
    Dependent Variable: PID              AIC:              2995.8455  
    Date:               2017-05-09 21:51 BIC:              3170.4500  
    No. Observations:   944              Log-Likelihood:   -1461.9    
    Df Model:           30               LL-Null:          -1750.3    
    Df Residuals:       908              LLR p-value:      1.8223e-102
    Converged:          1.0000           Scale:            1.0000     
    No. Iterations:     7.0000                                        
    ------------------------------------------------------------------
      PID = 0      Coef.   Std.Err.     t     P>|t|    [0.025   0.975]
    ------------------------------------------------------------------
    logpopul      -0.0115    0.0343  -0.3365  0.7365  -0.0787   0.0557
      selfLR       0.2977    0.0936   3.1798  0.0015   0.1142   0.4812
         age      -0.0249    0.0065  -3.8231  0.0001  -0.0377  -0.0122
    
    ...
    
  10. josef-pkt commented on May 10, 2017

    @josef-pkt
    Member

    One advantage of summary2 would be that users can set print precision (significant digits) which is hard code in summary.

    However, there is a bug deep inside of iolib.summary2 #1964 where I didn't get far enough to figure out how to fix it.

    If that is fixed, then all existing summary2 would have an additional functioning option. Unfortunately, not now.

  11. jbrockmendel commented on May 10, 2017

    @jbrockmendel
    ContributorAuthor

    I stumbled on a similar fix for the summary2 call, but a smoke-test for conf_int is still breaking. Setup same as above, but call res.conf_int() instead of res.summary2().

    When it gets to attach_columns, it breaks because the the squeezed that it is trying to wrap in a pd.DataFrame has shape (6, 6, 2).

    One thing I tried to get around this was to set _wrap_attrs["conf_int"] = "columns_eq" in MultinomialResultsWrapper. (Never mind that columns_eq would be wrong too, not actually relevant at this point). I haven't figured out why, but it didn't "take", and still tried to wrap with attach_columns.

    In this case it is just a coincidence that the first two dimensions are square. In general conf_int pre-wrapping has shape (model.J-1, model.K, 2). The non-obviousness of this is what motivated #3652.

  12. josef-pkt commented on May 10, 2017

    @josef-pkt
    Member

    I remember now the problem square example case. I think I or we changed it in at least one unit test case, because square might hide dimension/shape problems.

    I'm not sure what to do about 3-D objects with pandas wrappers. The standard would be to add an additional case to the wrapper handling code. But if pandas doesn't have 3-D arrays, then it get's more complicated.
    I just checked, VAR doesn't have conf_int, so it doesn't provide a precedence case.
    choices, AFAICS:

    • find 3-D alternative to pandas
    • reshape to 2-D with multi index
    • reshape to 2-D with simple index and combined names
    • ignore it in conf_int and get 2-D summary_frame with explicit DataFrame conversion code

    related: #669 needs access to combined names for the raveled params, which would be similar here if we want reshaped 2-D conf_int instead of a MultiIndex.

  13. josef-pkt commented on May 10, 2017

    @josef-pkt
    Member

    summary_frame with e.g. multi index might be the easiest way to provide this to the user

    e.g. summary2 constructs the individual tables for each "equation", level of endog, which would need to be merged (using summary2 or similar code)

    >>> res.summary2().tables[1].columns
    Index(['PID = 0', 'Coef.', 'Std.Err.', 't', 'P>|t|', '[0.025', '0.975]'], dtype='object')
    
  14. jbrockmendel commented on May 10, 2017

    @jbrockmendel
    ContributorAuthor

    Yah, test_discrete.test_issue_339 has a comment about testing the case with J != K. I may have just by coincidence tacked these smoke-tests on to a weird case.

    find 3-D alternative to pandas

    A lot of the methods we're discussing revolve around displaying tabular output. pandas has put a lot of effort into doing that nicely. Unless you're referring to something else?

    reshape to 2-D with multi index

    I'm going to really make sure the horse is dead and advocate for this one.

    reshape to 2-D with simple index and combined names

    This seems weakly-dominated by the MultiIndex option because conversion is super-easy e.g. idx = mi.map(lambda x: '-'.join(x)). (Assuming everything is already str-like. I expect there exists something more elegant).

    MultiIndex also nests nicely for when we eventually have a 4-D case. e.g. irf.cov() has shape (steps, neqs**2, neqs**2). Looking at just cov[0, :, :], I imagine something like:

    # mi = pd.MultiIndex.from_product([endog_names, endog_names], names=['impulse', 'response'])
    >>> irf.cov()
    impulse                  A                   B          
    response                 A         B         A         B
    impulse response                                        
    A       A         0.084483 -0.006326 -0.001155 -0.002313
            B        -0.006326  0.084425 -0.002822  0.000860
    B       A        -0.001155 -0.002822  0.084684 -0.000940
            B        -0.002313  0.000860 -0.000940  0.084447
    

    I have no idea if the example labelling actually corresponds to the output of irf.cov, which is kind of the point.

    [...] needs access to combined names for the raveled params

    I'd have to double-check, but I expect that stack() places nicely with ravel().

    [...] which would be similar here if we want reshaped 2-D conf_int instead of a MultiIndex.

    Not sure I follow. The reason I'm suggesting MultIIndex is largely so that conf_int can stay 2-dimensional. Just one of those dimensions is ['lower', 'upper']:

    >>> exog_names = list('ABCD')
    >>> equation_labels = range(3)
    >>> ci = np.random.random(2*3*4).reshape(2, 3, 4)
    >>> lower = pd.DataFrame(ci[0], columns=exog_names, index=equation_labels)
    >>> upper = pd.DataFrame(ci[1], columns=exog_names, index=equation_labels)
    >>> ci = pd.DataFrame({'lower': lower.stack(), 'upper': upper.stack()}, columns=['lower', 'upper'])
    >>> ci
            lower     upper
    0 A  0.940612  0.595088
      B  0.761138  0.543540
      C  0.666907  0.374432
      D  0.379941  0.756258
    1 A  0.926425  0.093406
      B  0.018044  0.241078
      C  0.044096  0.063055
      D  0.322088  0.567861
    2 A  0.648697  0.403993
      B  0.152491  0.296791
      C  0.010783  0.433425
      D  0.200455  0.615637
    

    Stepping back, you've mentioned that MNLogit and VAR are special cases. Are there other 2+ dimensional cases?

  15. josef-pkt commented on May 10, 2017

    @josef-pkt
    Member

    Stepping back, you've mentioned that MNLogit and VAR are special cases. Are there other 2+ dimensional cases?

    Those are currently the only two official Models, VAR including SVAR (maybe not because it needs 1-D params for nonlinear optimization) and soon VECM.
    We have now statsmodels.multivariate which has a multivariate OLS that supports MANOVA, but is not finished as a standalone model.
    Then, there will be special cases for balanced panel, SUR or multi-equation models with the specific rectangular parameter structure.

    For general panel data or multi-equation models we need to stack observations and params because they will not have a rectangular structure. Also more general multinomial or discrete choice models it is not possible to fit them into a rectangular pattern.

    So we will have a few models where rectangular, 2-D params is more convenient and computationally efficient, but those will always be a few exceptions, or special cases.

    The general case for params is 1-D but often structured with different components, e.g. multi-equation models like system of equations would be naturally stacked with parameters having and implicit or explicit multi index. Some models need to have their own parameter class to do the structuring, like MixedLM has it currently. In those cases it will be difficult to use or find a generic structure, except that the generic code can assume it's 1-D.

    One possibility that is not clear yet to me are "vectorized" models, i.e. many models stuck together, as for example with moving or expanding windows OLS. numpy has had for some time now vectorized linear algebra that we don't use yet. They worked pretty well in some experiments, but I have no idea how those would be wrapped.

    Aside to more than 2-D: The alternative is xarray which follows in the user interface closely to pandas but is not restricted to 2-D. The discussion a while ago with pandas developers was that for multi-dimensional panel data xarray will be the alternative.
    The question for computational efficiency with multi-index is whether the reshaping that we need can be based on views or needs to copy the entire data, which would not be good if we have to do it in a loop.


    to fix conf_int wrapper with the usual pattern:
    The question is how to get the endog label information into the base.data class
    https://github.com/statsmodels/statsmodels/blob/master/statsmodels/base/data.py#L526

    if results.ndim > 2:  
        <reshape and construct MultiIndex>
    

    Do we have the relevant information for how to reshape and what labels/names to use in the MultiIndex?
    For reshape we might be able to standardize on order="F" so we don't need extra info, the endog/equation labels or names are currently in results, AFAICS.

    Attributes that are more than 2-D, but always the same like your irf example could get a new _attach_xxx method. conf_int needs to work for both 2-D and 3-D, so it needs to go through the current path.

  16. jbrockmendel commented on May 10, 2017

    @jbrockmendel
    ContributorAuthor

    Going back to the specific case for this comment. I got this working with the following:

    In discrete_model, patch MultinomialResultsWrapper._wrap_methods with a new option for how:

    how = {
            'output': ['equations', 'exog_names', 'columns'],
            'columns': ['lower', 'upper'],
            'index': ('exog_names', 'equations')
            }
    class MultinomialResultsWrapper(linear_model.RegressionResultsWrapper):
        _attrs = {"resid_misclassified": "rows"}
        _wrap_attrs = wrap.union_dicts(linear_model.RegressionResultsWrapper._wrap_attrs, _attrs)
        _methods = {"conf_int": how}
        _wrap_methods = wrap.union_dicts(linear_model.RegressionResultsWrapper._wrap_methods, _methods)
    wrap.populate_wrapper(MultinomialResultsWrapper, MultinomialResults)
    

    Then in data.ModelData.wrap_output add a clause to check for dict cases:

            elif how == 'ynames':
                return self.attach_ynames(obj)
            elif isinstance(how, dict):
                return self.attach_dict(obj, how)
            else:
                return obj
    

    and finally defining an attach_dict method:

    def attach_dict(self, result, info):
        shape = info['output']
        if np.ndim(result) != 3:
            raise NotImplementedError
        
        recognized = ['endog_names', 'exog_names', 'equations']
        idxs = [n for n in range(len(shape)) if shape[n] not in recognized]
        assert len(idxs) == 1
        idx = idxs[0]
    
        pre_frames = [np.take(result, n, idx) for n in range(result.shape[idx])]
        if pre_frames == []:
            raise ValueError('Should have squeezed at some point?')
        
        nidxs = [n for n in range(len(shape)) if n != idx]
        assert len(nidxs) == 2
    
        (neqs0, neqs1) = pre_frames[0].shape
        (index_key, col_key) = (shape[nidxs[0]], shape[nidxs[1]])
        label_dict = {'endog_names': self.ynames, 'exog_names': self.xnames, 'equations': None}
        index = label_dict[index_key]
        if index is None:
            # If axis 0 is intended to correspond to equations, we give it
            # the not-so-creative labels [0, 1, ..., N-1].
            index = range(neqs0)
        columns = label_dict[col_key]
        if columns is None:
            # Likewise for columns
            columns = range(neqs1)
    
        frames = [pd.DataFrame(x, index=index, columns=columns) for x in pre_frames]
        for frame in frames:
            # index.columns names will become level names in MultiIndex
            frame.index.name = index_key
            frame.columns.name = col_key  # TODO: better names?
    
        if isinstance(info['index'], tuple):
            # We apply a MultiIndex along the first dimension
            cols = info['columns']
            frame = pd.DataFrame({cols[n]: frames[n].stack() for n in range(len(cols))}, columns=cols)
            # Note: we need to pass columns kwarg to ensure we keep the same order
            return frame
       else:
           raise NotImplementedError
    

    Not exactly pretty, but I think it has the makings of general-form solution.

    Now for that part that I really expect no one but me will like. The above isn't quite what I actually did. Instead I added that how dictionary as a _axis attribute to the conf_int method. Then back in wrapper I had patched make_wrapper to check for this and override the how arg if it is found. I'm toying with this primarily because I like to see the relevant info directly next to the function body. Not really relevant to this thread.

  17. added this to the 0.10 milestone on Oct 8, 2017
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