Sub topic 11
Multiclass problems: macro, micro, and weighted averages
Precision, recall, and F1 are defined for one positive class. A multiclass problem has several classes, so you get one set of numbers per class. This chapter shows how to turn those per-class numbers into a single score, and how the choice of average changes the story the score tells.
This chapter assumes you can already compute precision, recall, and F1 from true positive, false positive, and false negative counts in the binary case. It also assumes you can read a confusion matrix, run basic Python and NumPy, and call scikit-learn metric functions.
From one positive class to many
In a binary problem, one class is "positive" and the other is "negative". In a multiclass problem with classes cat, dog, and bird, every class takes a turn as the positive class. This is called one-vs-rest. For the class cat, a prediction counts like this:
- True positive (TP): the true label is cat and the model predicted cat.
- False positive (FP): the true label is something else and the model predicted cat.
- False negative (FN): the true label is cat and the model predicted something else.
- True negative (TN): neither the true label nor the prediction is cat.
You repeat this for each class. The result is one precision, one recall, and one F1 value per class. Averaging then combines those values into one number.
A worked example
Use a 3-class problem with 20 samples. Rows are true classes, columns are predicted classes, in the order 0, 1, 2.
| True \ Predicted | 0 | 1 | 2 | Support (row sum) |
|---|---|---|---|---|
| 0 | 8 | 1 | 1 | 10 |
| 1 | 1 | 4 | 1 | 6 |
| 2 | 0 | 1 | 3 | 4 |
Support is the number of true samples of a class. Class 2 is the rarest, with 4 samples.
For each class, TP is the diagonal cell. FP is the rest of the column. FN is the rest of the row.
- Precision for a class is the diagonal cell divided by its column sum.
- Recall for a class is the diagonal cell divided by its row sum.
The following code computes this directly from the matrix.
import numpy as np
cm = np.array([
[8, 1, 1],
[1, 4, 1],
[0, 1, 3],
])
tp = np.diag(cm)
precision = tp / cm.sum(axis=0) # column sums: predicted counts
recall = tp / cm.sum(axis=1) # row sums: true counts
f1 = 2 * precision * recall / (precision + recall)
support = cm.sum(axis=1)
print(precision.round(2)) # about [0.89 0.67 0.6]
print(recall.round(2)) # about [0.8 0.67 0.75]
print(f1.round(2)) # about [0.84 0.67 0.67]
print(support) # [10 6 4]Class 0 is predicted well. Classes 1 and 2 are weaker. Every average below summarizes these same nine numbers (three precisions, three recalls, three F1 scores), but each one weights the classes differently.
The three averages
Macro average
The macro average computes the metric for each class, then takes the plain mean. Every class counts equally, whatever its size.
print(precision.mean().round(2)) # 0.72
print(recall.mean().round(2)) # 0.74
print(f1.mean().round(2)) # 0.73Macro precision is (0.889 + 0.667 + 0.6) / 3 = 0.72. A rare class with poor scores pulls the macro average down as hard as a common class does. Use macro when each class matters equally, for example when a rare disease category is as important as a common one.
Micro average
The micro average pools the counts from all classes first, then computes the metric once. It sums TP, FP, and FN across classes.
Here the total TP is 8 + 4 + 3 = 15. Every wrong prediction is a false positive for the predicted class and a false negative for the true class. So the total FP is 5 and the total FN is 5.
total_tp = tp.sum()
total_fp = (cm.sum(axis=0) - tp).sum()
total_fn = (cm.sum(axis=1) - tp).sum()
micro_precision = total_tp / (total_tp + total_fp)
micro_recall = total_tp / (total_tp + total_fn)
micro_f1 = (2 * micro_precision * micro_recall
/ (micro_precision + micro_recall))
print(micro_precision, micro_recall, micro_f1) # 0.75 0.75 0.75In single-label multiclass classification, where each sample has exactly one true class and one predicted class, total FP always equals total FN. So micro precision, micro recall, and micro F1 are all equal to accuracy: 15 / 20 = 0.75. Large classes dominate this number, because they contribute the most samples.
Weighted average
The weighted average takes the per-class metrics and averages them using support as the weight. Each class counts in proportion to how many true samples it has.
weighted_precision = np.average(precision, weights=support)
weighted_recall = np.average(recall, weights=support)
weighted_f1 = np.average(f1, weights=support)
print(round(weighted_precision, 2)) # 0.76
print(round(weighted_recall, 2)) # 0.75
print(round(weighted_f1, 2)) # 0.75Weighted recall always equals accuracy in this setting, because the weights turn the mean back into total TP divided by total samples. Weighted precision and weighted F1 can differ from accuracy slightly. Weighted averaging keeps per-class detail but, like micro, lets large classes dominate.
Side by side
| Average | How it is computed | Who dominates | Equals accuracy? |
|---|---|---|---|
| Macro | Mean of per-class scores | All classes equally | No |
| Micro | Pool TP, FP, FN, then compute | Large classes | Yes, for single-label multiclass |
| Weighted | Mean of per-class scores, weighted by support | Large classes | Only recall |
For the example, the three averages give:
| Average | Precision | Recall | F1 |
|---|---|---|---|
| Macro | 0.72 | 0.74 | 0.73 |
| Micro | 0.75 | 0.75 | 0.75 |
| Weighted | 0.76 | 0.75 | 0.75 |
Macro is lowest because it gives the weak, small classes full weight. Micro and weighted sit closer to the strong, large class 0.
Computing the averages with scikit-learn
Rebuild the labels from the confusion matrix and let scikit-learn do the work.
from sklearn.metrics import (
confusion_matrix,
precision_recall_fscore_support,
)
y_true = [0] * 10 + [1] * 6 + [2] * 4
y_pred = ([0] * 8 + [1] + [2] # true class 0
+ [0] + [1] * 4 + [2] # true class 1
+ [1] + [2] * 3) # true class 2
print(confusion_matrix(y_true, y_pred))
# [[8 1 1]
# [1 4 1]
# [0 1 3]]
for avg in ("macro", "micro", "weighted"):
p, r, f, _ = precision_recall_fscore_support(
y_true, y_pred, average=avg
)
print(f"{avg:<9} {p:.2f} {r:.2f} {f:.2f}")
# macro 0.72 0.74 0.73
# micro 0.75 0.75 0.75
# weighted 0.76 0.75 0.75The output matches the manual calculation. The same average argument works in precision_score, recall_score, and f1_score.
Two related options are worth knowing:
average=Nonereturns one score per class, in sorted label order. Use it to find which class is hurting the average.classification_report(y_true, y_pred)prints per-class precision, recall, F1, and support, followed by an accuracy row, a macro average row, and a weighted average row. For single-label multiclass data it shows accuracy instead of a micro row, because the two are identical.
Edge cases
Classes the model never predicts
If the model never predicts a class, that class has TP + FP = 0. Its precision is 0 / 0, which is undefined. Scikit-learn replaces it with a fixed value, controlled by zero_division. The default is "warn", which uses 0 and emits a warning.
from sklearn.metrics import precision_score
y_true = [0, 0, 1, 2]
y_pred = [0, 0, 1, 1] # class 2 is never predicted
print(round(precision_score(y_true, y_pred, average="macro",
zero_division=0), 2)) # 0.5
print(round(precision_score(y_true, y_pred, average="macro",
zero_division=1), 2)) # 0.83The same data gives 0.5 or 0.83 depending on a convention. Macro averages feel this directly, because the undefined class has full weight. Report which setting you used.
Classes that are absent from the labels
If a class appears in neither y_true nor y_pred, scikit-learn does not know it exists. Pass labels=[0, 1, 2] to include it explicitly. This matters when a test split happens to lack a rare class, and when you compare scores across splits that should cover the same classes.
Multilabel data
When one sample can have several labels at once, there is a fourth option, average="samples". It computes the metric for each sample and averages across samples. Micro averaging for multilabel data does not equal accuracy, because the FP and FN totals no longer match.
Choosing and reporting an average
Follow these rules in practice:
- Start from the cost of errors. If missing a rare class is expensive, macro recall exposes it, while micro and weighted hide it.
- Use micro when you care about overall per-sample performance and class frequencies reflect real usage. It is the same as accuracy for single-label data, so reporting it separately adds nothing.
- Use weighted when you want per-class detail but a headline number that follows the data distribution.
- Always show per-class scores next to any average. An average of 0.75 can come from three classes near 0.75 or from one class at 0.95 and another at 0.4.
- Name the average. "F1 = 0.73" is incomplete. "Macro F1 = 0.73" can be compared with other results.
As in the binary case, compute all of these on held-out test data, not on the training set, and keep the test data unused while tuning the model.
Summary of the key points
- Multiclass precision, recall, and F1 come from treating each class as positive in turn (one-vs-rest).
- Macro averages per-class scores equally, so rare classes count fully.
- Micro pools counts, and for single-label multiclass data it equals accuracy.
- Weighted averages per-class scores by support, so large classes dominate.
- Undefined scores from classes that are never predicted depend on
zero_division, so state your choice.
Exercise
A 3-class model has this confusion matrix (rows are true classes, columns are predicted classes): [[9, 1, 0], [2, 6, 2], [0, 0, 10]]. Compute the per-class recall and the macro recall. Then compute the micro recall and explain why it differs from the macro recall, or why it does not.
Show answer
Row sums are 10, 10, and 10. Recall is 9/10 = 0.9 for class 0, 6/10 = 0.6 for class 1, and 10/10 = 1.0 for class 2. Macro recall = (0.9 + 0.6 + 1.0) / 3 = 0.8333. Micro recall = total TP / total samples = (9 + 6 + 10) / 30 = 25/30 = 0.8333. They are equal because every class has the same support (10). With equal class sizes, the macro mean and the pooled count give the same value. They differ only when class sizes differ.
Exercise
A fraud model has 3 classes: "legit" (950 samples), "card fraud" (40 samples), and "account takeover" (10 samples). It reaches 0.97 micro F1, but it detects almost none of the account takeover cases. Which average would reveal the problem, and what else should you report?
Show answer
Macro F1 would reveal it, because the account takeover class has the same weight as legit. Its F1 near 0 pulls the macro average well below the micro score. The weighted average would hide the problem, since account takeover is only 1% of the data. You should also report per-class precision, recall, and F1 (for example with classification_report or average=None), and state the zero_division setting if any class is never predicted.