2
$\begingroup$

I want to make a Random forest that aggregates by taking the maximum over the decision trees instead of taking the average.

By default Sklearn is taking the average, and I couldn't find how to change this to taking the maximum.

Does anyone know how to do this?

$\endgroup$
1
  • $\begingroup$ Just out of curiosity, why do you want to do this? What do you hope to achieve? $\endgroup$ Commented May 25, 2021 at 8:20

1 Answer 1

3
$\begingroup$

Yes, you can do it like this

import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor as rf

# generate some data
x = pd.DataFrame({'a' : [1,2,4], 'b' : [1,3,6]})
y = np.array([1,2,3])

# fit random forest
clf = rf(n_estimators = 10)
clf.fit(x, y)

# get predictions from each tree
estimates = {}
for e in clf.estimators_:
    estimates[e] = e.predict(x)

# take treewise maximum
pd.DataFrame(estimates).T.max()

Here is the same thing written as a function. This is probably not a very efficient way of doing it though.

def predict_using_max(clf, x):
    
    # clf  : fitted random forest object
    # x    : data frame to be predicted
    
    estimates = {}
    for e in clf.estimators_:
        estimates[e] = e.predict(x)
        
    return pd.DataFrame(estimates).T.max()

Edit: to make this into a class and override the predict method, you can do this (now in a classification context):

from sklearn.ensemble import RandomForestClassifier

class MyRandomForest(RandomForestClassifier):
    
    def predict(self, x):
        estimates = {}
        for e in self.estimators_:
            estimates[e] = e.predict_proba(x)[:, 1]

        return pd.DataFrame(estimates).T.max()

For example:

x = pd.DataFrame({'a' :  np.random.normal(0, 1, 20), 'b' : np.random.normal(0, 1, 20)})
y = np.array(np.random.choice([0,1], 20, replace=True))

clf = MyRandomForest(n_estimators = 10, max_depth=3)
clf.fit(x, y)

clf.predict(x)
$\endgroup$
2
  • $\begingroup$ This is a nice start. For a cleaner implementation would I need to derive from the RandomForestClassifier base class? In the spirit of: stackoverflow.com/questions/56907066/… $\endgroup$ Commented May 25, 2021 at 12:10
  • $\begingroup$ (Because I want to get this functionality simply by calling the predict function. Also I would like to take the maximum over the probabilities, but that can be done by changing predict to predict proba.) For development I'm using the explainer dashboard, and I think that one needs to have the predict method implemented. $\endgroup$ Commented May 25, 2021 at 12:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.