The Whole Recipe

Machine Learning in CodeMedium+10 XP+10

The Whole Recipe

A gardener has measured one flower. They want to know the species, how sure the model is, and how good the model is in general.

Task: write classify_flower(flower, k, seed). flower is a list of 4 numbers in the iris column order.

  1. Load iris as X and y with load_iris(return_X_y=True, as_frame=True).
  2. Split with train_test_split(X, y, test_size=0.2, random_state=seed, stratify=y).
  3. Train a KNeighborsClassifier(n_neighbors=k) on the training rows.
  4. Return a dict with three keys:
    • "score": the test score, rounded to 3 decimal places.
    • "species": the predicted species name for flower, as a string.
    • "confidence": the probability of that predicted species, rounded to 2 decimal places.

Pass the flower as a one-row DataFrame with the iris column names.

Examples

flower = [6.0, 2.9, 4.9, 1.7]
k = 7
seed = 1
returns {'score': 0.967, 'species': 'virginica', 'confidence': 0.57}
flower = [5.1, 3.5, 1.4, 0.2]
k = 5
seed = 0
returns {'score': 1.0, 'species': 'setosa', 'confidence': 1.0}

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