Skip to content

ENH: Allow predict to return a DataFrame - #2884

Merged
josef-pkt merged 18 commits into
statsmodels:masterfrom
bfcondon:pandas-predict
Apr 25, 2016
Merged

josef-pkt merged 18 commits into
statsmodels:masterfrom
bfcondon:pandas-predict

Conversation

@bfcondon

@bfcondon bfcondon commented Apr 4, 2016

Copy link
Copy Markdown
Contributor

Modified the RegressionModel predict method to return a pandas DataFrame if the original model data was in the form of a DataFrame.

Fixes #1352

@bfcondon

bfcondon commented Apr 4, 2016

Copy link
Copy Markdown
Contributor Author

This is my first pull request, so I apologize if I didn't follow the correct procedure.

@josef-pkt

Copy link
Copy Markdown
Member

@bfcondon Thanks for working on this.

These changes need to go into the Results instance predict and not the model.predict.
FYI: We have two classes Model like OLS and the results class. The user is accessing (almost) all methods through the results class, the model methods, except fit, are mostly internal, but public for advanced use.

The results predict method is for most models outside of tsa the same and is defined at the top level of our class hierarchy https://github.com/statsmodels/statsmodels/blob/master/statsmodels/base/model.py#L717

here is how I implemented pandas indexing for a new get_prediction method (#2151) that is not yet generically available, but is for linear regression models
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/regression/_prediction.py#L132

Note exog for prediction will in most cases be different from the exog and index in orig_data, and we need to get the index from the predict exog.

#2151 It looks like the PR didn't add unit tests for a new exog that is a dataframe.

A possible complication to do this on the top level is what the predict return could be 2 dimensional, and a if fittedvalues.ndim > 1 then return DataFrame else return Series might be necessary.
(This reminds me that there might not be any test cases for returning a scalar prediction, i.e. exog for prediction is a DataFrame with one row.)

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.006%) to 85.372% when pulling 29fd201 on bfcondon:pandas-predict into 970e99e on statsmodels:master.

@bfcondon

bfcondon commented Apr 9, 2016

Copy link
Copy Markdown
Contributor Author

Are there any tests you think I should add?

@josef-pkt

Copy link
Copy Markdown
Member

I'll check in a few hours. I think there are some generic tests across models that we could reuse for this.
multinomial disrete_model MNLogit has some problems in some results statistics and will need specific unit test I think.

@josef-pkt

Copy link
Copy Markdown
Member

There is a generic test for predict in statsmodels.base
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/base/tests/test_generic_methods.py#L122

some of those are just smoke tests.
You could add a call to predict with a pandas DataFrame to those tests.

Those generic tests don't include MNLogit because it doesn't have the same pattern.
It also doesn't include tsa models, but those have mostly their own predict methods
(checking: AR, ARMA/ARIMA and statespacemodels all have their own predict method in results. VAR doesn't inherit from statsmodels.base and I don't see a predict method in the source, only forecast.)

@josef-pkt

Copy link
Copy Markdown
Member

predict with exog=None is a bit unclear. It is uses in several places internally where we expect and ndarray. The pandas wrapped version is usually available as fittedvalues, IIRC.

I'm not sure we want or need to return a pandas Series or DataFrame in that case. I don't see an easy solution to get both behaviors.

@kaiminglee

Copy link
Copy Markdown

josef-pkt, I looked at your code L132, and it only seems to match row_labels (index), not col_labels (columns). Why not test of exog is a DataFrame (or Series), and in case of DataFrame, return (self.param*exog).sum(axis=1)?

I ran into this recently when I used an exog with columns in different order than in the original design matrix. One of the main selling points of pandas is automatic index/column alignment regardless of order, so I think statsmodels should not ignore either unless for a good reason. If you agree on this principle, I could help with coding.

@josef-pkt

Copy link
Copy Markdown
Member

@kaiminglee Please open a separate issue for this?
Nobody had brought this up before, but I think we can add it to the input handling. It works correctly when patsy does the transform of the exog for predict if a formula was used. But we don't check the content of the DataFrame when formulas are not used.
We cannot hardcode the dot product because the prediction is model specific, and relies on the predict method in the models.

@kaiminglee

Copy link
Copy Markdown

I think there is not much to share between prediction methods for different model types, so I don't see problems with doing this on a model-by-model basis (starting with better behavior for OLS,predict(), which hardcodes np.dot() anyway in the current version).

I'll open a separate issue for this.

@josef-pkt

Copy link
Copy Markdown
Member

