Skip to content

Use median instead of mean when constructing RandomForestRegressor #9553

Closed

Description

@mcgibbon

Description

I am using a RandomForestRegressor for a task where it seems I would benefit from having the leaf node values defined by the median over its samples instead of the mean over its samples, due to the presence of outliers. This functionality currently isn't present in scikit-learn, and I would like to add it (either as a PR, or just locally on my machine).

If I'm going to do this, I could a pointer as to how to do it. Specifically I am having trouble finding the line of code where sklearn currently takes the mean over values in a leaf. I'm aware that it's somewhere within the code for a decision tree. If I found that, I can probably handle the rest.

Steps/Code to Reproduce

from sklearn.ensemble import RandomForestRegressor
help(RandomForestRegressor)

Desired API

I could just hack something in, if I'm doing it only for myself locally. If I'm going to write this as a change to the RFR API, then maybe something like:

from sklearn.ensemble import RandomForestRegressor
import numpy as np
random_forest = RandomForestRegressor(reduction_op=np.median)  # default np.mean

Versions

Linux-3.10.0-514.10.2.el7.x86_64-x86_64-with-centos-7.3.1611-Core
('Python', '2.7.13 | packaged by conda-forge | (default, May 2 2017, 12:48:11) \n[GCC 4.8.2 20140120 (Red Hat 4.8.2-15)]')
('NumPy', '1.12.1')
('SciPy', '0.19.0')
('Scikit-Learn', '0.18.1')

