Swap In the Typical Value

Machine Learning in CodeMedium+10 XP+10

Swap In the Typical Value

A random forest has no coefficients, but you can still poke one prediction: replace one of the row's values with the typical (median) training value, and see how far the chance of benign moves.

Task: write biggest_swing(test_index, columns).

  • Load load_breast_cancer(return_X_y=True, as_frame=True) and split with train_test_split(X, y, test_size=0.25, random_state=0, stratify=y).
  • Fit RandomForestClassifier(n_estimators=100, random_state=0) on the training rows.
  • Take row = X_test.iloc[[test_index]]. Its base chance is predict_proba(row)[0, 1].
  • For each name in columns: copy the row, set that column to X_train[name].median(), and compute base - new_chance.
  • Return a dict:
    • "base": the base chance, rounded to 2 decimal places
    • "changes": a dict from each name to its change, rounded to 2 decimal places
    • "biggest": the name whose change is largest in size, ignoring the sign

All numbers are plain floats. No two changes tie in size.

Examples

test_index = 94
columns = ["worst area", "worst perimeter", "worst texture"]
returns {'base': 0.54, 'changes': {'worst area': -0.13, 'worst perimeter': -0.08, 'worst texture': -0.03}, 'biggest': 'worst area'}
test_index = 30
columns = ["worst area", "worst concave points", "mean concavity"]
returns {'base': 0.43, 'changes': {'worst area': 0.0, 'worst concave points': -0.24, 'mean concavity': -0.11}, 'biggest': 'worst concave points'}

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