user3013706 user3013706 - 1 year ago 173
Python Question

Save python random forest model to file

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 Source
...
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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download