The First Question

Machine Learning in CodeMedium+10 XP+10

The First Question

A tree's first question is the single split that separates the classes most cleanly. You want to know which column it asks about.

Write first_question(rows, labels, names).

  • names holds the column names, in the same order as each row.
  • Fit DecisionTreeClassifier(max_depth=1, random_state=0).
  • Use export_text(model, feature_names=names) to get the tree as text. Its first line has the form |--- <column name> <= <threshold>.

Return a dict:

  • "column": the name of the column the first question uses, as a string.
  • "threshold": the number in that question, as a float, exactly as export_text shows it.

Examples

rows = [[12, 3.1, 0.4], [30, 2.2, 0.9], [8, 9.5, 1.6], [25, 7.8, 0.3], [5, 1.2, 0.2], [40, 4.4, 1.1], [15, 8.9, 0.8], [22, 1.5, 1.9], [3, 6.1, 0.5], [35, 9.9, 0.6]]
labels = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
names = ['sugar', 'fat', 'salt']
returns {'column': 'sugar', 'threshold': 18.5}
rows = [[2.1, 40], [3.5, 22], [1.2, 35], [4.8, 28], [2.9, 18], [5.5, 45], [1.8, 12], [4.1, 50]]
labels = ['no', 'yes', 'no', 'yes', 'no', 'yes', 'no', 'yes']
names = ['rainfall', 'temperature']
returns {'column': 'rainfall', 'threshold': 3.2}

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