Repository navigation
[MRG] Normalization fix for gbm ensemble feature importances - #11176
Conversation
61a3945 to
954fedb
Compare
This makes a small change to the ``BaseDecisionTree`` and ``DecisionTreeRegressor``, adding a ``normalize_feature_importances`` ``kwarg`` that defaults to ``True`` (matching current behavior) but is set to ``False`` for GBMs. Tree-level feature importances are calculated as the proportional reduction of that tree's root node entropy (see ``_tree.pyx``) and ensemble-level importances are averaged across trees. Because the feature importances are (currently, by default) normalized and then averaged, feature importances from later stages are overweighted. GBMs now defer the normalization step until after the per-tree importances have been calculated (for the ``DecisionTreeRegressor`` used in ``ensemble.gradient_boosting.BaseGradientBoosting``). h/t to Joel Danke for spotting this and writing up the issue. Signed-off-by: Gil Forsyth <[email protected]>
jnothman
left a comment
There was a problem hiding this comment.
Thanks for the fully-fledged pr. You don't seem to test the effect of changing the new parameter as such
| sorted_idx = np.argsort(feature_importance) | ||
|
|
||
| feature_order = ['CHAS', 'ZN', 'RAD', 'INDUS', 'B', 'AGE', 'TAX', | ||
| 'PTRATIO', 'CRIM', 'NOX', 'DIS', 'RM', 'LSTAT'] |
There was a problem hiding this comment.
Is this expected order known from elsewhere, or something that you've calculated after the fix?
There was a problem hiding this comment.
This is calculated after the fix and included as a non-regression test.
| total_sum += stage_sum | ||
|
|
||
| importances = total_sum / len(self.estimators_) | ||
| importances /= importances.sum() |
There was a problem hiding this comment.
Please clarify how this relates to the new parameter
There was a problem hiding this comment.
The previous behavior normalized by the sum of importances, but did this on a per-tree basis before adding up all of the importances across trees. The new parameter stops the normalization on the per-tree basis so it is added back in here.
The general idea is to switch from a normalize then sum workflow to a sum then normalize in order to avoid overweighting features that contribute less to total gini importance.
There was a problem hiding this comment.
But when are we using normalize_feature_importances actually. It seems that it is never used.
There was a problem hiding this comment.
It's never being used in GBM, but it is set True (by default) when used by Random Forests.
There was a problem hiding this comment.
I got that but I don't see a statement:
if normalize_feature_importances:
importance /= ...There was a problem hiding this comment.
Ahhh, gotcha. Ok, I'll add that in. Thanks!
There was a problem hiding this comment.
Actually -- sorry, I think I misunderstood.
It's only being used in the call to instantiate the DecisionTreeRegressor without adding in a totally separate class.
There was a problem hiding this comment.
Oh sorry I see. The computation of the importance is in the cython file, right.
There was a problem hiding this comment.
Right, so for GBMs only, we skip the normalization part of the computation in the cython file and then do the normalization here (which is reasonably cheap since it's just the single numpy operation no matter the number of trees)
|
In re: the effect of changing the parameter, it is going to change the feature importance orders -- for the example here: http://scikit-learn.org/stable/auto_examples/ensemble/plot_gradient_boosting_regression.html |
|
Thanks for looking it over! |
|
okay. my main question (in some ignorance) is: should we be making this an
option, and if so, only in gbm? Or is it a bug that should be fixed? If
it's not an outright bug, then we should be maintaining a
backwards-compatible default.
|
|
It's a bug that should be fixed. |
|
Hey @jnothman -- just a gentle ping on this. Is there anything I can add to help get this merged in? |
|
Thanks for the ping. If it's definitely a bug, is there any benefit to providing an option to switch it? On the other hand, how much user code to we break by changing it outright? (Perhaps it's not so bad if we're only breaking feature importances and not prediction??) I'm basically unsure about the correct way to go on this, and would appreciate others' opinion and expertise on gradient boosting. |
|
(This comment has been edited lightly for clarity) Hey there! Let me try to provide a bit more context on this from the modeling angle, and how this incorporates with the software changes in Gil's patch. The problem arises because there are multiple modeling approaches that use decision tree regressors, however, scikit-learn's decision tree regressor implementation did not provide the unnormalized importance information back to the calling method (gradient boosting), in order for gradient boosting to correctly report feature importance back. Because gradient boosting was reporting feature importance normalized by tree, it was overweighting features in later stages of the boosting (which contributed overall less to the model's predictive power). Gil fixes this by normalizing across trees. The right way to think of this is that earlier trees in gradient boosting might have values like 1000/900 in their feature importance values, and later trees might have feature importance values like 10/9. If we normalize the feature importance values before summing them together, as scikit-learn was doing before this patch, we'll be misled into thinking the feature importances are "equal". R's GBM implementation reports feature importance correctly. The scikit-learn example for calculating feature importance of the Boston dataset (Gil's test checks for a regression against this) shows how calculating the tree-normalized feature importance in gradient boosting will lead to incorrect feature importances: http://scikit-learn.org/stable/auto_examples/ensemble/plot_gradient_boosting_regression.html. In the plotted example, AGE is overweighted and NOX is underweighted in terms of their overall predictive power. |
|
Sorry for the wall of text, here's an academic reference for the issue we're discussing here: In Friedman’s “Greedy Function Approximation” in the Annals of Statistics, 2001, https://projecteuclid.org/download/pdf_1/euclid.aos/1013203451, the relative importance of input variables is described in section 8.1. Equation 44 (from Breiman, Friedman, Olshen & Stone, 1983) shows that a feature’s relative importance in a tree is the total improvement in squared error over all nodes splitting on that feature — not normalized or proportional — with equation 45 computing the feature’s relative importance to the GBM by taking the average over all trees of the sum (again, not the average over proportions). The PR is “canonical” and consistent with other implementations, e.g., R’s gbm (and others). (Hat tip again to Joel Danke at Capital One for originally spotting this and helping Gil and I with the context we're providing here). |
|
Hey @jnothman -- thanks again for sticking with us on this. Do you have any suggestions on who among the maintainers has the requisite expertise on gradient boosting to look this over? |
|
@glemaitre, if you can chime in on whether you think this should be treated as a bug fix or an option? |
|
This look like a bug from what I can read in Friedman's paper. |
|
I don't think that the fix is the best one (API related). Introducing a parameter in the tree which is not related to the tree or not useful to user is a drawback (we already have a lot of parameter to understand in tree). However, I think that we could call |
|
So modifying this function: scikit-learn/sklearn/ensemble/gradient_boosting.py Lines 1219 to 1237 in 066b501 |
|
So for me the fix should be: stage_sum = sum(tree.tree_.compute_feature_importances_(normalize=False)
for tree in stage) / len(stage) |
|
Hey @glemaitre -- thanks for the review! I've reverted the API changes and added in the feature importance fix as you suggested. If it looks good to you I'll make sure CI passes and then squash down the changes and fix the original commit message to match the actual fix implemented. |
Do not squash. It will mess up the comments on GitHub. We are going to squash with the GitHub interface and take care about the history at merging time ;) |
|
Hey @glemaitre -- I've made the changes you requested and the regression test is passing on Travis now. There is a spurious failure on travis that seems to be from a 404 for some external data source one of the doc pages needs? @jnothman -- thanks for the review, I've updated the |
|
I saw an example of feature importance from Elements of Statistical Learning which is done on california housing. I would like to reproduce it to check if we can use it as testing. Sent from my phone - sorry to be brief and potential misspell.
|
|
So here come what I would consider as a test: import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
california = fetch_california_housing()
X, y = california.data, california.target
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
# Gradient boosting
reg = GradientBoostingRegressor(loss='huber', learning_rate=0.1,
max_leaf_nodes=6, n_estimators=800,
random_state=0)
reg.fit(X_train, y_train)
sorted_idx = np.argsort(reg.feature_importances_)[::-1]
print('Gradient boosting')
print([california.feature_names[s] for s in sorted_idx])
print(reg.feature_importances_[sorted_idx])
# Random Forest
reg = RandomForestRegressor(n_estimators=100, n_jobs=-1, min_samples_leaf=5,
random_state=0)
reg.fit(X_train, y_train)
sorted_idx = np.argsort(reg.feature_importances_)[::-1]
print('Random forest')
print([california.feature_names[s] for s in sorted_idx])
print(reg.feature_importances_[sorted_idx])Results in the master branchResults in the current PR:Results for Random ForestResults mentioned in Hastie et al. |
|
So it seems that this is a good fix even if the relative importance is still not the same than in the book but the trend is the same. So I would rework the test based on the snippet that I showed (we might not need 800 estimators). As some test conditions, I would check that MedInc > Longitude > HouseAge > Population. And I would add a comment at the beginning of the text referring to the experiment in Hastie et al. p.373 |
|
@jnothman Do you agree with those? |
|
I don't know how brittle that ordering is, but it's certainly comforting that this pr brings us closer. Yes it seems an appropriate test |
Hey @glemaitre -- I was working on the same example yesterday afternoon and have the same results. I'll experiment a little bit but looking at the Putting this together now and will report back results. |
Replacing regression test with a GBM example from the Elements of Statistical Learning, pg. 373.
| @@ -12,7 +12,7 @@ | |||
|
|
|||
| from sklearn import datasets | |||
There was a problem hiding this comment.
Yes it's used elsewhere in the test file.
| assert boston.feature_names[sorted_idx].tolist() == ordered_features | ||
| """Test that Gini importance is calculated correctly | ||
|
|
||
| This test is follows an example from [1] (pg. 373). |
There was a problem hiding this comment.
-> The test that follows is an example...
| [1]: Friedman, J., Hastie, T., & Tibshirani, R. (2001). The elements of | ||
| statistical learning. New York: Springer series in statistics. | ||
| """ | ||
| california = fetch_california_housing() |
| X, y = california.data, california.target | ||
| X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) | ||
|
|
||
| # Gradient boosting |
There was a problem hiding this comment.
I will clean it up when merging but let me wait for the CI first. appveyor is already saturated :)
| sorted_idx = np.argsort(reg.feature_importances_)[::-1] | ||
| feature_names_sorted = [california.feature_names[s] for s in sorted_idx] | ||
|
|
||
| assert feature_names_sorted[:4] == ['MedInc', 'Longitude', |
There was a problem hiding this comment.
It might be worth testing the bottom 2-3 as well if they are stable. But at this point, I'm really happy with where this PR is.
|
Thanks for the non-regression test @gforsyth . I found it a bit too slow. I pushed a change to relax it a bit while checking that I could still reproduce the issue on master with only 100 trees (instead of 200). |
|
BTW @gforsyth, remark for later: you should not use your master branch to submit PRs, otherwise you cannot work on several PRs in parallel. |
ogrisel
left a comment
There was a problem hiding this comment.
LGTM if CI is still green with the last commit.
|
@ahmadia @gforsyth in the plots reported by @glemaitre there seems to be a difference in the relative feature importances w.r.t. the plot of ESLII. It would be great to try to understand the source of that remaining discrepancy (although I think only the order really matters in practice). I you have sparse cycles feel free to open another issue with the results of your investigations. |
Sounds good to me @ogrisel -- thanks for the fix.
can't I just open PRs from arbitrary branches? |
You can but it's confusing to have a branch named "master" that does not actually track the content of the upstream master branch. |
jnothman
left a comment
There was a problem hiding this comment.
Thanks and good work, everyone.
I would even assume that this something shared by the GradientBoosting and RandomForest. I would check if there is not something fishy with some normalization when computing the the Gini Importance descending each tree. |
|
CI passed! Thanks for the reviews and help, all! |
…or GBT ## What changes were proposed in this pull request? Our feature importance calculation is taken from sklearn's one, which has been recently fixed (in scikit-learn/scikit-learn#11176). Citing the description of that PR: > Because the feature importances are (currently, by default) normalized and then averaged, feature importances from later stages are overweighted. The PR performs a fix similar to sklearn's one. The per-tree normalization of the feature importance is skipped and GBT. Credits for pointing out clearly the issue and the sklearn's PR to Daniel Jumper. ## How was this patch tested? modified UT, checked that the computed `featureImportance` in that test is similar to sklearn's one (ti can't be the same, because the trees may be slightly different) Closes apache#23773 from mgaido91/SPARK-26721. Authored-by: Marco Gaido <[email protected]> Signed-off-by: Sean Owen <[email protected]>




Reference Issues/PRs
What does this implement/fix? Explain your changes.
This makes a small change to the
BaseDecisionTreeandDecisionTreeRegressor, adding anormalize_feature_importanceskwargthat defaults to
True(matching current behavior) but is set toFalsefor GBMs.
Tree-level feature importances are calculated as the proportional reduction of
that tree's root node entropy (see _tree.pyx) and ensemble-level importances are
averaged across trees.
Because the feature importances are (currently, by default) normalized and then
averaged, feature importances from later stages are overweighted.
GBMs now defer the normalization step until after the per-tree importances have
been calculated (for the
DecisionTreeRegressorused inensemble.gradient_boosting.BaseGradientBoosting).Any other comments?
h/t to Joel Danke for spotting this and writing up the issue.