Where the Curve Peaks

Machine Learning in CodeMedium+10 XP+10

Where the Curve Peaks

Before running a big search, you sweep one setting and read the curve. Here the setting is the neighbour count of a tumour classifier.

Task: write neighbour_curve(k_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). Use the training rows only from here on.
  3. Run validation_curve on make_pipeline(StandardScaler(), KNeighborsClassifier()) with param_name set to the pipeline's neighbour-count setting, param_range=k_values and cv=5.
  4. Average the training scores and the validation scores across the folds, for each k.

Return a dict:

  • "best_k": the k with the highest mean validation score. If several tie, take the largest k, because more neighbours is the simpler model.
  • "best_score": that mean validation score, rounded to 4 decimal places.
  • "gap_at_first": for the first k in k_values, the mean training score minus the mean validation score, rounded to 4 decimal places.

Compare unrounded values when you choose.

Examples

k_values = [1, 5, 15, 51]
returns {'best_k': 5, 'best_score': 0.9625, 'gap_at_first': 0.0446}
k_values = [3, 7, 25]
returns {'best_k': 3, 'best_score': 0.9742, 'gap_at_first': 0.0117}

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