Random Forest: The Label Most Trees Pick

Classic MLMedium+15 XP+15

Random Forest: The Label Most Trees Pick

A random forest is a crowd of decision trees, each trained on a slightly different slice of the data. Individually they're mediocre and they make different mistakes — which is the point. Pool their answers and the disagreements cancel out.

Task: write majority_vote(tree_predictions) returning the forest's final prediction for every example.

  • tree_predictions is a list of trees, and each tree is its list of predictions for the examples — so tree_predictions[2][5] is tree 2's answer for example 5. Every tree predicted every example, so all the inner lists are the same length.
  • For each example, the forest predicts whichever label the most trees chose.
  • If two labels tie, return the smaller one.
  • Labels can be numbers or strings.

The awkward bit is that you're given the data tree-by-tree but need to decide example-by-example, so you have to turn the table on its side before you can count anything.

This is why a forest beats its own trees: a single tree needs to be right, while the forest only needs most of its trees to not be wrong in the same direction at once.

Majority Vote

Every tree in the forest votes on the same loan application. Pick a forest size and see how the vote plays out.

Approve (3 trees)60%
Reject (2 trees)40%
Final Decision: Approved3 of 5 trees voted Approve

A narrow majority. If just one tree had voted differently, the result could have flipped.

Examples

tree_predictions = [[0, 1, 1], [0, 0, 1], [1, 0, 1]]
returns [0, 0, 1]
tree_predictions = [[2, 2], [1, 3], [2, 1], [1, 1]]
returns [1, 1]

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