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
wls_prediction_std needs to be update to handle formula-like syntax #987
This is blocking some work I'm doing - it'd be great to have easy access to CIs on predicted data but I can't get wls_prediction_std's exog parameter to work.
Do you want predicted new observation or predicted mean, X beta, for a new observation?
to get formula support
The easiest should be to go through t_test which already has wrapper for creating the exog for predict, and the standard errors for the mean.
For the standard errors for a new observation we still need to add the standard error of the residual as in wls_prediction_std.
I thought this is a enhancement request, but there is a bug in the weight handling.
I don't know why OLS defines weights now,
or which refactoring caused this, or if the bug was there all along.
If weights is not set in argument, then it uses the full length weights, which has now also for OLS the same length as the original data, I think it was a scalar 1 before.
after WLS, the default was also wrong if exog was defined in argument, but not weights.
besides the bug for arrays, there is still the last part missing which is the enhancement to support formulas
>>> wls_prediction_std(f, {'x':0.5})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "e:\josef\eclipsegworkspace\statsmodels-git\statsmodels-all-new2_py27\statsmodels\statsmodels\sandbox\regression\predstd.py", line 83, in wls_prediction_std
raise ValueError('wrong shape of exog')
ValueError: wrong shape of exog
You can either explicitly specify weights as a work-around, weights=1. should do it, or
PR #1582 adjusts the weight handling in wls_prediction_std.
(I might not finish that until after pycon.)
I added a workaround to the notebook above - I lifted the code that wraps model.predict() in Results.predict() to transform my exog to a form that wls_prediction_std can accept.
I'm not particularly happy with that workaround, think I might be close to a better solution
Updated the notebook once more with some suggested changes to wls_prediction_std() that would
It still requires factoring out the wrapper code, which I called transform_exog_to_model().
Side note - there was some suspicious workaround stuff in wls_prediction_std:
# work around current bug: <- This was suspicious.
predicted = res.model.predict(res.params, exog) <- apparently this is the workaround it's referring to?
It seems wiser to just use Result.predict() instead:
Using Result.predict will do the formula to exog conversion twice since we need both predicted and exog
Calling result predict from the outside will return the wrapped predicted, if we have the pandas wrapper for predict. This might mess up the calculations, but in this case it might be ok (there is just one addition )
Good points.
If we move the transformation earlier in wls_prediction_std, we could call
Result.predict() with transform=False and avoid redoing some of the
transformation. It just seems odd to me that the current code is
bypassing/recreating some of the work that Result.predict() does, but it
might be easier to leave it that way.
Thanks so much for your help; I leave the follow-through to the correct
solution in your hands!
Using Result.predict will do the formula to exog conversion twice since we
need both predicted and exog
Calling result predict from the outside will return the wrapped predicted,
if we have the pandas wrapper for predict. This might mess up the
calculations, but in this case it might be ok (there is just one addition )
Reply to this email directly or view it on GitHubhttps://github.com//issues/987#issuecomment-39991704
.
I haven't followed this closely, but an API suggestion based off what we have in ARIMA where we have a forecast vs. predict.
I was thinking in linear regression we continue to follow the get_ pattern where it returns some kind of results object. See get_influence. Here we would have get_predict, which would return a class that has prediction or fittedvalues attached, prediction_std_err, and conf_int. Probably also a plotting utility function. This way you only go through the transformations once, wls_prediction_std stays a separate function and only expects transformed data, and it's all done in one method.
TypeError: unsupported operand type(s) for /: 'float' and 'NoneType'
So it seems like weights is actually not optional right now. If I set weights to an array of ones though, looks great! (i.e. for a quadratic regression)
There might be an issue how to get weights in WLS for out of sample prediction intervals. If there is heteroscedasticity as in your plot, we would need the corresponding weights for new observations. By default we would use weights = 1. The latter could be missing if you get an exception with it.
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
df = pd.DataFrame({'x1': [3.17, 4.76, 4.17, 8.70, 11.45],
'x2': [23, 26, 73, 72, 16],
'y': [880.37, 716.20, 974.79, 322.80, 1054.25]},
index=np.arange(10, 20, 2))
result = smf.ols('y ~ x1 + x2', df).fit()
df['yhat'] = result.fittedvalues
df['resid'] = result.resid
result2 = sm.OLS(df['y'], sm.add_constant(df[['x1', 'x2']])).fit()
df['yhat2'] = result2.fittedvalues
df['resid2'] = result2.resid
# predict doesn't return pandas series and no index is available
df['predicted'] = result.predict(df)
print(df)
print(result.get_prediction().summary_frame())
Yeah, right now if you specify exog, you need to specify weights as well, that might be fine because usually you'd want weights anyway like in the scenario you described. In this case I just wanted the CI of the regression line itself so I just set weights = 1 for a range of values generated by np.linspace.
I actually didn't try the y ~ poly(x,2) formula; I generated the squared and constant terms myself and just ran an OLS. That's because the following does not work:
result=smf.ols('y ~ poly(x,2)', df).fit()
xp=np.linspace(0, 30, 100) # or whatever over the range of datapred=result.get_prediction(exog=xp,weights=1)
which throws
/usr/local/lib/python2.7/dist-packages/patsy/eval.pyc in eval(self, expr, source_name, inner_namespace)
164 code = compile(expr, source_name, "eval", self.flags, False)
165 return eval(code, {}, VarLookupDict([inner_namespace]
--> 166 + self._namespaces))
167
168 @classmethod
<string> in <module>()
NameError: name 'poly' is not defined
I imagine transforming exog for a quadratic regression would require a bit more work than what is currently implemented.
I'm not sure about the 'poly' not defined, but patsy won't understand exog= a_numpy:array, patsy needs to have a variable name to associate with the variables in the formula
My guess is that this should be a dict or dataframe, e.g. pred = result.get_prediction(exog={'x': xp}, weight=1) or something like this.
Also, IIRC, poly in patsy is a categorical trend encoding, not a polynomial of a continuous variable.
>>> from numpy import exp
>>> result = smf.ols('y ~ exp(x1) + x2', df).fit()
>>> print(result.get_prediction(df, weights=1).summary_frame())
If you want a plain polynomial (that doesn't depend on a data specific state), then you can use a user defined transform. Or, I guess using numpy.polynomial vander functions should work.
BTW: patsy has built-in splines that you could use for a smooth feature.
(penalized splines and GAM will be in statsmodels 0.8, but maybe without full patsy integration in the first version.)
Activity
jason-curtis commentedon Apr 8, 2014
This is blocking some work I'm doing - it'd be great to have easy access to CIs on predicted data but I can't get wls_prediction_std's exog parameter to work.
josef-pkt commentedon Apr 9, 2014
Do you want predicted new observation or predicted mean, X beta, for a new observation?
to get formula support
The easiest should be to go through t_test which already has wrapper for creating the exog for predict, and the standard errors for the mean.
For the standard errors for a new observation we still need to add the standard error of the residual as in wls_prediction_std.
josef-pkt commentedon Apr 9, 2014
BUG, BUG independent of formula or pandas
I thought this is a enhancement request, but there is a bug in the weight handling.
I don't know why OLS defines weights now,
or which refactoring caused this, or if the bug was there all along.
If weights is not set in argument, then it uses the full length weights, which has now also for OLS the same length as the original data, I think it was a scalar 1 before.
after WLS, the default was also wrong if exog was defined in argument, but not weights.
josef-pkt commentedon Apr 9, 2014
besides the bug for arrays, there is still the last part missing which is the enhancement to support formulas
BUG: fix weight handling, fails in some cases, see statsmodels#987
josef-pkt commentedon Apr 9, 2014
@thatneat
You can either explicitly specify weights as a work-around,
weights=1.should do it, orPR #1582 adjusts the weight handling in
wls_prediction_std.(I might not finish that until after pycon.)
jason-curtis commentedon Apr 9, 2014
Thanks for your quick response and work. I made the classic mistake of making a vague comment on a bug report that was already lacking specifics. Allow me to be more specific now.
I am looking for the interval on a predicted new observation, but I am receiving the "wrong shape of exog" ValueError.
Demo: http://nbviewer.ipython.org/gist/thatneat/10286720 (updated with code that more specifically describes my use case)
I will take a look at t_test and see if I can grok the residual standard error code enough to get prediction intervals without using wls_prediction_std.
jason-curtis commentedon Apr 9, 2014
I added a workaround to the notebook above - I lifted the code that wraps model.predict() in Results.predict() to transform my exog to a form that wls_prediction_std can accept.
I'm not particularly happy with that workaround, think I might be close to a better solution
jason-curtis commentedon Apr 9, 2014
Updated the notebook once more with some suggested changes to wls_prediction_std() that would
It still requires factoring out the wrapper code, which I called transform_exog_to_model().
Side note - there was some suspicious workaround stuff in wls_prediction_std:
It seems wiser to just use Result.predict() instead:
josef-pkt commentedon Apr 9, 2014
Your solution should work, but two things
Using Result.predict will do the formula to exog conversion twice since we need both predicted and exog
Calling result predict from the outside will return the wrapped predicted, if we have the pandas wrapper for predict. This might mess up the calculations, but in this case it might be ok (there is just one addition )
jason-curtis commentedon Apr 9, 2014
Good points.
If we move the transformation earlier in wls_prediction_std, we could call
Result.predict() with transform=False and avoid redoing some of the
transformation. It just seems odd to me that the current code is
bypassing/recreating some of the work that Result.predict() does, but it
might be easier to leave it that way.
Thanks so much for your help; I leave the follow-through to the correct
solution in your hands!
On Wed, Apr 9, 2014 at 10:24 AM, Josef Perktold [email protected]:
josef-pkt commentedon Apr 9, 2014
If you look at the age of the function, you'll see that it still predates pandas and formula integration.
Feedback will be welcome when we add the proper results method with the predict extras. It will happen really soon now. :)
jseabold commentedon Apr 9, 2014
I haven't followed this closely, but an API suggestion based off what we have in ARIMA where we have a forecast vs. predict.
I was thinking in linear regression we continue to follow the
get_pattern where it returns some kind of results object. Seeget_influence. Here we would have get_predict, which would return a class that haspredictionorfittedvaluesattached,prediction_std_err, andconf_int. Probably also a plotting utility function. This way you only go through the transformations once,wls_prediction_stdstays a separate function and only expects transformed data, and it's all done in one method.All wrapping should stay at the model level IMO.
6 remaining items
josef-pkt commentedon Aug 20, 2015
Ok, I found the long SUMM issue, #2150,
(FYI: That's just a collection of issues and a table of content and most of it is not relevant here.)
mizzao commentedon Aug 21, 2015
@josef-pkt
get_predictioncauses the following error, how did you run the example at http://stackoverflow.com/a/32103366/586086 to work?So it seems like
weightsis actually not optional right now. If I set weights to an array of ones though, looks great! (i.e. for a quadratic regression)josef-pkt commentedon Aug 21, 2015
here is my script that I used for stackoverflow which works for me.
about the comment in http://stackoverflow.com/questions/17559408/confidence-and-prediction-intervals-with-statsmodels
There might be an issue how to get weights in WLS for out of sample prediction intervals. If there is heteroscedasticity as in your plot, we would need the corresponding weights for new observations. By default we would use weights = 1. The latter could be missing if you get an exception with it.
mizzao commentedon Aug 21, 2015
Yeah, right now if you specify
exog, you need to specifyweightsas well, that might be fine because usually you'd want weights anyway like in the scenario you described. In this case I just wanted the CI of the regression line itself so I just set weights = 1 for a range of values generated bynp.linspace.josef-pkt commentedon Aug 21, 2015
@mizzao Thanks, missing defaults weights=1 is a bug.
Does it work for the transformation examples like in your initial question?
mizzao commentedon Aug 21, 2015
I actually didn't try the
y ~ poly(x,2)formula; I generated the squared and constant terms myself and just ran an OLS. That's because the following does not work:which throws
I imagine transforming
exogfor a quadratic regression would require a bit more work than what is currently implemented.josef-pkt commentedon Aug 21, 2015
I'm not sure about the 'poly' not defined, but patsy won't understand
exog= a_numpy:array, patsy needs to have a variable name to associate with the variables in the formulaMy guess is that this should be a dict or dataframe, e.g.
pred = result.get_prediction(exog={'x': xp}, weight=1)or something like this.Also, IIRC, poly in patsy is a categorical trend encoding, not a polynomial of a continuous variable.
mizzao commentedon Aug 21, 2015
So I'm going by the
stat_smoothfunction in ggplot, which lets you do fit a quadratic regression to a scatter plot, with confidence intervals, likeIt does seem like patsy doesn't support doing this automatically yet, e.g. pydata/patsy#20.
I understand the need to specify
exog={'x': xp}but this arises before that.josef-pkt commentedon Aug 21, 2015
Since I have the stackoverflow example still open
this works correctly, as expected in the example.
If you want a plain polynomial (that doesn't depend on a data specific state), then you can use a user defined transform. Or, I guess using numpy.polynomial vander functions should work.
For example, this doesn't raise an exception:
but I didn't verify if the numbers are correct.
josef-pkt commentedon Aug 21, 2015
BTW: patsy has built-in splines that you could use for a
smoothfeature.(penalized splines and GAM will be in statsmodels 0.8, but maybe without full patsy integration in the first version.)
tbarrios2 commentedon Jan 7, 2016
@mizzao Can you share the code you used to get that plot from Aug 21st?
Thanks!
josef-pkt commentedon Jan 30, 2023
closing,
old issue, and we have
get_predictionin most models