One Classifier, Three Averages

Model EvaluationMedium+20 XP+20

One Classifier, Three Averages

A plant-care app sorts leaf photos into classes such as "healthy", "rust" and "blight". The F1 Score lesson scored a yes/no model. With more than two classes, you score each class on its own by treating it as the Positive class and every other class as Negative. For a class ccc:

  • TP: actual ccc, predicted ccc
  • FP: predicted ccc, actual anything else
  • FN: actual ccc, predicted anything else

Each class then gets its own Precision, Recall and F1 from the formulas you already know. A class's support is the number of rows whose actual label is that class. There are three common ways to turn the per-class scores into one number:

  • Macro F1: the plain average of the per-class F1 scores. Every class counts the same.
  • Weighted F1: the average of the per-class F1 scores, each weighted by its class's support.
  • Balanced accuracy: the plain average of the per-class Recall.

Task: write f1_summary(actual, predicted) and return the tuple (macro_f1, weighted_f1, balanced_accuracy), each rounded to 4 decimal places.

  • The classes are every label that appears in actual or in predicted. Labels can be strings or numbers.
  • If a class has TP = 0, its F1 is 0. This covers every case where Precision or Recall would divide by zero.
  • Macro F1 averages over all the classes. Balanced accuracy averages Recall over the classes that appear in actual only, since a class with no actual rows has nothing to recall.

When one class dominates a dataset, these three numbers can tell very different stories about the same predictions. Which one to report depends on whether a rare class matters as much to you as a common one.

Examples

actual = ["healthy", "rust", "healthy", "blight", "healthy", "rust", "healthy", "healthy", "rust", "healthy"]
predicted = ["healthy", "rust", "healthy", "healthy", "healthy", "healthy", "rust", "healthy", "rust", "healthy"]
returns (0.4786, 0.6615, 0.5)
actual = [0, 0, 0, 0, 0, 0, 0, 1, 1, 2]
predicted = [0, 0, 0, 0, 0, 0, 0, 0, 1, 2]
returns (0.8667, 0.8867, 0.8333)

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