Cost-Aware Fraud Model Comparison
Arrays & HashingAuto-graded · 13 test casesLast updated
Compares classification models using business costs, derives optimal decision thresholds, and identifies the most economical model.
You are building a fraud detection system for an online marketplace. Each order must either be flagged for manual review or allowed to proceed automatically.
You have evaluated two candidate models on a validation dataset. For each model, you know the confusion matrix at a fixed operating point: true positives (TP), false positives (FP), false negatives (FN), and true negatives (TN).
The business incurs these costs:
- Review cost: paid for every flagged order (legitimate or fraudulent)
- Friction cost: additional cost when a legitimate order is incorrectly flagged
- Missed fraud cost: loss incurred when a fraudulent order is not caught
Your task is to compute standard classification metrics, determine the cost-optimal probability threshold for flagging orders, calculate the expected cost per order for each model, and identify which model minimizes cost.
Write a function that takes:
models: a list of confusion matrices, where each matrix is[TP, FP, FN, TN]costs: a dictionary with keys"review","friction", and"missed_fraud"(all positive floats)base_rate: the true prevalence of fraud in the population (between 0 and 1)
Return a dictionary containing:
"models": a list of dictionaries, one per input model, each with:"name":"A"for the first model,"B"for the second, or the zero-based index as a string for others"precision": TP / (TP + FP), or 0.0 if no positive predictions"recall": TP / (TP + FN), or 0.0 if no actual positives (also equals TPR)"f1": harmonic mean of precision and recall, or 0.0 if both are zero"fpr": FP / (FP + TN), or 0.0 if no actual negatives"tpr": same as recall"expected_cost_per_order": total cost divided by total orders
"base_rate": the input base rate (echoed back)"cost_optimal_probability_threshold": the breakeven probability above which flagging is cheaper than passing, computed as(review + friction) / (missed_fraud + friction)"lowest_cost_model":"A","B", or index string of the model with minimum expected cost per order, orNoneif no models provided
Constraints
- 1 ≤ number of models ≤ 100
- All confusion matrix entries are non-negative integers
- TP + FP + FN + TN ≥ 1 for each model
- All costs are positive floats
- 0 < base_rate < 1
- Return floating-point values with full precision (do not round)
Examples
Example 1
Input: compare_fraud_models([[490, 4900, 210, 94400], [560, 8400, 140, 90900]], {'review': 3, 'friction': 1, 'missed_fraud': 120}, 0.007)
Output: {'models': [{'name': 'A', 'precision': 0.09090909090909091, 'recall': 0.7, 'f1': 0.16091954022988506, 'fpr': 0.04934541792547835, 'tpr': 0.7, 'expected_cost_per_order': 0.4627}, {'name': 'B', 'precision': 0.0625, 'recall': 0.8, 'f1': 0.11594202898550725, 'fpr': 0.08459214501510574, 'tpr': 0.8, 'expected_cost_per_order': 0.5208}], 'base_rate': 0.007, 'cost_optimal_probability_threshold': 0.03305785123966942, 'lowest_cost_model': 'A'}
Hints
Hint 1
The expected cost per order is the sum of (flagged orders × review cost) + (false positives × friction cost) + (false negatives × missed fraud cost), all divided by total orders.
Hint 2
The cost-optimal threshold comes from comparing the cost of flagging versus passing an order with probability p of being fraud. Set them equal and solve for p.
Hint 3
A model with higher recall is not necessarily better—compare the models strictly on expected cost per order under the given cost structure.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires translating classification performance into business impact through a cost model, then identifying the most economical decision rule.
Step 1: Compute standard metrics from confusion matrices
For each model, extract the four counts (TP, FP, FN, TN) and compute:
- Precision = TP / (TP + FP): what fraction of flagged orders are actually fraudulent
- Recall (TPR) = TP / (TP + FN): what fraction of fraudulent orders are caught
- F1 = 2 × precision × recall / (precision + recall): harmonic mean balancing the two
- FPR = FP / (FP + TN): false alarm rate among legitimate orders
Handle division by zero by returning 0.0 when denominators are zero.
Step 2: Calculate expected cost per order
The total cost for a model at its operating point is:
- Every flagged order (TP or FP) incurs the review cost
- Every false positive adds an additional friction cost (wasted review effort, customer annoyance)
- Every false negative (missed fraud) incurs the full fraud loss
So: total_cost = TP × review + FP × (review + friction) + FN × missed_fraud
Divide by the total number of orders to get cost per order. This is the primary decision metric.
Step 3: Derive the cost-optimal threshold
For an order with true fraud probability p, compare the expected cost of each action:
- Flag it: pay review cost for certain, plus friction cost with probability (1 − p)
→ Expected cost =
review + (1 − p) × friction - Let it pass: incur fraud loss with probability p
→ Expected cost =
p × missed_fraud
Flag when review + (1 − p) × friction < p × missed_fraud
Rearranging: review + friction < p × (missed_fraud + friction)
Therefore: p* = (review + friction) / (missed_fraud + friction)
This is the breakeven probability. Flag any order with fraud probability above this threshold. Note that this threshold depends only on the cost structure, not on the base rate or the models' calibration.
Step 4: Identify the lowest-cost model
Compare the expected cost per order across all models and select the one with minimum cost. Name the first model "A", the second "B", and any additional models by their zero-based index.
Complexity
- Time: O(M) where M is the number of models. Each model requires constant-time arithmetic.
- Space: O(M) to store the output dictionary for each model.
Solution Code
from typing import List, Dict
def compare_fraud_models(models: List[List[int]], costs: Dict[str, float], base_rate: float) -> Dict[str, object]:
review = costs["review"]
friction = costs["friction"]
missed = costs["missed_fraud"]
result = []
for index, row in enumerate(models):
tp, fp, fn, tn = row
total = tp + fp + fn + tn
precision = tp / (tp + fp) if tp + fp else 0.0
recall = tp / (tp + fn) if tp + fn else 0.0
f1 = (2.0 * precision * recall / (precision + recall)
if precision + recall else 0.0)
fpr = fp / (fp + tn) if fp + tn else 0.0
expected_cost = (
tp * review
+ fp * (review + friction)
+ fn * missed
) / total if total else 0.0
result.append({
"name": "A" if index == 0 else "B" if index == 1 else str(index),
"precision": precision,
"recall": recall,
"f1": f1,
"fpr": fpr,
"tpr": recall,
"expected_cost_per_order": expected_cost
})
threshold = (review + friction) / (missed + friction)
best_index = min(
range(len(result)),
key=lambda i: result[i]["expected_cost_per_order"]
) if result else None
return {
"models": result,
"base_rate": base_rate,
"cost_optimal_probability_threshold": threshold,
"lowest_cost_model": (
"A" if best_index == 0 else
"B" if best_index == 1 else
str(best_index) if best_index is not None else None
)
}