821. Weigh recall over precision with the F-beta score
Why it matters Safety classifiers and LLM guardrails are often tuned on F2 because a missed harmful output costs more than an extra flag.
F1 treats precision and recall equally. When a missed case costs more than a false alarm (fraud, toxic content, medical triage), teams report F2, which weighs recall more; F0.5 does the opposite.
Write fbeta(y_true, y_pred, beta) for binary 0/1 lists. With tp, fp, fn counts, precision = tp / (tp + fp) and recall = tp / (tp + fn), each 0 when its denominator is 0. Return (1 + beta^2) * precision * recall / (beta^2 * precision + recall), or 0.0 when that denominator is 0.
def fbeta(y_true, y_pred, beta)Example 1
Input: fbeta([1, 1, 0, 0], [1, 0, 1, 0], 1.0)
Output: 0.5
Example 2
Input: y_true = [1, 1, 1, 0], y_pred = [1, 0, 0, 0], beta = 2.0
Output: 0.384615
Example 3
Input: y_true = [1, 1, 1, 0], y_pred = [1, 0, 0, 0], beta = 0.5
Output: 0.714286
Constraints
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 5 tests to be accepted.
Hint 1
Count tp, fp and fn first.
Hint 2
Guard every division: no predicted positives means precision 0, no true positives means recall 0.
Common mistakes
- Putting beta^2 on recall instead of precision in the denominator, which flips F2 and F0.5.
- Dividing by zero when there are no positives.
Understand the idea
F-beta is a weighted harmonic mean of precision and recall in which recall counts beta times as much. beta = 1 gives F1.
one true positive, no false positives, two misses. Precision 1, recall 1/3. F2 = 5 x 1 x (1/3) / (4 x 1 + 1/3) = 0.385, while F0.5 = 1.25 x (1/3) / (0.25 + 1/3) = 0.714.
F_beta = (1 + b^2) P R / (b^2 P + R)