Compute information gain for one split

Why it matters Gradient-boosted trees in ranking and fraud models pick every split by a gain like this.

A decision tree picks the split that reduces label entropy the most.

Write info_gain(parent, left, right), each a list of class labels. Return H(parent) - (|left| / |parent|) H(left) - (|right| / |parent|) H(right), with entropy in bits (log base 2). An empty child contributes 0.

Signaturedef info_gain(parent, left, right)

Example

info_gain([0, 0, 1, 1], [0, 0], [1, 1]) is 1.0.

Understand the idea

A decision tree wants each split to make the labels purer. Entropy measures impurity: a node with all one class has entropy 0, and a 50/50 binary node has entropy 1 bit. Information gain is how much entropy drops after the split, with each child weighted by its share of the rows. Worked example: parent [0, 0, 0, 1], left [0, 0], right [0, 1]. H(parent) = -(0.75 log2 0.75 + 0.25 log2 0.25) = about 0.8113. H(left) = 0 because it is pure. H(right) = 1 because it is 50/50. Each child holds 2 of 4 rows, so the gain is 0.8113 - 0.5 * 0 - 0.5 * 1 = about 0.3113. Rule: H(S) = -sum over classes of p log2 p, using the class proportions p in S. Gain = H(parent) - (|left| / |parent|) H(left) - (|right| / |parent|) H(right). An empty child contributes 0. Used in: ID3 and C4.5 style trees, random forests and feature ranking, where the split with the biggest gain is picked at every node.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: exampleinfo_gain([0, 0, 1, 1], [0, 0], [1, 1])
  • Sample 2: useless splitinfo_gain([0, 1, 0, 1], [0, 1], [0, 1])
  • Test 3: uneveninfo_gain([0, 0, 0, 1, 1, 2], [0, 0, 0], [1, 1, 2])
  • Test 4: empty childinfo_gain([1, 1, 0], [1, 1, 0], [])