Extracting the trees (predictor) from random forest classifier

Viewed 9636

I have a specific technical question about sklearn, random forest classifier.

After fitting the data with the ".fit(X,y)" method, is there a way to extract the actual trees from the estimator object, in some common format, so the ".predict(X)" method can be implemented outside python?

2 Answers

Yes there is and @ogrisel answer enabled me to implement the following snippet, which enables to use a (partially trained) random forest to predict the values. It saves a lot of time if you want to cross validate a random forest model over the number of trees:

rf_model = RandomForestRegressor()
rf_model.fit(x, y)

estimators = rf_model.estimators_

def predict(w, i):
    rf_model.estimators_ = estimators[0:i]
    return rf_model.predict(x)

I explained this in more details here : extract trees from a Random Forest

Related