Weighing the Rare Class

Machine Learning in CodeEasy+10 XP+10

Weighing the Rare Class

A card company's transaction table is mostly ordinary purchases with a few frauds mixed in. In When One Class Is Rare you stopped a model from ignoring the rare class with one setting, class_weight="balanced". Behind that setting is a short calculation that gives every row a weight. While the model trains, a mistake on a row costs as much as that row's weight.

The weights are chosen so that three things are true at once:

  1. All rows of the same class get the same weight.
  2. Every class's weights add up to the same total, however many rows that class has.
  3. The weights of all nnn rows add up to nnn, so the average weight is exactly 1.

Task: write balanced_weights(labels). It takes the label of every row and returns the list of row weights, in the same order as labels, each rounded to 4 decimal places.

  • Labels can be numbers or strings, in any order.
  • Only classes that actually appear in labels count as classes.

Examples

labels = [0, 0, 0, 1]
returns [0.6667, 0.6667, 0.6667, 2.0]
labels = ["ok", "fraud", "ok", "ok", "ok", "ok", "ok", "ok", "ok", "fraud"]
returns [0.625, 2.5, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 2.5]

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