The Whole Machine

Machine Learning in CodeHard+10 XP+10

The Whole Machine

A fruit stall's table has gaps in its number columns and a colour column with words. Build one leak-free pipeline that learns everything from the training rows only.

Task: write fruit_machine(table, labels, new_rows, seed).

  • table is a dict with number columns "weight" and "sweet" (which may contain None) and a word column "colour". labels holds the answer for each row.
  • new_rows is a dict with the same three columns, holding one or more new fruits.
  • Split with train_test_split(X, y, test_size=0.25, random_state=seed, stratify=y).
  • Build the pipeline:
    • A ColumnTransformer with ("numbers", ..., ["weight", "sweet"]), where ... is a Pipeline of SimpleImputer(strategy="median") then StandardScaler(). Add ("words", OneHotEncoder(handle_unknown="ignore"), ["colour"]).
    • Then KNeighborsClassifier(n_neighbors=3) as the last step.
  • Fit it on the training rows only.
  • Return {"score": test score rounded to 3 decimal places, "predictions": list of predictions for new_rows}.

Make the number columns float so each None becomes np.nan.

Examples

table = {"weight": [150.0, None, 170.0, 130.0, 110.0, None, 160.0, 120.0], "sweet": [7.0, 8.0, 3.0, 2.0, 2.0, 7.0, 6.0, 3.0], "colour": ["red", "red", "yellow", "yellow", "yellow", "red", "red", "yellow"]}
labels = ["apple", "apple", "lemon", "lemon", "lemon", "apple", "apple", "lemon"]
new_rows = {"weight": [None, 125.0], "sweet": [6.5, 2.5], "colour": ["red", "yellow"]}
seed = 0
returns {'score': 1.0, 'predictions': ['apple', 'lemon']}
table = {"weight": [150, 165, 172, 128, 112, 158, 163, 121, 140, 118, 155, 133], "sweet": [7, 8, None, 2, 2, 7, 6, 3, None, 3, 8, 2], "colour": ["red", "green", "red", "yellow", "yellow", "green", "red", "yellow", "green", "yellow", "red", "yellow"]}
labels = ["apple", "apple", "apple", "lemon", "lemon", "apple", "apple", "lemon", "apple", "lemon", "apple", "lemon"]
new_rows = {"weight": [160, 115, None], "sweet": [None, 2, 7], "colour": ["green", "yellow", "purple"]}
seed = 1
returns {'score': 0.667, 'predictions': ['apple', 'lemon', 'apple']}

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