Pushed the Other Way

Machine Learning in CodeMedium+10 XP+10

Pushed the Other Way

A scaled logistic regression reads 30 tumour measurements and predicts class 1 (benign) or 0 (malignant). A positive push moves a row towards benign; a negative push moves it towards malignant.

For one test sample, a doctor wants both sides of the story.

Task: write both_sides(test_index, n).

  • Load load_breast_cancer(return_X_y=True, as_frame=True).
  • Split with train_test_split(X, y, test_size=0.25, random_state=0, stratify=y).
  • Fit make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)) on the training rows.
  • Take test row X_test.iloc[[test_index]]. Its pushes are its scaled values times coef_[0].
  • Return a dict:
    • "predicted": the predicted class, a plain int
    • "benign": the names of the n columns with the largest positive pushes, largest first
    • "malignant": the names of the n columns with the most negative pushes, most negative first

Examples

test_index = 0
n = 2
returns {'predicted': 1, 'benign': ['worst texture', 'mean concave points'], 'malignant': ['compactness error', 'symmetry error']}
test_index = 40
n = 3
returns {'predicted': 0, 'benign': ['compactness error', 'mean compactness', 'symmetry error'], 'malignant': ['radius error', 'worst radius', 'worst area']}

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