Which Way, and How Much?

Machine Learning in CodeHard+10 XP+10

Which Way, and How Much?

A clinician asked for the model's top columns, and for each one, which way it pushes the prediction. That needs two tools: importance for which, partial dependence for which way.

Task: write top_with_direction(n).

  • Load load_diabetes(return_X_y=True, as_frame=True) and split with train_test_split(X, y, test_size=0.25, random_state=0).
  • Fit make_pipeline(StandardScaler(), LinearRegression()) on the training rows.
  • Rank the columns by permutation_importance(model, X_test, y_test, n_repeats=10, random_state=0), highest mean first.
  • For each of the top n columns, run partial_dependence(model, X_train, features=[name], grid_resolution=10) and take its ["average"][0]. The column rises if the last value is greater than the first, and falls otherwise.
  • Return a list of [name, "rises" or "falls"] pairs, in importance order.

Examples

n = 2
returns [['s5', 'rises'], ['s1', 'falls']]
n = 4
returns [['s5', 'rises'], ['s1', 'falls'], ['bmi', 'rises'], ['bp', 'rises']]

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