Activity

  1. mcgibbon commented on Aug 14, 2017

    @mcgibbon
    Author

    I hadn't thought about this, but I suppose I would also want to use the median when aggregating values from different trees.

  2. amueller commented on Aug 14, 2017

    @amueller
    Member

    Would you use the median across all leaves in all the trees or the median per tree and then the median of the medians? Do you have any literature or experiments on this? It makes intuitive sense, but it's not obvious that it'll actually help in practice.

  3. mcgibbon commented on Aug 14, 2017

    @mcgibbon
    Author

    When constructing the leaf I'd take the median among the samples given to that leaf, and when getting the value for the forest I'd take the median of the medians. The (non-peer reviewed?) paper I found using this is here. For my particular problem zero is a special value that occurs often (I'm predicting statistical moments, and when variance is zero other outputs are also zero), and on top of that some of the variables I output are quite skewed with fat-tailed PDFs. It seems like this might help for my particular application. I'll leave it to you to think about whether it makes sense to put in sklearn.

  4. amueller commented on Aug 14, 2017

    @amueller
    Member

    Thanks for the reference :) I'm no expert in regression, I'll let the tree builders weigh in...

  5. mcgibbon commented on Aug 14, 2017

    @mcgibbon
    Author

    Perhaps a better reference is Robustness of random forests for regression.

  6. mcgibbon commented on Aug 14, 2017

    @mcgibbon
    Author

    On the question of how to do this, since no matter what I have to implement this for myself... right now I'm confused by why the tree builders in tree/_tree.py seem to have no code in them. If anyone knows the lines where means are taken (when building a tree and when aggregating in a forest) it would really help me out.

  7. amueller commented on Aug 14, 2017

    @amueller
    Member

    You probably also want to change the criterion, since using MSE for splitting seems a bit odd then? Not sure what the papers use. The criteria are here. The node_value method here is where the values are computed.

  8. mcgibbon commented on Aug 14, 2017

    @mcgibbon
    Author

    That's strange, reading this code it looks like the MAE criterion is actually what I am proposing. It uses medians for nodes, presuming that's what self.node_medians[k] = (<WeightedMedianCalculator> right_child[k]).get_median() would do.

    In other words, it looks like if you set "mae" as the criterion (assuming that makes this MAE object get used), it will take the median for each node. If that's true, the documentation should probably make this more clear.

  9. mcgibbon commented on Aug 14, 2017

    @mcgibbon
    Author

    Assuming I just need to use criterion='mae', I now have another issue which is that the MAE criterion does not scale the way MSE does. Is this a problem with the implementation, or an intrinsic limitation of using MAE and the median? Here I plot up to ~16k samples, but for my actual problem I have 2576460 samples and need to train more like a depth 16-20 tree than a depth 2 tree, so this is probably too slow for me to use.

    from sklearn.ensemble import RandomForestRegressor
    import numpy as np
    import time
    import matplotlib.pyplot as plt
    
    n_sample_list = [i * 1024 for i in (1, 2, 4, 8, 16)]
    time_list_mse = []
    time_list_mae = []
    
    for n_samples in n_sample_list:
        train_X = np.random.randn(n_samples, 3)
        train_y = np.random.randn(n_samples, 3)
    
        start = time.time()
        random_forest = RandomForestRegressor(
            n_estimators=16, max_features=1, max_depth=2, n_jobs=8, criterion='mse',)
        random_forest.fit(train_X, train_y)
        elapsed = time.time() - start
        print('Elapsed: {} seconds'.format(elapsed))
        time_list_mse.append(elapsed)
    
        start = time.time()
        random_forest = RandomForestRegressor(
            n_estimators=16, max_features=1, max_depth=2, n_jobs=8, criterion='mae')
        random_forest.fit(train_X, train_y)
        elapsed = time.time() - start
        print('Elapsed: {} seconds'.format(elapsed))
        time_list_mae.append(elapsed)
    
    plt.figure()
    plt.plot(n_sample_list, time_list_mse, label='mse')
    plt.plot(n_sample_list, time_list_mae, label='mae')
    plt.xlabel('n_samples')
    plt.ylabel('log(training time (seconds))')
    plt.yscale('log')
    plt.legend()
    plt.tight_layout()
    plt.show()

    mse_vs_mae_scaling

  10. mcgibbon commented on Aug 14, 2017

    @mcgibbon
    Author

    I should really plot out a little further to show the actual scaling for MSE:

    from sklearn.ensemble import RandomForestRegressor
    import numpy as np
    import time
    import matplotlib.pyplot as plt
    
    n_sample_list = [
        int(i * 1024) for i in (0.25, 0.5, 1, 2, 4, 8, 16, 32, 64,
                                128, 256, 512, 1024, 2048, 4096)]
    time_list_mse = []
    time_list_mae = []
    
    for n_samples in n_sample_list:
        train_X = np.random.randn(n_samples, 3)
        train_y = np.random.randn(n_samples, 3)
    
        start = time.time()
        random_forest = RandomForestRegressor(
            n_estimators=2, max_features=1, max_depth=2, n_jobs=1, criterion='mse',)
        random_forest.fit(train_X, train_y)
        elapsed = time.time() - start
        print('Elapsed: {} seconds'.format(elapsed))
        time_list_mse.append(elapsed)
    
        if n_samples <= 16*1024:
            start = time.time()
            random_forest = RandomForestRegressor(
                n_estimators=2, max_features=1, max_depth=2, n_jobs=1, criterion='mae')
            random_forest.fit(train_X, train_y)
            elapsed = time.time() - start
            print('Elapsed: {} seconds'.format(elapsed))
            time_list_mae.append(elapsed)
    
    plt.figure()
    plt.plot(n_sample_list, time_list_mse, label='mse')
    plt.plot(n_sample_list[:len(time_list_mae)], time_list_mae, label='mae')
    plt.xlabel('n_samples')
    plt.ylabel('log(training time (seconds))')
    plt.yscale('log')
    plt.xscale('log')
    plt.legend()
    plt.tight_layout()
    plt.show()

    mse_vs_mae_scaling_2

  11. mcgibbon commented on Aug 14, 2017

    @mcgibbon
    Author

    It looks like this is rooted in the fact that for MSE, the impurity is defined by

            impurity = self.sq_sum_total / self.weighted_n_node_samples
            for k in range(self.n_outputs):
                impurity -= (sum_total[k] / self.weighted_n_node_samples)**2.0

    and sum_total[k] is easy to update when changing the split. On the other hand, when using the median we use

           for k in range(self.n_outputs):
                for p in range(self.start, self.end):
                    i = samples[p]
                    y_ik = y[i * self.y_stride + k]
                    impurity += <double> fabs((<double> y_ik) - <double> self.node_medians[k])

    When an update happens we can (and do) incrementally update the median, assuming that's what happens when you call

                    for k in range(self.n_outputs):
                        y_ik = y[i * self.y_stride + k]
                        # remove y_ik and its weight w from left and add to right
                        (<WeightedMedianCalculator> left_child[k]).remove(y_ik, w)
                        (<WeightedMedianCalculator> right_child[k]).push(y_ik, w)

    But even then, the impurity gets entirely re-computed by iterating over the samples. Could we cache the result and incrementally update it when the median is updated? If you know you are increasing the median by some small delta, then you can compute the effect of this on the contributions from most of the samples immediately (in constant time).

    Let's say 0.60 of the samples were and still are less than the median, and 0.38 of the samples were and still are greater than the median. For the less than samples, the error has increased by delta, while for the greater than samples, it has decreased by delta. Then you know for those samples their contribution to the MAE has changed by 0.6 delta - 0.38 delta = (0.6 - 0.38) delta, and you only need to directly calculate the contribution from the remaining 2% of the samples that switched which side of the median they are on. Is my thinking correct here?

    This could possibly be implemented by adding a method to WeightedMedianCalculator that will keep track of the MAE as new values are added or removed.

  12. jnothman commented on Aug 15, 2017

    @jnothman
    Member
  13. amueller commented on Aug 15, 2017

    @amueller
    Member

    That's very possible (see, I have no idea about the tree details lol). @raghavrv @jnothman @jmschrei @glouppe can probably confirm. Lol the ensembles user guide doesn't mention the word "criterion". I feel we could improve that.

  14. amueller commented on Aug 15, 2017

    @amueller
    Member

    (whoops looked at an old version of the page when I commented)

  15. mcgibbon commented on Aug 15, 2017

    @mcgibbon
    Author

    I've written up a PR (#9556) that should implement the change I suggested, but the problem is the scaling is still the same. The run time is virtually identical to before the change. I'm using a develop install, was certain to re-run build_ext --inplace, and double-checked sklearn.__version__ was correct (that it was using the develop install).

  16. 1 remaining item

  17. jnothman commented on Aug 16, 2017

    @jnothman
    Member
  18. mcgibbon commented on Aug 16, 2017

    @mcgibbon
    Author

    The finding a median itself can be made average-case n using quickselect if the weights are all constant, though it may get more complicated for a weighted median. The median also should ideally be updated when adding new values in constant time, but I don't know if quickselect would do that. There may be some algorithm that does everything you'd need to make it n or nlogn, but I haven't been able to figure it out. I tried just implementing the median for node_value using quickselect while still using MSE for splits, but there was some bug in my code and it just hangs.

  19. jnothman commented on Aug 16, 2017

    @jnothman
    Member
  20. amueller commented on Aug 17, 2017

    @amueller
    Member

    I feel like we have a fast median computation in cython somewhere? Though maybe I was just thinking of the quicksort in _simultaneous_sort.

  21. mcgibbon commented on Aug 23, 2017

    @mcgibbon
    Author

    I thought I'd let you know this has taken a lower priority for me now, because I'm thinking now that the median won't actually help my research results. If someone else is interested they can tackle this, but I may make some progress eventually.

    The actual issues here are (different from the ones at the top of this issue):

    • Currently when "mae" is selected as a criterion, the RF will switch to using the median instead of the mean for computing node values, but this is not documented anywhere.
    • When "mae" is selected as a criterion, the performance is O(N^2), but this can probably be written to be O(N*log(N)). This would likely be done by making it so that when items are pushed onto the WeightedMedianCalculator (which keeps a sorted list of its values) the correct index is found in log(N) time, whereas currently this takes N time. It probably also requires the MAE being pre-computed and updated every time an item is pushed onto the WeightedMedianCalculator, since currently it is re-computed which requires N time. There may be other places that need to be changed, but these are the two main ones I've identified.
  22. jnothman commented on Aug 23, 2017

    @jnothman
    Member
  23. xoelop commented on Nov 21, 2018

    @xoelop

    Just for the record, I was curious wether taking the median of the results of each individual tree in a Random Forest would get us a better prediction than taking the mean. It kinda made sense that it woud be better, but it wasn't.

    Here are some results. A scatterplot comparing the predictions taken as the mean of each tree output, taken as the median and the actual value, VS the actual value. Note that this is an aggregation by date, the original data has ~44k datapoints.

    image

    And the R2 scores, for all the 44k points:
    image

    Very curiously, the R2 score is higher when we take the mean of the predictions, but when we take the log of the values, the R2 score is higher when we take the median of the predictions. Anybody knows why?

  24. mcgibbon commented on Nov 21, 2018

    @mcgibbon
    Author
  25. noklam commented on Apr 22, 2021

    @noklam

    This thread is awesome, thanks! The information is till relevant.

  26. glemaitre commented on May 17, 2024

    @glemaitre
    Member

    Closing in favor of #9626 that report the slowness of the MAE only.

  27. AhmedThahir commented on Mar 13, 2025

    @AhmedThahir

    Is there a way to aggregate the predictions of all the trees using median instead of mean (regardless of L1 or L2 objective).

    For eg:
    If the predictions of the trees are 5,5,5,5,10
    Then I want the output of the forest to be 5, not 6

  28. worthy7 commented on Apr 24, 2025

    @worthy7

    I am also interested in this.
    I am playing with sklearn for stock market predicting ™ and I realized that if the leaf node has 4 samples, 3 of which very close and one anomaly, I absolutely don't want it to give me a value of the mean which would be a completely unseen outcome. The median however at least would be the "most likely case".
    So I think it depends what you are trying to predict, what you define as error.

  29. AhmedThahir commented on Apr 24, 2025

    @AhmedThahir

    I am also interested in this. I am playing with sklearn for stock market predicting ™ and I realized that if the leaf node has 4 samples, 3 of which very close and one anomaly, I absolutely don't want it to give me a value of the mean which would be a completely unseen outcome. The median however at least would be the "most likely case". So I think it depends what you are trying to predict, what you define as error.

    I created an issue for this, check it out: #30986 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions