FDE Times dataFDE jobs open 928▲21 Change in open roles over 7 days, like-for-like: roles from companies we started tracking this week are left outNew in 7 days 85Companies hiring 200Remote-friendly 24%Median US pay $200kTop hirer Databricks 107
中文VI

The newspaper of the Forward Deployed Engineer

Guides

Moving one threshold cut a credit model's losses with no retraining

In scikit-learn's example, gain rises from -209 to -143 once each error is priced, and that cost, not AUC, is what customers ask about.

ShareLinkedInFacebookX

In brief

  • Choosing precision or recall really means choosing which kind of error the model is optimized to avoid, so the answer lies in the client's costs.
  • The default 0.5 threshold is likely not optimal for a real problem. In scikit-learn's example, tuning the threshold by cost moves the business gain from -209 to -143.
  • AUC is for comparing models because it covers every threshold. Making a decision requires picking one threshold, and it must be tuned on data not used for training.
Horizontal bar chart comparing error cost across 1,000 hypothetical loan applications, 100 of them bad borrowers, with cost = 1 × FP + 5 × FN. Guessing that everyone is a good customer gives accuracy of 90%, recall of 0% and a cost of 500. The default 0.5 threshold gives accuracy of 93%, the highest of the three, and a cost of 310. The 0.2 threshold gives accuracy of 91.5%, recall of 75% and the lowest cost, 185, highlighted in orange. A closing box reads: choose the threshold by the cost of errors, not by accuracy. In the scikit-learn example, the gain improves from -209 to -143.
For the same model, the threshold with the highest accuracy (0.5) is not the one with the lowest error cost. Figures are illustrative, not real measurements.

In a credit-scoring example, the scikit-learn documentation keeps the model unchanged and alters a single number: the decision threshold. Business gain rises from -209 to -143, close to twice as good. No new features, no retraining.

For anyone who wants to work as an FDE, this is a skill worth practicing before meeting a client. Data scientists tend to report AUC or accuracy. Clients want to know how accurate is accurate enough, and how much money or how many staff hours each mistake costs them. This guide walks through the steps for answering that question in code, on your own laptop.

What you will do: write a cost function, sweep thresholds on a validation set, pick the best one and check it on a test set. What you need: Python 3 and any binary classifier that outputs probability scores. The code below is deliberately plain Python, with no library calls, so every calculation is visible. It is a simplified version meant for learning.

Are you choosing a metric, or a type of error?

Two definitions to keep in mind: precision is the share of positive predictions that are actually positive, and recall is the share of actual positives the model catches. Domino’s data science dictionary points out something often missed: favoring precision or recall changes which type of error the model is optimized to avoid.

Google’s ML Crash Course offers a handy rule. Favor recall when false negatives cost more than false positives. Favor precision when positive predictions must be right. On imbalanced data, do not use accuracy.

Why not accuracy? Take 1,000 loan applications, 100 of them from bad borrowers. A “lazy” model that labels everyone a good borrower scores 90% accuracy and catches no bad borrowers at all. That is why the first step is a conversation with the client, before any code.

Step 1: get the price of each error from the client

In scikit-learn’s example, “positive” means a bad borrower. Lending to a bad borrower by mistake (a false negative) costs on average five times as much as wrongly rejecting a good one (a false positive). The gain matrix therefore assigns -1 point for each FP and -5 points for each FN.

COST_FP = 1   # good borrower wrongly rejected
COST_FN = 5   # bad borrower wrongly approved

def business_cost(tp, fp, tn, fn):
    return COST_FP * fp + COST_FN * fn

Check: does the client agree with the 1:5 ratio? The number need not be exact, but it has to come from someone who knows the business. Engineers should not guess it.

Step 2: turn scores into labels

The model returns probabilities. Getting labels means choosing a probability as the cut-off, called the classification threshold. Google notes that different thresholds usually produce different counts of TP, FP, TN and FN.

