Every Combination, Five Folds Each

Machine Learning in CodeMedium+10 XP+10

Every Combination, Five Folds Each

A clinic wants the best neighbour settings for a tumour classifier, chosen honestly: by cross-validation on the training rows, with the test rows opened only once at the end.

Task: write search_neighbours(neighbour_counts, weightings).

  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. Run a GridSearchCV over make_pipeline(StandardScaler(), KNeighborsClassifier()) with cv=5. Search every combination of neighbour_counts for the neighbour count and weightings for the weights setting.
  4. Fit the search 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 4 decimal places,
  • "test": the refitted winner's accuracy on the test rows, rounded to 4 decimal places,
  • "fits": how many models the search trained during cross-validation (combinations × folds), as a whole number.

Examples

neighbour_counts = [1, 3, 5]
weightings = ["uniform"]
returns {'best': {'kneighborsclassifier__n_neighbors': 3, 'kneighborsclassifier__weights': 'uniform'}, 'cv': 0.9742, 'test': 0.951, 'fits': 15}
neighbour_counts = [1, 5, 21]
weightings = ["uniform", "distance"]
returns {'best': {'kneighborsclassifier__n_neighbors': 5, 'kneighborsclassifier__weights': 'uniform'}, 'cv': 0.9625, 'test': 0.951, 'fits': 30}

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