|
| 1 | +import pandas as pd |
| 2 | +from sklearn.ensemble import RandomForestRegressor |
| 3 | +from sklearn.inspection import permutation_importance |
| 4 | +import matplotlib.pyplot as plt |
| 5 | +import numpy as np |
| 6 | + |
| 7 | + |
| 8 | +def generate_mdi(X, y, feature_names=None, random_state=42) -> pd.DataFrame: |
| 9 | + """ |
| 10 | + Generates a DataFrame with Gini importances from a RandomForestRegressor. |
| 11 | +
|
| 12 | + Notes: |
| 13 | + There are two limitations of impurity-based feature importances: |
| 14 | + - impurity-based importances are biased towards high cardinality features; |
| 15 | + - impurity-based importances are computed on training set statistics |
| 16 | + and therefore do not reflect the ability of feature to be useful to |
| 17 | + make predictions that generalize to the test set. Permutation |
| 18 | + importances can mitigate the last limitation, because ti can be computed on the |
| 19 | + test set. |
| 20 | +
|
| 21 | + Args: |
| 22 | + X (pd.DataFrame or np.ndarray): The feature set. |
| 23 | + y (pd.Series or np.ndarray): The target variable. |
| 24 | + feature_names (list, optional): List of feature names for labeling. Defaults to None. |
| 25 | + random_state (int, optional): Random state for the RandomForestRegressor. Defaults to 42. |
| 26 | +
|
| 27 | + Returns: |
| 28 | + pd.DataFrame: DataFrame with 'Feature' and 'Importance' columns. |
| 29 | +
|
| 30 | + Examples: |
| 31 | + >>> from spotpython.plot.importance import generate_mdi |
| 32 | + >>> import pandas as pd |
| 33 | + >>> from sklearn.datasets import make_regression |
| 34 | + >>> X, y = make_regression(n_samples=100, n_features=5, noise=0.1, random_state=42) |
| 35 | + >>> X_df = pd.DataFrame(X) |
| 36 | + >>> y_series = pd.Series(y) |
| 37 | + >>> result = generate_mdi(X_df, y_series) |
| 38 | + >>> print(result) |
| 39 | +
|
| 40 | + """ |
| 41 | + # Convert X and y to pandas DataFrames if they are not already |
| 42 | + if not isinstance(X, pd.DataFrame): |
| 43 | + X = pd.DataFrame(X) |
| 44 | + if not isinstance(y, pd.Series): |
| 45 | + y = pd.Series(np.ravel(y)) # Use np.ravel instead of flatten |
| 46 | + |
| 47 | + # Train a Random Forest Regressor |
| 48 | + rf = RandomForestRegressor(random_state=random_state) |
| 49 | + rf.fit(X, y) |
| 50 | + |
| 51 | + # Get feature importances |
| 52 | + importances = rf.feature_importances_ |
| 53 | + |
| 54 | + # Create a DataFrame |
| 55 | + if feature_names is None: |
| 56 | + df_mdi = pd.DataFrame({"Feature": X.columns, "Importance": importances}) |
| 57 | + else: |
| 58 | + df_mdi = pd.DataFrame({"Feature": feature_names, "Importance": importances}) |
| 59 | + df_mdi = df_mdi.sort_values("Importance", ascending=False).reset_index(drop=True) |
| 60 | + |
| 61 | + return df_mdi |
| 62 | + |
| 63 | + |
| 64 | +def generate_imp(X_train, X_test, y_train, y_test, random_state=42, n_repeats=10, use_test=True) -> permutation_importance: |
| 65 | + """ |
| 66 | + Generates permutation importances from a RandomForestRegressor. |
| 67 | +
|
| 68 | + Args: |
| 69 | + X_train (pd.DataFrame or np.ndarray): The training feature set. |
| 70 | + X_test (pd.DataFrame or np.ndarray): The test feature set. |
| 71 | + y_train (pd.Series or np.ndarray): The training target variable. |
| 72 | + y_test (pd.Series or np.ndarray): The test target variable. |
| 73 | + random_state (int, optional): Random state for the RandomForestRegressor. Defaults to 42. |
| 74 | + n_repeats (int, optional): Number of repeats for permutation importance. Defaults to 10. |
| 75 | + use_test (bool, optional): If True, computes permutation importance on the test set. If False, uses the training set. Defaults to True. |
| 76 | +
|
| 77 | + Returns: |
| 78 | + permutation_importance: Permutation importances object. |
| 79 | +
|
| 80 | + Examples: |
| 81 | + >>> from spotpython.plot.importance import generate_imp |
| 82 | + >>> import pandas as pd |
| 83 | + >>> from sklearn.datasets import make_regression |
| 84 | + >>> X, y = make_regression(n_samples=100, n_features=5, noise=0.1, random_state=42) |
| 85 | + >>> X_train, X_test = X[:80], X[80:] |
| 86 | + >>> y_train, y_test = y[:80], y[80:] |
| 87 | + >>> X_train_df = pd.DataFrame(X_train) |
| 88 | + >>> X_test_df = pd.DataFrame(X_test) |
| 89 | + >>> y_train_series = pd.Series(y_train) |
| 90 | + >>> y_test_series = pd.Series(y_test) |
| 91 | + >>> perm_imp = generate_imp(X_train_df, X_test_df, y_train_series, y_test_series) |
| 92 | + >>> print(perm_imp) |
| 93 | + """ |
| 94 | + # Convert inputs to pandas DataFrames/Series if they are not already |
| 95 | + if not isinstance(X_train, pd.DataFrame): |
| 96 | + X_train = pd.DataFrame(X_train) |
| 97 | + if not isinstance(X_test, pd.DataFrame): |
| 98 | + X_test = pd.DataFrame(X_test) |
| 99 | + if not isinstance(y_train, pd.Series): |
| 100 | + y_train = pd.Series(np.ravel(y_train)) # Use np.ravel instead of flatten |
| 101 | + if not isinstance(y_test, pd.Series): |
| 102 | + y_test = pd.Series(np.ravel(y_test)) # Use np.ravel instead of flatten |
| 103 | + |
| 104 | + # Train a Random Forest Regressor |
| 105 | + rf = RandomForestRegressor(random_state=random_state) |
| 106 | + rf.fit(X_train, y_train) |
| 107 | + |
| 108 | + # Select the dataset for permutation importance |
| 109 | + X_eval = X_test if use_test else X_train |
| 110 | + y_eval = y_test if use_test else y_train |
| 111 | + |
| 112 | + # Calculate permutation importances |
| 113 | + perm_imp = permutation_importance(rf, X_eval, y_eval, n_repeats=n_repeats, random_state=random_state) |
| 114 | + |
| 115 | + return perm_imp |
| 116 | + |
| 117 | + |
| 118 | +def plot_importances(df_mdi, perm_imp, X_test, target_name=None, feature_names=None, k=10, show=True) -> None: |
| 119 | + """ |
| 120 | + Plots the impurity-based and permutation-based feature importances for a given classifier. |
| 121 | +
|
| 122 | + Args: |
| 123 | + df_mdi (pd.DataFrame): |
| 124 | + DataFrame with Gini importances. |
| 125 | + perm_imp (object): |
| 126 | + Permutation importances object. |
| 127 | + X_test (pd.DataFrame): |
| 128 | + The test feature set for permutation importance. |
| 129 | + target_name (str, optional): |
| 130 | + Name of the target variable for labeling. Defaults to None. |
| 131 | + feature_names (list, optional): |
| 132 | + List of feature names for labeling. Defaults to None. |
| 133 | + k (int, optional): |
| 134 | + Number of top features to display based on importance. Default is 10. |
| 135 | + show (bool, optional): |
| 136 | + If True, displays the plot immediately. Default is True. |
| 137 | +
|
| 138 | + Returns: |
| 139 | + None |
| 140 | +
|
| 141 | + Examples: |
| 142 | + >>> from spotpython.plot.importance import generate_mdi, generate_imp, plot_importances |
| 143 | + >>> import pandas as pd |
| 144 | + >>> from sklearn.datasets import make_regression |
| 145 | + >>> X, y = make_regression(n_samples=100, n_features=5, noise=0.1, random_state=42) |
| 146 | + >>> X_train, X_test = X[:80], X[80:] |
| 147 | + >>> y_train, y_test = y[:80], y[80:] |
| 148 | + >>> X_train_df = pd.DataFrame(X_train) |
| 149 | + >>> X_test_df = pd.DataFrame(X_test) |
| 150 | + >>> y_train_series = pd.Series(y_train) |
| 151 | + >>> y_test_series = pd.Series(y_test) |
| 152 | + >>> df_mdi = generate_mdi(X_train_df, y_train_series) |
| 153 | + >>> perm_imp = generate_imp(X_train_df, X_test_df, y_train_series, y_test_series) |
| 154 | + >>> plot_importances(df_mdi, perm_imp, X_test_df) |
| 155 | +
|
| 156 | + """ |
| 157 | + |
| 158 | + # Plot impurity-based importances for top-k features |
| 159 | + fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 8)) |
| 160 | + |
| 161 | + sorted_mdi_importances = df_mdi.set_index("Feature")["Importance"] |
| 162 | + sorted_mdi_importances[:k].sort_values().plot.barh(ax=ax1) |
| 163 | + ax1.set_xlabel("Gini importance") |
| 164 | + if target_name: |
| 165 | + ax1.set_title(f"Impurity-based feature importances for target: {target_name}") |
| 166 | + else: |
| 167 | + ax1.set_title("Impurity-based feature importances") |
| 168 | + |
| 169 | + # Ensure X_test is a DataFrame |
| 170 | + if not isinstance(X_test, pd.DataFrame): |
| 171 | + X_test = pd.DataFrame(X_test) |
| 172 | + |
| 173 | + perm_sorted_idx = perm_imp.importances_mean.argsort()[-k:] |
| 174 | + if feature_names is not None: |
| 175 | + ax2.boxplot(perm_imp.importances[perm_sorted_idx].T, vert=False, labels=np.array(feature_names)[perm_sorted_idx]) |
| 176 | + else: |
| 177 | + ax2.boxplot(perm_imp.importances[perm_sorted_idx].T, vert=False, labels=X_test.columns[perm_sorted_idx]) |
| 178 | + ax2.axvline(x=0, color="k", linestyle="--") |
| 179 | + if target_name: |
| 180 | + ax2.set_xlabel(f"Decrease in mse for target: {target_name}") |
| 181 | + else: |
| 182 | + ax2.set_xlabel("Decrease in mse") |
| 183 | + ax2.set_title("Permutation-based feature importances") |
| 184 | + |
| 185 | + # fig.suptitle("Impurity-based vs. permutation importances") |
| 186 | + fig.tight_layout() |
| 187 | + if show: |
| 188 | + plt.show() |
0 commit comments