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
FAQ: How to save only the model's prediction part? #3563
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
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.
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.
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
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?
/anaconda3/lib/python3.5/site-packages/statsmodels/tools/decorators.py:117: CacheWriteWarning: The attribute 'mu' cannot be overwritten
warnings.warn(errmsg, CacheWriteWarning)
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.)
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
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:
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
Activity
josef-pkt commentedon Mar 20, 2017
Yes, we added an option to drop all full length (nobs) arrays
http://www.statsmodels.org/devel/generated/statsmodels.regression.linear_model.RegressionResults.remove_data.html
the results class has the corresponding save and load methods for pickling
josef-pkt commentedon Mar 20, 2017
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.
josef-pkt commentedon Mar 20, 2017
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 callsummarybefore 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.youjin2 commentedon Mar 20, 2017
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 = betaself.scaler = scalerdef 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.betabeta0 = 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].indexif order == 1:order1_beta = beta1[idx_temp_order]order1_pred = X[order1_beta.index] * order1_betapred += order1_pred.sum(axis=1)else:order_up2_pred = 0for 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_predreturn predsmshuai commentedon Jul 26, 2017
Hi when I save GLM results with
remove_data=TRUE, I always get a warning likestatsmodels/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:
/anaconda3/lib/python3.5/site-packages/statsmodels/tools/decorators.py:117: CacheWriteWarning: The attribute 'mu' cannot be overwritten warnings.warn(errmsg, CacheWriteWarning)josef-pkt commentedon Jul 26, 2017
@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.
josef-pkt commentedon Jul 26, 2017
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.
muis 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.)smshuai commentedon Jul 26, 2017
Thanks for your reply. I will ignore the warning then!
josef-pkt commentedon Jul 27, 2017
There is still something strange (that I don't understand)
muis attached as model attribute in fit_irls, but not in _fit_gradient. The above lineself._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
josef-pkt commentedon Jul 27, 2017
I don't understand anymore what the
wipefunction in base remove_data does. It might attempt to remove an result attribute if it has the same name as the model attributeself._data_attr_model.append('mu')should be redundant because it is also in the GLM model class: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 upjosef-pkt commentedon Jul 27, 2017
I'm giving up on this for now, new issue #3840, currently this is just one extra invalid warning
bsaunders23 commentedon Dec 21, 2017
FYI solve on @youjin2 initial question #4174
[-]How to save only the model's prediction part?[/-][+]FAQ: How to save only the model's prediction part?[/+]