Two Rankings, One Forest

Machine Learning in CodeMedium+10 XP+10

Two Rankings, One Forest

A winery's forest model ranks its columns two ways. The built-in importances are measured on the training rows. Permutation importance shuffles each column of the test rows and measures how far the accuracy falls. The two rankings do not have to agree. Here you check how far they overlap.

Task: write two_rankings(n).

  1. Load the data with load_wine(return_X_y=True, as_frame=True).
  2. Split it with train_test_split(X, y, test_size=0.25, random_state=0, stratify=y).
  3. Fit RandomForestClassifier(n_estimators=50, random_state=0) on the training rows.
  4. Run permutation_importance on the fitted forest with the test rows, n_repeats=5 and random_state=0.

Return a dict:

  • "built_in": the n column names with the highest feature_importances_, most important first,
  • "permutation": the n column names with the highest mean permutation importance (importances_mean), most important first,
  • "shared": how many names appear in both lists, as a whole number.

If two columns have exactly the same importance, the one that comes first in the data's columns ranks higher.

Examples

n = 3
returns {'built_in': ['proline', 'color_intensity', 'flavanoids'], 'permutation': ['proline', 'color_intensity', 'flavanoids'], 'shared': 3}
n = 6
returns {'built_in': ['proline', 'color_intensity', 'flavanoids', 'od280/od315_of_diluted_wines', 'alcohol', 'total_phenols'], 'permutation': ['proline', 'color_intensity', 'flavanoids', 'od280/od315_of_diluted_wines', 'alcohol', 'malic_acid'], 'shared': 5}

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run