Cut the Table in Two

Machine Learning in CodeEasy+10 XP+10

Cut the Table in Two

A gym keeps a table about its members. One column is the thing it wants to predict. All the other columns are clues.

Task: write predict_from_table(table, label_column, new_rows).

  • table is a dict that maps each column name to a list of values. All lists have the same length. It includes the label column, and the label column is not always the last one.
  • label_column is the name of the column to predict.
  • new_rows is a dict shaped like table but without the label column. Its feature columns are in the same order as in table.
  • Build X from every column except the label, and y from the label column.
  • Train a KNeighborsClassifier(n_neighbors=3) on X and y, then predict new_rows.
  • Return the predictions as a plain list, one per new row.

Examples

table = {"weight": [150, 170, 130, 110, 160], "sweet": [7, 8, 3, 2, 6], "fruit": ["apple", "apple", "lemon", "lemon", "apple"]}
label_column = "fruit"
new_rows = {"weight": [155, 115], "sweet": [7, 2]}
returns ['apple', 'lemon']
table = {"visits": [2, 12, 3, 15, 1, 11], "plan": ["basic", "pro", "basic", "pro", "basic", "pro"], "classes": [0, 4, 1, 5, 0, 3]}
label_column = "plan"
new_rows = {"visits": [14, 2], "classes": [4, 1]}
returns ['pro', 'basic']

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