The Average Hides a Group

Machine Learning in CodeMedium+10 XP+10

The Average Hides a Group

A loan model is 90% accurate overall. But is it 90% accurate for everyone? Slice the results by group and find out.

Task: write group_accuracy(groups, y_true, y_pred).

  • groups[i] is the group of row i, such as an age band or a country. Groups are strings.
  • y_true and y_pred hold the real and predicted labels.
  • A group's accuracy is the share of its rows that were predicted correctly.

Return a dict:

  • "overall": the accuracy over all rows,
  • "by_group": a dict from each group to its accuracy,
  • "worst": the group with the lowest accuracy. If several groups tie, take the one that comes first alphabetically.

Round every accuracy to 3 decimal places. Compare unrounded accuracies when you choose the worst group.

Examples

groups = ['young', 'old', 'young', 'old', 'young', 'old', 'young']
y_true = [1, 0, 1, 1, 0, 1, 0]
y_pred = [1, 0, 1, 0, 0, 0, 0]
returns {'overall': 0.714, 'by_group': {'old': 0.333, 'young': 1.0}, 'worst': 'old'}
groups = ['UK', 'FR', 'UK', 'DE', 'FR', 'UK', 'DE', 'FR']
y_true = ['yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'no']
y_pred = ['yes', 'no', 'no', 'no', 'no', 'no', 'no', 'yes']
returns {'overall': 0.625, 'by_group': {'DE': 0.5, 'FR': 0.333, 'UK': 1.0}, 'worst': 'FR'}

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