Precision and Recall from a Confusion Matrix
Implement precision_recall(y_true, y_pred, average) returning [precision, recall] as a list of two floats.
average="binary": the positive class is label1.average="macro"andaverage="micro"as defined above.
No scikit-learn. Build the counts yourself.
Examples
Binary: 3 TP, 2 FP, 1 FN
- Input
- precision_recall([1, 0, 1, 1, 0, 0, 1, 0], [1, 0, 0, 1, 0, 1, 1, 1], "binary")
- Output
- [0.6, 0.75]
Three classes, macro average (the worked example)
- Input
- precision_recall([0, 1, 2, 2, 1, 0, 2, 1, 0], [0, 2, 2, 2, 1, 0, 1, 1, 2], "macro")
- Output
- [0.722222, 0.666667]
Three classes, micro average equals accuracy
- Input
- precision_recall([0, 1, 2, 2, 1, 0, 2, 1, 0], [0, 2, 2, 2, 1, 0, 1, 1, 2], "micro")
- Output
- [0.666667, 0.666667]
Hints
Hint 1
Join the pieces along the feature axis, not the row axis.
Hint 2
Watch for this: divided by zero when a class is never predicted.
Requirements
y_true: Integer labels, shape (n,)y_pred: Integer labels, shape (n,): "binary" (positive class is 1), "macro", or "micro"
Return [precision, recall] as floats. Zero denominators give 0.0.
Constraints
Allowed library: NumPy only
Time limit: 200 ms, Memory: 64 MB
Where this shows up
8 employers weight this skill
3 AI product companies, 2 frontier labs, 1 health and bio company, 1 big tech firm, 1 autonomy company. Top match scores 93.
import numpy as np
def precision_recall(y_true, y_pred, average: str = "binary") -> list:
"""
Precision and recall from predicted and true labels.
Args:
y_true: Integer labels, shape (n,)
y_pred: Integer labels, shape (n,)
average: "binary" (positive class is 1), "macro", or "micro"
Returns:
[precision, recall] as floats. Zero denominators give 0.0.
"""
y_true = np.asarray(y_true)
y_pred = np.asarray(y_pred)
# YOUR CODE HERE
pass