Compare class balance across train, val and test with value_counts

Easypandas

Why it matters Checking label balance per split catches broken splits and distribution shift before you trust any metric.

If the test split has a very different class balance from train, your metrics will mislead you. The quick check is the share of each label inside each split.

Write label_shares(df) where df has columns split (str) and label (str).

Return a dict mapping each split to a dict {label: share}, where share is the fraction of that split's rows with that label. Only labels that appear in a split are listed for it. Shares inside a split add up to 1.

Signaturedef label_shares(df)

Example

split ['train', 'train', 'train', 'test'], label ['a', 'a', 'b', 'b'] gives {'train': {'a': 0.6667, 'b': 0.3333}, 'test': {'b': 1.0}} (shares shown rounded).

Understand the idea

value_counts counts how often each value appears. With normalize=True it returns fractions instead of counts. After groupby, it does this inside each group, so each group's fractions add up to 1.

Worked example: train has labels a, a, b, so counts are a = 2, b = 1 and shares are 2/3 = 0.667 and 1/3 = 0.333. Test has a single b, so its share is 1.0. Dividing by the whole table (4 rows) instead would give train a = 0.5 and test b = 0.25, which answers a different question.

Rule: share(label | split) = count(split, label) / count(split).

Data teams run this before training classifiers and before trusting eval numbers, to spot leaked or skewed splits.

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

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

  • Sample 1: examplelabel_shares(_d1())
  • Sample 2: test split is skewedlabel_shares(_d2())
  • Test 3: one labellabel_shares(_d3())