Tune the Columns and the Model Together

Machine Learning in CodeMedium+10 XP+10

Tune the Columns and the Model Together

How many columns to keep is a setting, just like C. So you can search both at once, with cross-validation on the training rows, and open the test rows once at the end.

Task: write tune_k_and_c(k_values, c_values).

  1. Load the data with load_breast_cancer(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. Build Pipeline([("scale", StandardScaler()), ("select", SelectKBest(f_classif)), ("model", SVC())]).
  4. Run GridSearchCV on it with cv=5, searching every combination of k_values for the selector's k and c_values for the model's C. Fit it on the training rows.

Return a dict:

  • "best": the search's best_params_, exactly as scikit-learn gives it,
  • "cv": the best cross-validated score, rounded to 3 decimal places,
  • "test": the winner's accuracy on the test rows, rounded to 3 decimal places.

Examples

k_values = [5, 30]
c_values = [1]
returns {'best': {'model__C': 1, 'select__k': 30}, 'cv': 0.986, 'test': 0.958}
k_values = [3, 10, 30]
c_values = [0.1, 1, 10]
returns {'best': {'model__C': 1, 'select__k': 30}, 'cv': 0.986, 'test': 0.958}

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