Skip to content

FAQ: How to save only the model's prediction part? #3563

Open

Description

@youjin2

Hi.
I'm currently trying to fit the OLS and using it for prediction.

import statsmodels.api as sma
ols = sma.OLS(myformula, mydata).fit()
with open('ols_result', 'wb') as f:
pickle.dump(ols ,f)

However, my data set is about 5GB and OLSResults takes about 6GB memory.
It's the problematic part because i want to share the model.predict() with other environments, but moving and loading 6GB file takes too much time.

with open('ols_result', 'wb') as f:
pickle.dump(ols.predict ,f)

This code does not solved my situation. (it also takes 6GB)

Is there any way to save only the predicting part of the model?

edit (Josef)

most of the discussion below (comments by me) miss the point of this example here which is that formula information cannot be pickled, and we need to recreate it as a hack.
as pointed out by by @bsaunders23 with link to #4174

Activity

  1. josef-pkt commented on Mar 20, 2017

    @josef-pkt
    Member
  2. josef-pkt commented on Mar 20, 2017

    @josef-pkt
    Member

    In the linear model case you could also just pickle params and use exog.dot(params)

    Also, there are pickling problems when using the formula interface.

  3. josef-pkt commented on Mar 20, 2017

    @josef-pkt
    Member

    I reopened and will make it into a FAQ issue, I'm not sure this is well enough documented

    original issue was #176
    For prediction we don't need to keep much information, but we don't have standalone predict functions. In cases like GLM, prediction needs additional information to just params.
    All main classes are unit tested for this, but not in tsa which is more complicated because in needs past observations. https://github.com/statsmodels/statsmodels/blob/master/statsmodels/base/tests/test_shrink_pickle.py

    specific about cache: many results are computed in a lazy way, i.e. computed only on demand and then stored in an internal cache. Only arrays of length nobs are deleted by remove_data. Smaller arrays and results are kept in cache if they are in there. In the unit tests I call summary before remove data, so all the interesting results are created.
    In either case cov_params should be kept (AFAIR), so prediction confidence intervals could still be computed after calling remove_data. However, AFAIR there are no unit tests for that case.

  4. youjin2 commented on Mar 20, 2017

    @youjin2
    Author

    Thanks for your response.
    I tried to use the model.remove_data() method but it also takes 2.5G memory.
    Although it is relatively smaller than that of the original one, it also does not give a satisfactory result.

    If i use a scikit-learn LinearRegression() like below, it takes only 979Bites but since i'm going to use more advanced statistical models like glm for later, i wish there's another approach to save predicting results which takes up to 2~300MB

    lm = sklearn.linear_model.LinearRegression()
    lm.fit(train_X, train_Y)
    with open('sklm.pkl, 'wb') as f:
    pickle.dump(lm, f)

    Below is my source code for a temporary solution, but in glm cases i should make another generalized solution code which is somewhat a challenging part.

    class demo_ols(object):
    def __init__(self, beta, scaler=None):
    self.beta = beta
    self.scaler = scaler

    def predict(self, X):
    if self.scaler is not None:
    col_idx = np.array(['azimuth', 's_altitude', 'temp', 'irradiation', 'humidity'], dtype=object)
    X = X[col_idx]
    scaleX = self.scaler.transform(X)
    X = pd.DataFrame(scaleX, index=X.index, columns=X.columns)
    else:
    print "Note: X is not standardized (use pre-defiened StandardScaler())"
    beta = self.beta
    beta0 = beta[beta.index == 'Intercept']
    beta1 = beta[beta.index != 'Intercept']
    beta1_name = pd.Series(beta1.index)
    beta1_name_split = beta1_name.apply(lambda x: x.split(':'))
    beta1_split_len = beta1_name_split.apply(lambda x: len(x))
    Norder = sorted(beta1_split_len.unique())

    pred = float(beta0)

    for order in Norder:
    idx_temp_order = beta1_split_len[beta1_split_len == order].index
    if order == 1:
    order1_beta = beta1[idx_temp_order]
    order1_pred = X[order1_beta.index] * order1_beta
    pred += order1_pred.sum(axis=1)
    else:
    order_up2_pred = 0
    for idx in idx_temp_order:
    temp_up2_beta = beta1[idx]
    order_up2_pred += X[beta1_name_split[idx]].prod(axis=1) * beta1[idx]
    pred += order_up2_pred
    return pred

  5. smshuai commented on Jul 26, 2017

    @smshuai

    Hi when I save GLM results with remove_data=TRUE, I always get a warning like statsmodels/tools/decorators.py:117: CacheWriteWarning: The attribute 'mu' cannot be overwritten warnings.warn(errmsg, CacheWriteWarning). I'm wondering is it safe to ignore it?

    Here is code to replicate this issue:

    # python 3.5
    # statsmodels.__version__ '0.8.0'
    import statsmodels.api as sm
    data = sm.datasets.star98.load()
    data.exog = sm.add_constant(data.exog, prepend=False)
    glm_binom = sm.GLM(data.endog, data.exog, family=sm.families.Binomial())
    res = glm_binom.fit()
    res.save('./test.pkl', remove_data=True)
    /anaconda3/lib/python3.5/site-packages/statsmodels/tools/decorators.py:117: CacheWriteWarning: The attribute 'mu' cannot be overwritten
      warnings.warn(errmsg, CacheWriteWarning)
  6. josef-pkt commented on Jul 26, 2017

    @josef-pkt
    Member

    @smshuai The only problem could be that mu is not removed and the pickle is larger than with full removal.

    However, if mu is not removed, then this would be a bug. AFAIR it should be removed like other data sized arrays.

  7. josef-pkt commented on Jul 26, 2017

    @josef-pkt
    Member

    mu is twice on the removal list, the second is for the attribute which is incorrect

    That means the warning is just noise, and the extra command should be try .. except protected anyway.
    mu is removed from cache, which should be verified by the unit tests (AFAIR there is not enough slack in the memory size condition of the pickle test to have one extra array still attached.)

            self.data_in_cache = getattr(self, 'data_in_cache', [])
            self.data_in_cache.extend(['null', 'mu'])
            self._data_attr_model = getattr(self, '_data_attr_model', [])
            self._data_attr_model.append('mu')
    
  8. smshuai commented on Jul 26, 2017

    @smshuai

    Thanks for your reply. I will ignore the warning then!

  9. josef-pkt commented on Jul 27, 2017

    @josef-pkt
    Member

    There is still something strange (that I don't understand)
    mu is attached as model attribute in fit_irls, but not in _fit_gradient. The above line self._data_attr_model.append('mu') is then correct.

    mu is referenced through fittedvalues, so maybe the problem is that the cached attribute is deleted twice. But that also looks strange/incorrect because fittedvalues is also cached

        @cache_readonly
        def fittedvalues(self):
            return self.mu
    
        @cache_readonly
        def mu(self):
            return self.model.predict(self.params)
    
  10. josef-pkt commented on Jul 27, 2017

    @josef-pkt
    Member

    I don't understand anymore what the wipe function in base remove_data does. It might attempt to remove an result attribute if it has the same name as the model attribute

    self._data_attr_model.append('mu') should be redundant because it is also in the GLM model class:

    self._data_attr.extend(['weights', 'pinv_wexog', 'mu', 'freq_weights',
                                    '_offset_exposure', 'n_trials'])
    

    commenting out self._data_attr_model.append('mu') does not change anything. The attribute and cached attributes are set to None, and the warning still shows up

  11. josef-pkt commented on Jul 27, 2017

    @josef-pkt
    Member

    I'm giving up on this for now, new issue #3840, currently this is just one extra invalid warning

  12. bsaunders23 commented on Dec 21, 2017

    @bsaunders23

    FYI solve on @youjin2 initial question #4174

  13. changed the title [-]How to save only the model's prediction part?[/-] [+]FAQ: How to save only the model's prediction part?[/+] on Aug 28, 2021
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

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions