You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
BUG: discrete.discrete_model MNLogitResults.summary2() raises ValueError in new smoketest #3651
======================================================================
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.
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)
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.
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?
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.
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.
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.
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.
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.
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_intcan 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?
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.
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.
Activity
josef-pkt commentedon May 9, 2017
as background: for
summary(notsummary2)summaryis defined in DiscreteResults, which delegates toiolib.summary.Summary.add_table_paramswhich is doing the delegation to 1-D or 2D
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)jbrockmendel commentedon May 9, 2017
summary2's docstring says it is experimental. Is there some plan to phase out or mergesummary/summary2?josef-pkt commentedon May 9, 2017
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.
jbrockmendel commentedon May 9, 2017
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:Calling
res.summary2()produces the error I expect:But when I go to step through
summary2line-by-line, it breaks before even getting to thesummary_paramscall. Instead it raises an error in the call toself.conf_int(alpha):I don't have a good explanation for this behavior, which usually suggests "user error". Can you reproduce it?
jbrockmendel commentedon May 9, 2017
Tentative hypothesis: when I call
res.conf_int()manually, that is the ResultsWrapper method I'm calling. But whenconf_intgets called from within thesummary2call, it is theResultsmethod.jbrockmendel commentedon May 10, 2017
The arguments being passed to
summary_paramslook like they're intended for a different function.josef-pkt commentedon May 10, 2017
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
selfand use a tuple, then this part worksHowever, in summary2, the tuple unpacking uses the wrong name
std_err(from memory because change) instead ofbse(raises later thatbseis not defined)results, params, std_err, tvalues, pvalues, conf_int = resultsIf I fix that
results, params, bse, tvalues, pvalues, conf_int = resultsthen I just get a bit further to
because if we provide a tuple with the values, then it doesn't have the names.
etc. etc. etc.
jbrockmendel commentedon May 10, 2017
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_intmethod also raises an Error; I'm going to spend some time on that.josef-pkt commentedon May 10, 2017
I got the fix.
We need results included in the tuple but the
alphaneeds to be a separate keywordi.e.
and in summary_params
with these two changes, I get a summary table without exception
josef-pkt commentedon May 10, 2017
One advantage of
summary2would be that users can set print precision (significant digits) which is hard code insummary.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.
jbrockmendel commentedon May 10, 2017
I stumbled on a similar fix for the
summary2call, but a smoke-test forconf_intis still breaking. Setup same as above, but callres.conf_int()instead ofres.summary2().When it gets to
attach_columns, it breaks because the thesqueezedthat it is trying to wrap in apd.DataFramehas shape (6, 6, 2).One thing I tried to get around this was to set
_wrap_attrs["conf_int"] = "columns_eq"inMultinomialResultsWrapper. (Never mind thatcolumns_eqwould 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 withattach_columns.In this case it is just a coincidence that the first two dimensions are square. In general
conf_intpre-wrapping has shape(model.J-1, model.K, 2). The non-obviousness of this is what motivated #3652.josef-pkt commentedon May 10, 2017
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:
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.
josef-pkt commentedon May 10, 2017
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)
jbrockmendel commentedon May 10, 2017
Yah,
test_discrete.test_issue_339has a comment about testing the case withJ != K. I may have just by coincidence tacked these smoke-tests on to a weird case.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?
I'm going to really make sure the horse is dead and advocate for this one.
This seems weakly-dominated by the
MultiIndexoption 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).MultiIndexalso nests nicely for when we eventually have a 4-D case. e.g.irf.cov()has shape(steps, neqs**2, neqs**2). Looking at justcov[0, :, :], I imagine something like:I have no idea if the example labelling actually corresponds to the output of
irf.cov, which is kind of the point.I'd have to double-check, but I expect that
stack()places nicely withravel().Not sure I follow. The reason I'm suggesting MultIIndex is largely so that
conf_intcan stay 2-dimensional. Just one of those dimensions is['lower', 'upper']:Stepping back, you've mentioned that
MNLogitandVARare special cases. Are there other 2+ dimensional cases?josef-pkt commentedon May 10, 2017
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#L526Do 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_xxxmethod. conf_int needs to work for both 2-D and 3-D, so it needs to go through the current path.jbrockmendel commentedon May 10, 2017
Going back to the specific case for this comment. I got this working with the following:
In discrete_model, patch
MultinomialResultsWrapper._wrap_methodswith a new option forhow:Then in
data.ModelData.wrap_outputadd a clause to check fordictcases:and finally defining an
attach_dictmethod: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
howdictionary as a_axisattribute to theconf_intmethod. Then back inwrapperI had patchedmake_wrapperto check for this and override thehowarg 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.BUG: fix summary2 for MNLogit, see statsmodels#3651