Which Column Is Lemon?

Machine Learning in CodeMedium+10 XP+10

Which Column Is Lemon?

predict_proba gives one column per label, but which column is which? The model keeps the order in classes_, and it is not always the order you expect.

Task: write chance_of(train_rows, train_labels, new_rows, label, k).

  • Train a KNeighborsClassifier(n_neighbors=k) on train_rows and train_labels. The labels are strings.
  • For each row in new_rows, find the predicted probability of label. label is always one of the training labels.
  • Return those probabilities as a list, each rounded to 2 decimal places.

Examples

train_rows = [[150, 7], [170, 8], [130, 3], [110, 2], [160, 6]]
train_labels = ["lemon", "lemon", "apple", "apple", "lemon"]
new_rows = [[155, 7], [135, 4]]
label = "lemon"
k = 3
returns [1.0, 0.33]
train_rows = [[1, 1], [2, 2], [3, 3], [7, 7], [8, 8], [9, 9], [15, 15]]
train_labels = ["sun", "sun", "rain", "rain", "fog", "fog", "fog"]
new_rows = [[2, 2], [8, 8]]
label = "rain"
k = 4
returns [0.5, 0.5]

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