user3013706 user3013706 - 1 year ago 204
Python Question

Save python random forest model to file

In R, after running "random forest" model, I can use

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=, Predy)

I tried to return
, 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 Source
import cPickle

rf = RandomForestRegresor(), 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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download