Skip to content
RED SAGSkills

Binary Classifier Metrics

A fraud model labels each transaction 1 (fraud) or 0 (legitimate). Given the true labels actual and the model output predicted (same length), build the confusion matrix and its metrics.

tp counts actual 1 / predicted 1, fp actual 0 / predicted 1, fn actual 1 / predicted 0, tn actual 0 / predicted 0. Then accuracy = (tp + tn) / total, precision = tp / (tp + fp), recall = tp / (tp + fn) and f1 = 2 * precision * recall / (precision + recall). Any ratio whose denominator is 0 is 0. Compute f1 from the unrounded precision and recall.

Return { tp, fp, fn, tn, accuracy, precision, recall, f1 } with the four ratios rounded to 4 decimals (Math.round(x * 10000) / 10000).

Example 1

Input: actual = [1,0,1,1,0], predicted = [1,1,0,1,0]
Output: {"tp":2,"fp":1,"fn":1,"tn":1,"accuracy":0.6,"precision":0.6667,"recall":0.6667,"f1":0.6667}
Explanation: tp 2, fp 1, fn 1, tn 1.

Example 2

Input: actual = [0,0,0], predicted = [0,0,0]
Output: {"tp":0,"fp":0,"fn":0,"tn":3,"accuracy":1,"precision":0,"recall":0,"f1":0}

Constraints

  • 1 <= actual.length == predicted.length <= 10^5
  • Every label is 0 or 1
Hint 1

Count the four cells in one loop.

Hint 2

Write a ratio(a, b) helper that returns 0 when b is 0.

Good practice for: Data Scientist, Machine Learning Engineer, AI Engineer (LLM & Generative AI), MLOps Engineer, Data Engineer, Automation Test Engineer

Run checks your code on 3 sample tests. Submit runs all 7 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.