Information Gain: The Entropy a Split Removes

Classic MLMedium+15 XP+15

Information Gain: The Entropy a Split Removes

Entropy measures how mixed a group of labels is, in bits:

H=−∑ipilog⁡2piH = -\sum_i p_i \log_2 p_iH=−i∑​pi​log2​pi​

All one class scores 0 — no surprise left. An even two-way mix scores exactly 1 bit.

Information gain is how much of that mixing a split removes: the entropy you started with, minus the entropy you're left with afterwards. Since a split leaves two groups, "afterwards" is their size-weighted average:

IG=H(parent)−[nLnH(L)+nRnH(R)]IG = H(\text{parent}) - \left[\frac{n_L}{n} H(L) + \frac{n_R}{n} H(R)\right]IG=H(parent)−[nnL​​H(L)+nnR​​H(R)]

Task: write information_gain(parent, left, right) returning the gain, rounded to 4 decimal places.

  • All three arguments are lists of labels — numbers or strings, any number of classes. left and right together hold the same labels as parent.
  • n is len(parent).
  • An empty side has entropy 0 and weight 0, so it contributes nothing — but don't divide by its size on the way there.
  • Use log2, so the answer is in bits.

Gain is never negative: splitting data cannot increase the weighted average entropy. A gain of exactly 0 means the split sorted the rows into two piles without separating the classes at all — the question you asked was irrelevant.

Which Question Is Smarter?

Try each question below and watch how much uncertainty it removes.

DogDogCatBirdDogBird

Examples

parent = [0, 0, 1, 1]
left = [0, 0]
right = [1, 1]
returns 1.0
parent = [0, 0, 1, 1]
left = [0, 1]
right = [0, 1]
returns 0.0

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