def confusion_at(y_true, y_score, threshold):
    tp = fp = tn = fn = 0
    for y, s in zip(y_true, y_score):
        pred = 1 if s >= threshold else 0
        if pred == 1 and y == 1: tp += 1
        elif pred == 1 and y == 0: fp += 1
        elif pred == 0 and y == 0: tn += 1
        else: fn += 1
    return tp, fp, tn, fn

Check: tp + fp + tn + fn must equal the number of samples. If it does not, your labels contain values other than 0 and 1.

Step 3: sweep thresholds instead of trusting 0.5

The scikit-learn documentation states plainly that the default strategy (a 0.5 threshold) is likely not optimal for the problem at hand. The optimal threshold is the one at which your chosen metric is best. Here that metric is business cost.

def sweep(y_true, y_score):
    rows = []
    for i in range(5, 96, 5):
        t = i / 100
        tp, fp, tn, fn = confusion_at(y_true, y_score, t)
        precision = tp / (tp + fp) if tp + fp else 0.0
        recall = tp / (tp + fn) if tp + fn else 0.0
        rows.append((t, business_cost(tp, fp, tn, fn), precision, recall))
    return sorted(rows, key=lambda r: r[1])

To see what the output looks like, go back to the hypothetical 1,000 applications above. The figures in the table are illustrative, not measurements.

Classification approach TP / FP / FN Precision Recall Accuracy Cost
Label everyone a good borrower 0 / 0 / 100 — 0% 90% 500
Threshold 0.5 40 / 10 / 60 80% 40% 93% 310
Threshold 0.2 75 / 60 / 25 55.6% 75% 91.5% 185

The detail to notice: moving from 0.5 down to 0.2, accuracy falls while cost drops sharply. Recall rises and precision falls. That is the same kind of trade-off scikit-learn records when tuning the threshold in its credit example. Report by accuracy and you will pick the wrong threshold.

Step 4: never tune the threshold on training data

scikit-learn’s guide says never to use the same dataset to train the classifier and to tune the threshold, because it leads to overfitting. On training data the model is more confident than it really is, so a threshold found there will be too optimistic.

The safe approach is to split the data three ways: train to fit the model, validation to run sweep, and test to measure cost one final time at the chosen threshold. If cost on test is much higher than on validation, your threshold is fitting noise.

Check: run confusion_at on the test set with the chosen threshold, then compute business_cost. Put this number in the report, not the validation figure.

So what is AUC for?

AUC and the ROC curve show how well a model separates the two classes across every possible threshold. For that very reason, AUC cannot tell you where to set the threshold. It is good for comparing two models before choosing a threshold, but it is no substitute for the cost at the threshold that will actually run in production.

What this skill looks like on site with a client

Say you deploy a model that flags suspicious transactions for a bank. Operations will complain about too many false alarms. Risk management will worry about missed cases. Both are right, and the argument only ends once there is a shared number: the cost of each type of error.

The first thing to do is sit down with both sides and ask: how many times more does a missed case cost than a false alarm? Then run sweep, show them a table like the one above and let them pick the row that fits. The threshold becomes a business decision with evidence behind it, no longer a technical parameter buried in code.

On a CV or in an interview, do not just write “achieved AUC 0.9”. Write that you turned the client’s requirements into a cost function, chose the threshold on a separate validation set and cut the cost of errors by a given percentage compared with the default threshold.

When a job description asks for someone who can translate business needs into metrics, this example is ready-made proof that you can.

The best model in the notebook can still be the most expensive one in the real world if the threshold is wrong. The engineer who asks the client “which mistake costs more?” before running any code is usually the one who gets invited back.

Was this article useful?

Use with your AI assistantAsk Claude ↗Ask ChatGPT ↗
5 sources
Read next on the roadmap · Stage 6: MeasurementThe agent dashboard is green and the customer is still unhappyCompletion rate, tool errors, step count and escalations can be measured from week one and turn vague complaints into a list of fixes.