Majority vote of a forest

Easy8 min10 hidden tests

A random forest of several trees sorts support tickets into classes: 0 for billing, 1 for a bug report, 2 for account access. Each tree votes a class for every ticket. Write majority_vote(votes) that returns the forest's answer for each ticket: the class with the most votes, with ties going to the smallest class number.

Tap a vote to change it

most votes per column, ties to the smaller class
B0 billingU1 bugA2 accountunder each answer: votes for 0·1·2

The forest answers [0, 1, 2, 0]: the class with the most votes in each column. Ticket 0 is a tie at 2 votes each, so the smaller class, 0 (billing), wins.

Forest answer 0, 1, 2, 0.

Examples

Three trees, three tickets

majority_vote([[0, 1, 2], [0, 2, 2], [1, 1, 0]])

returns [0, 1, 2]

Both tickets are 2 against 2, so the smaller class wins

majority_vote([[2, 0], [1, 0], [2, 1], [1, 1]])

returns [1, 0]

Requirements

  • votes is a 2-D list or array of shape (n_trees, n_tickets) of ints 0 or more. Row t holds tree t's votes, and column j holds every tree's vote for ticket j.
  • Return a 1-D NumPy int array of length n_tickets.
  • Entry j is the class that appears most often in column j. If classes tie, pick the smallest.
The idea behind it

A random forest trains many decision trees, each on a resampled copy of the data and with random subsets of features. Each tree alone overfits in its own way. Their mistakes differ, so a vote among them is more accurate than most single trees. That is the idea of bagging, short for bootstrap aggregating. For classification the forest uses a majority vote: each tree names one class, and the class named most often wins. Ties need a fixed rule so the same input always gets the same answer. Here the smallest class number wins. Some libraries average the trees' class probabilities instead, a soft vote. The hard vote in this problem is the original form and is still common when trees only output labels.

pythonCtrl+Enter runs
import numpy as np

def majority_vote(votes):
"""Combine the trees' votes for each ticket.

votes: 2-D list or array, shape (n_trees, n_tickets), int classes >= 0
Returns a 1-D int array of length n_tickets: the most voted class in
each column, with ties going to the smallest class.
"""
raise NotImplementedError

Stuck? Reveal one rung at a time

Worked solution

Pro includes the solution and walkthrough for every problem, plus the hands-on labs. The first problem of each topic is free.