Skip to content

Trees with MAE criterion are slow to train #9626

Closed

Description

@jiangfeng

Description

when I use 'mae' criterion for the model extratreesregressor, training for a long time, it's seems lead to an endless training. there have no problem for mse
I find not only me hava this problem. I hava tried two version (0.18 and 0.19.X) , but no used .

https://www.kaggle.com/c/allstate-claims-severity/discussion/24293

Steps/Code to Reproduce

from sklearn.ensemble import ExtraTreesRegressor
rfr = ExtraTreesRegressor(n_estimators=100,
max_features=0.8,  
criterion='mae', 
max_depth=6, 
min_samples_leaf=200,
 n_jobs=-1,
 random_state=17, 
verbose=0)
 mod = rfr.fit(train[distilled_features], train['y'])

Expected Results

can normal training in my model when mae used

Actual Results

aways traing in fit step

Versions

Darwin-16.1.0-x86_64-i386-64bit
Python 3.6.1 |Anaconda 4.4.0 (x86_64)| (default, May 11 2017, 13:04:09)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)]
NumPy 1.12.1
SciPy 0.19.0
Scikit-Learn 0.19.X

Activity

  1. changed the title [-]model extratreesregressor when criterion use "MAE" lead to an endless training[/-] [+]model ExtraTreesRegressor when criterion use "MAE" lead to an endless training[/+] on Aug 25, 2017
  2. changed the title [-]model ExtraTreesRegressor when criterion use "MAE" lead to an endless training[/-] [+]Trees with MAE criterion are slow to train[/+] on Aug 27, 2017
  3. jnothman commented on Aug 27, 2017

    @jnothman
    Member

    Thanks. See also #9553 (comment) and below.

  4. jiangfeng commented on Aug 30, 2017

    @jiangfeng
    Author

    hello @jnothman , when i debug the code in fit function , ExtraTreesRegressor model use RandomSplitter (tree/_splitter.pyx) , self.criterion.update(current.pos) cost 10 minutes every loop.
    I hava run 2 days but the loop keep running

    my training sets contains 806298 samples and 137 features

  5. jnothman commented on Aug 30, 2017

    @jnothman
    Member

    You might be interested in using the random sub-sampling from #9645. For 800000 samples and 137 features, there's a lot of calculation to do at each split.

    Perhaps MAE could perhaps be made faster (needs investigation), as per @mcgibbon's comment:

    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.

  6. mcgibbon commented on Aug 30, 2017

    @mcgibbon

    I think with 800k samples, you will really want to optimize the MAE so it scales better (as I said in that comment), unless you can get away with subsampling a few percent of your training data. to get some sense of how long it will take, run it with a bunch of different small sample sizes (like, 500, 1000, 2000, 4k, 8k, 16k, 32k... until the run takes over a minute) and then plot the run time versus the sample size. I personally had 2 million samples splitting on 5 features, and I was doubting the code would finish in my lifetime based on what I saw for scaling.

    Even if it is re-written, the MAE would still be much slower than MSE, since it would scale with N*log(N) whereas MSE seems to scale with N.

  7. jnothman commented on Aug 30, 2017

    @jnothman
    Member
  8. jnothman commented on Aug 30, 2017

    @jnothman
    Member

    But the point of #9645 is that the ensemble will sub-sample for you, differently for each tree.

  9. SmokinCaterpillar commented on Nov 12, 2017

    @SmokinCaterpillar

    Is there any update on this? Running a multi-output Random Forest Regresser with the mae criterion and a couple of million samples takes days in comparison to minutes for mse.

  10. jmschrei commented on Nov 12, 2017

    @jmschrei
    Member

    This was an issue that @nelson-liu and I were working on as a part of his GSoC 2016. The gist comes down to it being more difficult to compute running medians versus running means. I think we figured out a possible solution, but ran out of summer before getting it done. If someone would like to take up the issue, I'd be more than happy to discuss the idea with them.

  11. SmokinCaterpillar commented on Nov 13, 2017

    @SmokinCaterpillar

    What was your idea?

    I guess, theoretically, it boils down to computing the exact median which costs O(n log n), right? How about an approximation of the median in linear time, like the Median of Medians?

    Especially when it comes to random forests, the error introduced by the median approximation can be neglected or rather seen as another source of randomness.

  12. JohnStott commented on Jan 28, 2018

    @JohnStott
    Contributor

    It's a shame this takes such a long time, but understandable with having to takes medians etc. What I have found frustrating is that the time taken to train is not linear. For example, I have a sample of data that takes 50 minutes to train 10 trees, however, if I run the same test for 20 trees, it takes 160 minutes (not the expected 100 minutes). This is on a system with 40 cores using "jobs=36" (also uses around 5% of my total system memory), so plenty of room to run a tree per core. Under the bonnet, if my understanding is correct, each tree is independent so I'd be better just running small numbers of trees and joining them up myself! Anyone know why the job times seem exponential to the number of trees used in the model (not linear)?

  13. jnothman commented on Jan 28, 2018

    @jnothman
    Member
  14. mcgibbon commented on Jan 28, 2018

    @mcgibbon

    @SmokinCaterpillar I attempted to implement this, but my resulting solution failed unit tests (it was doing one calculation or another incorrectly). I was unable to configure any kind of Cython debugging to work with Anaconda, and I figured for other reasons that this probably won't impact my research, so in the end I gave up.

    The real issue isn't in computing running medians, but in computing the mean absolute error in constant time at each step (you can update the MSE in constant time). WeightedMedianCalculator needs to be modified to update the median in constant time, and also to keep running track of the MAE and also update that in constant time.

    You can compute running medians by keeping the entries sorted, and keeping track of the middle entry (which is necessary because it's a weighted median). When an entry gets pushed or popped, you need to update the position of the middle entry, if necessary, and update the MAE if the position is updated. You can update the weighted MAE based on the sign of the change in the MAE. If it decreases, the absolute error is decreased by that amount for all lower samples, and increased by that amount for all higher samples. You also add in the contribution to the MAE based on the absolute error of the new sample.

    After that, MAE.node_impurity and MAE.children_impurity need to be updated to use the new WeightedMedianCalculator.get_mae() function that you will write.

    At least, all that is the solution I came up with.

    I'm very surprised about the tree number scaling. You should try with a few more numbers of trees (between 1 and 20) and plot the scaling in log space. The code really does train the trees independently, and there are other reasons you might expect the scaling to be nonlinear (though probably not exponential).

  15. JohnStott commented on Jan 29, 2018

    @JohnStott
    Contributor

    Thanks @mcgibbon for the ideas, I don't suppose you still have your source code, or am I able to view it in github somewhere? I have some time this week so could try and look into this.

    I have created a simple script and it doesn't appear exponential like I first mentioned. However, there does appear to be quite a bit of "slippage" in sharing the work amongst the cores, much more than I would have anticipated. I will run the script soon under more ideal conditions (i.e., when it can't be affected by external processes) and I'll post it here when done, with my results.

  16. 50 remaining items

  17. ogrisel commented on Nov 15, 2023

    @ogrisel
    Member

    Here is the left-heavy view of speedscope:

    image

    Note that libc's __mem* operations do not show up under the _push methods. So maybe memory realloc is not the only culprit here.

  18. jjerphan commented on Nov 15, 2023

    @jjerphan
    Member

    Note: for py-spy output, if you use -f speedscope, please use a .json filename, otherwise it's quite confusing (even for my firefox).

    Fixed.

  19. jjerphan commented on Nov 18, 2023

    @jjerphan
    Member

    Another option is to use skip lists to improve the average-case complexity of WeightedPQueue.{push,remove} from $\mathcal{O}(n)$ to $\mathcal{O}(\log n)$.

  20. AhmedThahir commented on Nov 5, 2024

    @AhmedThahir

    Any updates on this?

  21. jjerphan commented on Nov 21, 2024

    @jjerphan
    Member

    No update, someone needs to implement the solution. 🙂

  22. cakedev0 commented on Sep 2, 2025

    @cakedev0
    Member

    I'd be happy to try implementing the solution.

    Looking at the code, I see that the implementation of WeightedMedianCalculator isn't great in term of performance: O(n) at each update, because WeightedPQueue.{push,remove} is in O(n) as @jjerphan mentioned. As it's updated O(n) times, the overall time complexity is O(n^2), which can be easily verified experimentally by plotting run time vs data size (See the plot in my notebook here).

    I propose to rewrite the implementation of WeightedMedianCalculator of by adpating the well-known two-heap solution (see for instance this leetcode solution) for weighted data. This would make each update O(log n) (expect in some very patological cases that you won't fall into unless you're actively trying to).

    I think this won't be enough to make the code as fast as it should be, because I think children_impurity of the class MAE(RegressionCriterion) is in O(n) and is called O(n) times, so this part is O(n^2) too. But I think the O(n) loop inside this function can easily be replaced by a O(1) calculation using some precomptued quantities. I'll dive into that later.

    Before posting this comment & diving into the complex sckit-learn code, I did a "stand-alone" implementation of those ideas using python/numba, see this repo. Performance & tests are good. So at the end of the day, I should be able to get it working right & fast in sklearn too 😄

  23. AhmedThahir commented on Sep 2, 2025

    @AhmedThahir

    The idea looks great! Looking forward to this :)

    Also, would it be possible to show the plot of how your implementation and the existing implementation compare?
    Your notebook only shows the existing implementation.

  24. cakedev0 commented on Sep 2, 2025

    @cakedev0
    Member

    I already have a few time measurements in my notebook, I don't really see the point of adding this plot. For instance, on my sample of 50k random data points, my implem runs in 27ms while sklearn's one runs in ~9s. O(n log n) vs O(n^2) ...

    And ~1s for 1M data points. Should be fast enough for most real-world use cases of such algorithms.

    Note: this is for just one split, with only two features. In realcase scenarios with many splits and many features, you'll be x10 / x100 slower (both for sklearn and my code).

  25. mcgibbon commented on Sep 3, 2025

    @mcgibbon

    It has been 8 years since I originally reported this as a grad student, excited to see it might get fixed! People come by these issues often who have newly run into it and I imagine there are many more who never comment.

  26. cakedev0 commented on Sep 3, 2025

    @cakedev0
    Member

    It was quite an adventure because the code is not the easier to edit (when some self.array is modified inplace by other classes in between calls of some self.method(...), finding the bug is hard ^^). Plus it was my first time doing Cython.

    But I think I'm good now: tests are green 🟢, perf is great 🚀 (~1s for one split on 1M data points and two features). There is just one thing I'll need to discuss with reviewers about memory footprint.

    My repo/branch is here, I'll open the PR soon: https://github.com/cakedev0/scikit-learn/tree/mae-split-optim

  27. cakedev0 commented on Sep 3, 2025

    @cakedev0
    Member

    @mcgibbon

    It has been 8 years since I originally reported this as a grad student

    I first came across this issue 5 years ago. I had the idea of the solution, but I was busy and the existing code was fairly scary, so I never took the time to write the PR 😅

    Btw, 8 years ago you said:

    Even if it is re-written, the MAE would still be much slower than MSE, since it would scale with N*log(N) whereas MSE seems to scale with N.

    Actually I think that splitting always requires sorting by each feature, so MSE is also N*log(N). After my changes, on 10M points, 2 features, max_depth=1, MSE takes 4s, MAE takes 17s so really not too far 😁

  28. yupbank commented on Nov 12, 2025

    @yupbank
    Contributor
  29. cakedev0 commented on Nov 13, 2025

    @cakedev0
    Member

    That's a really cool paper, it solves a much harder problem than continuous MAE split!

    For now, there is no support for categorical splits in sklearn's decision trees, but I (and others) have started working on it. And I was wondering how to support MAE, it felt super hard. I came to the conclusion the paper proved "This paper demonstrates that unsupervised numerical encoding methods are not viable for the MAE criteria." and it discouraged me to search further.

    I hope we'll implement this paper one day, once categorical splits are supported for "simple" cases.

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