@kaiminglee
See my first comment above. We are not using pandas inside of statsmodels, pandas and numpy behave too differently to maintain that at manageable cost, except for a few special cases. The interface is restricted to localized conversion. Converting to pandas inside of the models will break statsmodels at various places. (Besides, the pandas dot product wouldn't work because params is internally just a numpy array without any information about names or labels of the elements.)
The conversion is generic and cannot be put into methods of individual models. (Again with a few special case exceptions, mainly where we want to take advantage of pandas' groupby methods.)

@kaiminglee

Copy link
Copy Markdown

3 points:

(1)

the pandas dot product wouldn't work because params is internally just a numpy array without any information about names or labels of the elements

I just tested this on 0.6.1 and this seems wrong. sm.OLS(y, X).fit().params is a pandas Series with parameter labels taken from X if X is a DataFrame. (and even if X is not a DataFrame but y is a Series/DataFrame, using surrogate x1, x2, ... labels). If exog is a DataFrame, exog.dot(params) works exactly as expected (namely first aligning exog column labels to params index labels), while the current implementation does not by ignoring exog column labels.

(2)
In the current version predict() in both the OLS and the RegressionResultsWrapper classes are fully implemented inside the RegressionModel class, not inheriting from anything from base. So I don't see why pandas dot can't just be called inside there. Why won't a simple insertion of

    from pandas.core.series import DataFrames
    if isinstance(exog, DataFrame):
        return exog.dot(params)

before return np.dot(exog, params) work? It doesn't convert any numpy arrays to DataFrames, it just does calls the appropriate method when exog already is a DataFrame.

(3)
Note the comment for class OLS in line 742: #TODO: change example to use datasets. This was the point of datasets!. Surely the point of datasets is not to ignore the labels when they're already there?

@josef-pkt

Copy link
Copy Markdown
Member

@kaiminglee

(1) sm.OLS(y, X).fit().params returns the wrapped result not the internally use numpy array if y and X are Series/DataFrames. sm.OLS(y, X).fit()._results is the "real" internal results instance.
`aligning each time we do an operation is very bad for performance, because exog (or whatever else) would have to be copied to rearrange columns.

(2) OLS.predict or generally model.predict is internal. The access for users goes through the results instance which is generic, inherited and has additional patsy handling if needed. That's the proper location for any changes, as I pointed out before.
This also means Dataframes never go to the model.predict.

(3) I don't disagree with the usecase, we can use the labels, but not inside statsmodels.

Some developers write their computation code with pandas, but not in statsmodels. Mixing pandas and numpy arrays requires a lot of "very careful coding", and that's too much pain for my taste.
I'm all in favor in closing gaps where our pandas support is still not good enough, as this PR does, but only at well defined boundaries.
Even if it is simple to adjust in specific models, I don't like inconsistencies in the pattern across models because it makes the code much less "obvious", and more difficult to understand.

@bfcondon

bfcondon commented Apr 15, 2016 •

Copy link
Copy Markdown
Contributor Author

I added the tests and it is almost working, but one main test fails. It is caused by the hazard_regression predict method returning a bunch object as follows:

<statsmodels.duration.hazard_regression.PHReg.predict.<locals>.bunch object at 0x7f2c2d79b908>

Is there a way to identify when this bunch object will be returned so I can exclude it?

@josef-pkt

Copy link
Copy Markdown
Member

@bfcondon
add a hasattr(..., 'predicted_values') check and then skip the conversion to pandas DataFrame as temporary solution

I was just looking at PHReg, and have not yet looked in details at your latest changes.

I will open a new issue for this. I think this needs to be changed in PHReg so we have consistent code and definition of returns across models.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.001%) to 85.377% when pulling 81ff81d on bfcondon:pandas-predict into 970e99e on statsmodels:master.

@bfcondon

Copy link
Copy Markdown
Contributor Author

Tests are now passing. Let me know if you have any comments.

Comment thread statsmodels/base/model.py Outdated
return self.model.predict(self.params, exog, *args, **kwargs)
predict_results = self.model.predict(self.params, exog, *args, **kwargs)

if (isinstance(orig_exog, pd.Series) or isinstance(orig_exog, pd.DataFrame) and

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why did you switch to an instance check instead of just checking for an attribute index?

@bfcondon bfcondon Apr 15, 2016 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When I checked for the index attribute, it did not uniquely identify the pandas object. I received the several errors similar to the following:

ERROR: statsmodels.base.tests.test_generic_methods.TestGenericGEEPoisson.test_predict_types

Traceback (most recent call last):
File "/home/brendan/anaconda3/envs/statsmodels-test/lib/python3.4/site-packages/nose/case.py", line 198, in runTest
self.test(*self.arg)
File "/home/brendan/statsmodels/statsmodels/base/tests/test_generic_methods.py", line 152, in test_predict_types
assert_allclose(fitted, res.predict(np.squeeze(p_exog).tolist()),
File "/home/brendan/statsmodels/statsmodels/base/model.py", line 769, in predict
return pd.Series(predict_results, index=row_labels)
File "/home/brendan/anaconda3/envs/statsmodels-test/lib/python3.4/site-packages/pandas/core/series.py", line 151, in init
index = _ensure_index(index)
File "/home/brendan/anaconda3/envs/statsmodels-test/lib/python3.4/site-packages/pandas/core/index.py", line 3963, in _ensure_index
return Index(index_like)
File "/home/brendan/anaconda3/envs/statsmodels-test/lib/python3.4/site-packages/pandas/core/index.py", line 172, in new
subarr = com._asarray_tuplesafe(data, dtype=object)
File "/home/brendan/anaconda3/envs/statsmodels-test/lib/python3.4/site-packages/pandas/core/common.py", line 2170, in _asarray_tuplesafe
values = list(values)
TypeError: 'builtin_function_or_method' object is not iterable

@josef-pkt

Copy link
Copy Markdown
Member

Thanks,
I added two questions about the implementation.
I'll look at the unit tests later, most likely tonight.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.001%) to 85.377% when pulling 44f032c on bfcondon:pandas-predict into 970e99e on statsmodels:master.

@bfcondon bfcondon changed the title ENH: Allow predict to return a DataFrame [issue 1352] ENH: Allow predict to return a DataFrame Apr 15, 2016
@bfcondon

Copy link
Copy Markdown
Contributor Author

@josef-pkt I responded to your questions. Do you have any comments on the tests?

@bfcondon

Copy link
Copy Markdown
Contributor Author

@josef-pkt Did you have any other comments? I am happy to make further updates.

@josef-pkt

Copy link
Copy Markdown
Member

@bfcondon
I'm sorry, I got distracted for a week. I'll go over it tonight.

@josef-pkt

Copy link
Copy Markdown
Member

Looks good. I think we can merge it as it is.
Can you squash this into a single commit?
This has a large number of commits, and the intermediate commits are not really relevant to understand the final changeset.

@bfcondon

Copy link
Copy Markdown
Contributor Author

@josef-pkt
josef-pkt merged commit ff5d01b into statsmodels:master Apr 25, 2016
@josef-pkt

josef-pkt commented Apr 25, 2016 •

Copy link
Copy Markdown
Member

Ok, merged with squash through github, but it doesn't create a merge commit, so we won't use this.

we only want to have no-ff merges into master which makes it easier to distinguish merge commits with git log, and shows the branch merge in the network tree.
I don't see an option for squashing and no-ff merge in the github interface.
Full squashing before merge is an exception for statsmodels.

One advantage is that the original PR branch doesn't need to be rebased, which keeps the original commit-comment sequence. (i.e. similar to commandline merge, but that is extra work, that we mostly avoid.)

@bfcondon

Copy link
Copy Markdown
Contributor Author

Thanks. For future reference, what is the right way to flatten a bunch of commits on a branch?

@bfcondon
bfcondon deleted the pandas-predict branch April 25, 2016 23:55
@bfcondon
bfcondon restored the pandas-predict branch April 25, 2016 23:56
@josef-pkt

josef-pkt commented Apr 26, 2016 •

Copy link
Copy Markdown
Member

@bfcondon Thank you for your first contribution.

For future reference, what is the right way to flatten a bunch of commits on a branch?

I usually use interactive rebase to squash or make other changes to the commits, and then force push or push to a new branch. If there are no merge conflicts, then it's automatic after editing the commit text file.
git rebase -i remotes/origin/master "origin" is the official statsmodels repo in my maintenance clone/checkout.
In most cases we don't squash or squash only selected commits, especially when there are competing implementation in earlier commits or discussion on numerical issues, which might be useful information to understand the code in future.
edit: another main reason for not squashing is that some merges are very large, and the code is much easier to understand by looking only at a set of related commits at a time.

@bfcondon
bfcondon deleted the pandas-predict branch April 30, 2016 07:31
@bfcondon
bfcondon restored the pandas-predict branch April 30, 2016 07:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants