Study, Then Answer

Machine Learning in CodeEasy+10 XP+10

Study, Then Answer

A market stall sorts fruit by two measurements: weight in grams and a sweetness score.

The owner has a few fruits that are already labelled. Now some new fruits arrive with no label.

Task: write predict_fruit(train_rows, train_labels, new_rows).

  • train_rows is a list of rows, one inner list of numbers per fruit. train_labels holds the answer for each of those rows, in the same order.
  • new_rows is a list of rows shaped the same way, but with no answers.
  • Make a KNeighborsClassifier with n_neighbors=3, let it learn from the labelled fruits, then ask it about the new ones.
  • Return the predicted labels as a plain Python list, one per new row, in the same order as new_rows.

Examples

train_rows = [[150, 7], [170, 8], [130, 3], [110, 2], [160, 6]]
train_labels = ["apple", "apple", "lemon", "lemon", "apple"]
new_rows = [[155, 7], [120, 3]]
returns ['apple', 'lemon']
train_rows = [[4.1, 30], [3.8, 28], [9.5, 61], [10.2, 66], [4.4, 33], [9.9, 58]]
train_labels = ["cat", "cat", "dog", "dog", "cat", "dog"]
new_rows = [[9.0, 60], [4.0, 31], [10.5, 70]]
returns ['dog', 'cat', 'dog']

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