Save python random forest model to file

user3013706 picture user3013706 · Dec 18, 2013 · Viewed 22.1k times · Source

In R, after running "random forest" model, I can use save.image("***.RData") to store the model. Afterwards, I can just load the model to do predictions directly.

Can you do a similar thing in python? I separate the Model and Prediction into two files. And in Model file:

rf= RandomForestRegressor(n_estimators=250, max_features=9,compute_importances=True)
fit= rf.fit(Predx, Predy)

I tried to return rf or fit, but still can't load the model in the prediction file.

Can you separate the model and prediction using the sklearn random forest package?

Answer

Jake Burkhead picture Jake Burkhead · Dec 18, 2013
...
import cPickle

rf = RandomForestRegresor()
rf.fit(X, y)

with open('path/to/file', 'wb') as f:
    cPickle.dump(rf, f)


# in your prediction file                                                                                                                                                                                                           

with open('path/to/file', 'rb') as f:
    rf = cPickle.load(f)


preds = rf.predict(new_X)