Skip to content

wls_prediction_std needs to be update to handle formula-like syntax #987

Closed

Description

@jseabold

From mailing list

import pandas as pd
import numpy as np
import statsmodels.formula.api as sm
from statsmodels.sandbox.regression.predstd import wls_prediction_std

d = pd.DataFrame({'x': np.random.randn(100) })
d['y'] = d.x + np.random.randn(100)
f = sm.ols('y~x', d).fit()
print f.predict({'x':0.5})
#  => array([ 0.46793312])
print np.shape(wls_prediction_std(f, [0, 0.5]))
#  => (3, 100)
np.shape(wls_prediction_std(f, {'x':0.5}))

Activity

  1. jason-curtis commented on Apr 8, 2014

    @jason-curtis

    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.

  2. josef-pkt commented on Apr 9, 2014

    @josef-pkt
    Member

    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.

  3. josef-pkt commented on Apr 9, 2014

    @josef-pkt
    Member

    BUG, BUG independent of formula or pandas

    >>> wls_prediction_std(f, [0, 0.5], weights=[1])
    (array([ 1.01056418]), array([-1.74095975]), array([ 2.26990368]))
    

    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.

  4. josef-pkt commented on Apr 9, 2014

    @josef-pkt
    Member

    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
    
  5. josef-pkt commented on Apr 9, 2014

    @josef-pkt
    Member

    @thatneat

    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.)

  6. jason-curtis commented on Apr 9, 2014

    @jason-curtis

    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.

  7. jason-curtis commented on Apr 9, 2014

    @jason-curtis

    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

  8. jason-curtis commented on Apr 9, 2014

    @jason-curtis

    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:

    predicted = res.predict(exog)
    
  9. josef-pkt commented on Apr 9, 2014

    @josef-pkt
    Member

    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 )

  10. jason-curtis commented on Apr 9, 2014

    @jason-curtis

    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]:

    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 )

    Reply to this email directly or view it on GitHubhttps://github.com//issues/987#issuecomment-39991704
    .

  11. josef-pkt commented on Apr 9, 2014

    @josef-pkt
    Member

    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. :)

  12. jseabold commented on Apr 9, 2014

    @jseabold
    MemberAuthor

    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.

    All wrapping should stay at the model level IMO.

  13. 6 remaining items

  14. josef-pkt commented on Aug 20, 2015

    @josef-pkt
    Member

    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.)

  15. mizzao commented on Aug 21, 2015

    @mizzao

    @josef-pkt get_prediction causes the following error, how did you run the example at http://stackoverflow.com/a/32103366/586086 to work?

    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)

    image

  16. josef-pkt commented on Aug 21, 2015

    @josef-pkt
    Member

    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.

    
    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())
    
  17. mizzao commented on Aug 21, 2015

    @mizzao

    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.

  18. josef-pkt commented on Aug 21, 2015

    @josef-pkt
    Member

    @mizzao Thanks, missing defaults weights=1 is a bug.
    Does it work for the transformation examples like in your initial question?

  19. mizzao commented on Aug 21, 2015

    @mizzao

    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 data
    pred = 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.

  20. josef-pkt commented on Aug 21, 2015

    @josef-pkt
    Member

    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.

  21. mizzao commented on Aug 21, 2015

    @mizzao

    So I'm going by the stat_smooth function in ggplot, which lets you do fit a quadratic regression to a scatter plot, with confidence intervals, like

    ggplot(data, aes(x=foo, y=bar)) + 
      geom_point() + 
      stat_smooth(method = "lm", formula = y ~ poly(x, 2), size = 1)

    It 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.

  22. josef-pkt commented on Aug 21, 2015

    @josef-pkt
    Member

    Since I have the stackoverflow example still open

    this works correctly, as expected in the example.

    >>> 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.

    For example, this doesn't raise an exception:

    result = smf.ols('y ~ np.vander(x1, 2) + x2', df).fit()
    print(result.get_prediction(df, weights=1).summary_frame())
    

    but I didn't verify if the numbers are correct.

  23. josef-pkt commented on Aug 21, 2015

    @josef-pkt
    Member

    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.)

  24. tbarrios2 commented on Jan 7, 2016

    @tbarrios2

    @mizzao Can you share the code you used to get that plot from Aug 21st?
    Thanks!

  25. josef-pkt commented on Jan 30, 2023

    @josef-pkt
    Member

    closing,
    old issue, and we have get_prediction in most models

  26. modified the milestones: 0.8, 0.14 on Apr 14, 2023
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

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions