You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Use median instead of mean when constructing RandomForestRegressor #9553
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.
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:
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.
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.
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.
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.
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.
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.
When an update happens we can (and do) incrementally update the median, assuming that's what happens when you call
forkinrange(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.
On 15 Aug 2017 9:38 am, "Jeremy McGibbon" ***@***.***> wrote:
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.
—
You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
<#9553 (comment)>,
or mute the thread
<https://github.com/notifications/unsubscribe-auth/AAEz62rxMOrudyGRBvJk8ee7Y5vOMWu3ks5sYNpfgaJpZM4O2zOb>
.
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.
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).
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.
On 17 Aug 2017 8:53 am, "Jeremy McGibbon" ***@***.***> wrote:
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.
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
<#9553 (comment)>,
or mute the thread
<https://github.com/notifications/unsubscribe-auth/AAEz6_U2CWPjIP0K4LovSB4cSnQ-Tijfks5sY3LrgaJpZM4O2zOb>
.
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.
On 24 Aug 2017 8:52 am, "Jeremy McGibbon" ***@***.***> wrote:
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 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.
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
<#9553 (comment)>,
or mute the thread
<https://github.com/notifications/unsubscribe-auth/AAEz652Vn-6HUSp6XRfEsaQyqeM2xvYQks5sbK07gaJpZM4O2zOb>
.
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.
And the R2 scores, for all the 44k points:
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?
This is expected because when using the mean, the L2 norm is optimized
(mean squared error) whereas when using the median, the L1 norm (mean
absolute error) is optimized. When you take the log, R2 will depend on the
absolute error.
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 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.
Activity
mcgibbon commentedon Aug 14, 2017
I hadn't thought about this, but I suppose I would also want to use the median when aggregating values from different trees.
amueller commentedon Aug 14, 2017
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.
mcgibbon commentedon Aug 14, 2017
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.
amueller commentedon Aug 14, 2017
Thanks for the reference :) I'm no expert in regression, I'll let the tree builders weigh in...
mcgibbon commentedon Aug 14, 2017
Perhaps a better reference is Robustness of random forests for regression.
mcgibbon commentedon Aug 14, 2017
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.
amueller commentedon Aug 14, 2017
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_valuemethod here is where the values are computed.mcgibbon commentedon Aug 14, 2017
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.
mcgibbon commentedon Aug 14, 2017
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.
mcgibbon commentedon Aug 14, 2017
I should really plot out a little further to show the actual scaling for MSE:
mcgibbon commentedon Aug 14, 2017
It looks like this is rooted in the fact that for MSE, the impurity is defined by
and sum_total[k] is easy to update when changing the split. On the other hand, when using the median we use
When an update happens we can (and do) incrementally update the median, assuming that's what happens when you call
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.
jnothman commentedon Aug 15, 2017
amueller commentedon Aug 15, 2017
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.
amueller commentedon Aug 15, 2017
(whoops looked at an old version of the page when I commented)
mcgibbon commentedon Aug 15, 2017
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).1 remaining item
jnothman commentedon Aug 16, 2017
mcgibbon commentedon Aug 16, 2017
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.
jnothman commentedon Aug 16, 2017
amueller commentedon Aug 17, 2017
I feel like we have a fast median computation in cython somewhere? Though maybe I was just thinking of the quicksort in
_simultaneous_sort.mcgibbon commentedon Aug 23, 2017
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):
jnothman commentedon Aug 23, 2017
xoelop commentedon Nov 21, 2018
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.
And the R2 scores, for all the 44k points:

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?
mcgibbon commentedon Nov 21, 2018
noklam commentedon Apr 22, 2021
This thread is awesome, thanks! The information is till relevant.
glemaitre commentedon May 17, 2024
Closing in favor of #9626 that report the slowness of the MAE only.
AhmedThahir commentedon Mar 13, 2025
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
worthy7 commentedon Apr 24, 2025
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.
AhmedThahir commentedon Apr 24, 2025
I created an issue for this, check it out: #30986 (comment)