|
| 1 | +""" |
| 2 | +================================================================ |
| 3 | +Permutation Importance vs Random Forest Feature Importance (MDI) |
| 4 | +================================================================ |
| 5 | +
|
| 6 | +In this example, we will compare the impurity-based feature importance of |
| 7 | +:class:`~sklearn.ensemble.RandomForestClassifier` with the |
| 8 | +permutation importance on the titanic dataset using |
| 9 | +:func:`~sklearn.inspection.permutation_importance`. We will show that the |
| 10 | +impurity-based feature importance can inflate the importance of numerical |
| 11 | +features. |
| 12 | +
|
| 13 | +Furthermore, the impurity-based feature importance of random forests suffers |
| 14 | +from being computed on statistics derived from the training dataset: the |
| 15 | +importances can be high even for features that are not predictive of the target |
| 16 | +variable, as long as the model has the capacity to use them to overfit. |
| 17 | +
|
| 18 | +This example shows how to use Permutation Importances as an alternative that |
| 19 | +can mitigate those limitations. |
| 20 | +
|
| 21 | +.. topic:: References: |
| 22 | +
|
| 23 | + .. [1] L. Breiman, "Random Forests", Machine Learning, 45(1), 5-32, |
| 24 | + 2001. https://doi.org/10.1023/A:1010933404324 |
| 25 | +""" |
| 26 | +print(__doc__) |
| 27 | +import matplotlib.pyplot as plt |
| 28 | +import numpy as np |
| 29 | + |
| 30 | +from sklearn.datasets import fetch_openml |
| 31 | +from sklearn.ensemble import RandomForestClassifier |
| 32 | +from sklearn.impute import SimpleImputer |
| 33 | +from sklearn.inspection import permutation_importance |
| 34 | +from sklearn.compose import ColumnTransformer |
| 35 | +from sklearn.model_selection import train_test_split |
| 36 | +from sklearn.pipeline import Pipeline |
| 37 | +from sklearn.preprocessing import OneHotEncoder |
| 38 | + |
| 39 | + |
| 40 | +############################################################################## |
| 41 | +# Data Loading and Feature Engineering |
| 42 | +# ------------------------------------ |
| 43 | +# Let's use pandas to load a copy of the titanic dataset. The following shows |
| 44 | +# how to apply separate preprocessing on numerical and categorical features. |
| 45 | +# |
| 46 | +# We further include two random variables that are not correlated in any way |
| 47 | +# with the target variable (``survived``): |
| 48 | +# |
| 49 | +# - ``random_num`` is a high cardinality numerical variable (as many unique |
| 50 | +# values as records). |
| 51 | +# - ``random_cat`` is a low cardinality categorical variable (3 possible |
| 52 | +# values). |
| 53 | +X, y = fetch_openml("titanic", version=1, as_frame=True, return_X_y=True) |
| 54 | +X['random_cat'] = np.random.randint(3, size=X.shape[0]) |
| 55 | +X['random_num'] = np.random.randn(X.shape[0]) |
| 56 | + |
| 57 | +categorical_columns = ['pclass', 'sex', 'embarked', 'random_cat'] |
| 58 | +numerical_columns = ['age', 'sibsp', 'parch', 'fare', 'random_num'] |
| 59 | + |
| 60 | +X = X[categorical_columns + numerical_columns] |
| 61 | + |
| 62 | +X_train, X_test, y_train, y_test = train_test_split( |
| 63 | + X, y, stratify=y, random_state=42) |
| 64 | + |
| 65 | +categorical_pipe = Pipeline([ |
| 66 | + ('imputer', SimpleImputer(strategy='constant', fill_value='missing')), |
| 67 | + ('onehot', OneHotEncoder(handle_unknown='ignore')) |
| 68 | +]) |
| 69 | +numerical_pipe = Pipeline([ |
| 70 | + ('imputer', SimpleImputer(strategy='mean')) |
| 71 | +]) |
| 72 | + |
| 73 | +preprocessing = ColumnTransformer( |
| 74 | + [('cat', categorical_pipe, categorical_columns), |
| 75 | + ('num', numerical_pipe, numerical_columns)]) |
| 76 | + |
| 77 | +rf = Pipeline([ |
| 78 | + ('preprocess', preprocessing), |
| 79 | + ('classifier', RandomForestClassifier(random_state=42)) |
| 80 | +]) |
| 81 | +rf.fit(X_train, y_train) |
| 82 | + |
| 83 | +############################################################################## |
| 84 | +# Accuracy of the Model |
| 85 | +# --------------------- |
| 86 | +# Prior to inspecting the feature importances, it is important to check that |
| 87 | +# the model predictive performance is high enough. Indeed there would be little |
| 88 | +# interest of inspecting the important features of a non-predictive model. |
| 89 | +# |
| 90 | +# Here one can observe that the train accuracy is very high (the forest model |
| 91 | +# has enough capacity to completely memorize the training set) but it can still |
| 92 | +# generalize well enough to the test set thanks to the built-in bagging of |
| 93 | +# random forests. |
| 94 | +# |
| 95 | +# It might be possible to trade some accuracy on the training set for a |
| 96 | +# slightly better accuracy on the test set by limiting the capacity of the |
| 97 | +# trees (for instance by setting ``min_samples_leaf=5`` or |
| 98 | +# ``min_samples_leaf=10``) so as to limit overfitting while not introducing too |
| 99 | +# much underfitting. |
| 100 | +# |
| 101 | +# However let's keep our high capacity random forest model for now so as to |
| 102 | +# illustrate some pitfalls with feature importance on variables with many |
| 103 | +# unique values. |
| 104 | +print("RF train accuracy: %0.3f" % rf.score(X_train, y_train)) |
| 105 | +print("RF test accuracy: %0.3f" % rf.score(X_test, y_test)) |
| 106 | + |
| 107 | + |
| 108 | +############################################################################## |
| 109 | +# Tree's Feature Importance from Mean Decrease in Impurity (MDI) |
| 110 | +# -------------------------------------------------------------- |
| 111 | +# The impurity-based feature importance ranks the numerical features to be the |
| 112 | +# most important features. As a result, the non-predictive ``random_num`` |
| 113 | +# variable is ranked the most important! |
| 114 | +# |
| 115 | +# This problem stems from two limitations of impurity-based feature |
| 116 | +# importances: |
| 117 | +# |
| 118 | +# - impurity-based importances are biased towards high cardinality features; |
| 119 | +# - impurity-based importances are computed on training set statistics and |
| 120 | +# therefore do not reflect the ability of feature to be useful to make |
| 121 | +# predictions that generalize to the test set (when the model has enough |
| 122 | +# capacity). |
| 123 | +ohe = (rf.named_steps['preprocess'] |
| 124 | + .named_transformers_['cat'] |
| 125 | + .named_steps['onehot']) |
| 126 | +feature_names = ohe.get_feature_names(input_features=categorical_columns) |
| 127 | +feature_names = np.r_[feature_names, numerical_columns] |
| 128 | + |
| 129 | +tree_feature_importances = ( |
| 130 | + rf.named_steps['classifier'].feature_importances_) |
| 131 | +sorted_idx = tree_feature_importances.argsort() |
| 132 | + |
| 133 | +y_ticks = np.arange(0, len(feature_names)) |
| 134 | +fig, ax = plt.subplots() |
| 135 | +ax.barh(y_ticks, tree_feature_importances[sorted_idx]) |
| 136 | +ax.set_yticklabels(feature_names[sorted_idx]) |
| 137 | +ax.set_yticks(y_ticks) |
| 138 | +ax.set_title("Random Forest Feature Importances (MDI)") |
| 139 | +fig.tight_layout() |
| 140 | +plt.show() |
| 141 | + |
| 142 | + |
| 143 | +############################################################################## |
| 144 | +# As an alternative, the permutation importances of ``rf`` are computed on a |
| 145 | +# held out test set. This shows that the low cardinality categorical feature, |
| 146 | +# ``sex`` is the most important feature. |
| 147 | +# |
| 148 | +# Also note that both random features have very low importances (close to 0) as |
| 149 | +# expected. |
| 150 | +result = permutation_importance(rf, X_test, y_test, n_repeats=10, |
| 151 | + random_state=42, n_jobs=2) |
| 152 | +sorted_idx = result.importances_mean.argsort() |
| 153 | + |
| 154 | +fig, ax = plt.subplots() |
| 155 | +ax.boxplot(result.importances[sorted_idx].T, |
| 156 | + vert=False, labels=X_test.columns[sorted_idx]) |
| 157 | +ax.set_title("Permutation Importances (test set)") |
| 158 | +fig.tight_layout() |
| 159 | +plt.show() |
| 160 | + |
| 161 | +############################################################################## |
| 162 | +# It is also possible to compute the permutation importances on the training |
| 163 | +# set. This reveals that ``random_num`` gets a significantly higher importance |
| 164 | +# ranking than when computed on the test set. The difference between those two |
| 165 | +# plots is a confirmation that the RF model has enough capacity to use that |
| 166 | +# random numerical feature to overfit. You can further confirm this by |
| 167 | +# re-running this example with constrained RF with min_samples_leaf=10. |
| 168 | +result = permutation_importance(rf, X_train, y_train, n_repeats=10, |
| 169 | + random_state=42, n_jobs=2) |
| 170 | +sorted_idx = result.importances_mean.argsort() |
| 171 | + |
| 172 | +fig, ax = plt.subplots() |
| 173 | +ax.boxplot(result.importances[sorted_idx].T, |
| 174 | + vert=False, labels=X_train.columns[sorted_idx]) |
| 175 | +ax.set_title("Permutation Importances (train set)") |
| 176 | +fig.tight_layout() |
| 177 | +plt.show() |
0 commit comments