aiml

Lesson 4 of 21Module 2

Choose a decision threshold using explicit error costs

Compare three thresholds on the same validation predictions while keeping the fitted model and final test set unchanged.

Prerequisites

Complete the preceding course lessons in the shared user-return lab; keep their work/ outputs. Python functions and local CLI commands.

Preparation and term definitions

By the end, you can

  • Separate fitted probabilities from the policy threshold.
  • Compare error costs on the same validation cases.
  • Retain a selected threshold as an explicit release policy.
Runtime
Python 3.12+; local CPU
Dependencies
Python standard library and SQLite

Lab code, tests and fixtures (ZIP, 1.6 MB)Quiz check your understanding

Progress is saved in this browser.

Compare three thresholds on the same validation predictions while keeping the fitted model and final test set unchanged.

Problem

When you need this. A return probability does not by itself define a decision. Suppose the analyst marks users as expected to return when their score reaches a threshold. A false positive marks a user who does not return; a false negative misses one who does. The consequences of those mistakes may differ.

This workshop adapts the existing cost-accounting exercise to the return model. It uses illustrative costs of one unit for a false positive and three for a false negative. These are teaching assumptions, not measured revenue or a recommendation for a real retention program.

Concepts

The threshold converts a continuous score into a binary decision. Changing it can change the error counts without fitting new model weights. The model remains the candidate created by the manual workflow.

Total error cost is false positives multiplied by their declared cost plus false negatives multiplied by theirs. The comparison uses the same 48 validation examples for every threshold so that the totals refer to the same cases.

Accuracy weights every mistake equally. A cost policy can prefer a threshold with lower accuracy when it reduces the more expensive error. Neither metric measures the effect of contacting users or running an intervention.

The command inspects thresholds 0.3, 0.5 and 0.7. It reports the lowest-cost threshold for inspection and leaves the model’s declared 0.5 threshold unchanged. A later release policy must explicitly carry any chosen threshold into the prediction service.

Architecture

One validation example: user-05-day-10 has three known events and an actual return label of 1.

At threshold 0.3, this example is predicted to return. At 0.5, it is predicted not to return and contributes one false negative.

ThresholdFalse positivesFalse negativesTotal cost
0.318224
0.581141
0.751653

Total cost = false positives × 1 + false negatives × 3

One frozen validation score can yield different decisions at different thresholds. The table uses the same 48 validation cases for every policy.

Working code

Download the shared application and tests, unzip it and enter mlops-return-workflow/. Keep the same directory throughout the course. Create the environment once. This workshop uses the standard library.

Create the local environmentTerminal · bash
python3.12 -m venv .venv
source .venv/bin/activate

On PowerShell, activate with .venv\Scripts\Activate.ps1.

Complete the manual workflow first to create work/cohort.json and work/candidate.json.

Compare the threshold policies

The cost command first checks that the cohort hash stored in the model matches the cohort file. It then applies each of the three thresholds to the validation rows only.

Source excerpt: cost_reportSource · pythonDownload
def cost_report(cohort_path, model_path, false_positive=1.0, false_negative=3.0):
    for value in [false_positive,false_negative]:
        if type(value) not in (int,float) or not __import__('math').isfinite(value) or value < 0:
            raise ValueError('costs must be finite nonnegative values')
    cohort, model = w.cohort(cohort_path), w.load_model(model_path)
    if model['cohort_sha256']!=w.sha(cohort_path):
        raise ValueError('model and cohort identities differ')
    # Explicit illustrative costs: unnecessary analyst follow-up versus a missed return.
    # A real retention experiment must estimate these costs before threshold selection.
    rows=[r for r in cohort['rows'] if r['split']=='validation']
    if not rows: raise ValueError('validation rows are required')
    reports=[]
    for threshold in [0.3,0.5,0.7]:
        fp=fn=correct=0
        for row in rows:
            predicted=int(w.predict(model,row['feature_count'])['return_probability']>=threshold)
            fp+=int(predicted==1 and row['label']==0)
            fn+=int(predicted==0 and row['label']==1)
            correct+=int(predicted==row['label'])
        reports.append({'threshold':threshold,'correct':correct,'false_positive':fp,'false_negative':fn,
                        'total_cost':fp*false_positive+fn*false_negative})
    return {'split':'validation','rows':len(rows),'costs':{'false_positive':false_positive,'false_negative':false_negative},
            'units':'illustrative decision-cost units, not measured money',
            'candidates':reports,'selected_for_inspection':min(reports,key=lambda r:(r['total_cost'],r['threshold']))['threshold'],
            'model_threshold_unchanged':0.5,'final_test_used':False}
Compare the threshold policiesTerminal · bash
python adapt.py costs --cohort work/cohort.json --model work/candidate.json
Actual local application outputRecorded output · jsonDownload
{
  "split": "validation",
  "rows": 48,
  "costs": {
    "false_positive": 1.0,
    "false_negative": 3.0
  },
  "units": "illustrative decision-cost units, not measured money",
  "candidates": [
    {
      "threshold": 0.3,
      "correct": 28,
      "false_positive": 18,
      "false_negative": 2,
      "total_cost": 24.0
    },
    {
      "threshold": 0.5,
      "correct": 29,
      "false_positive": 8,
      "false_negative": 11,
      "total_cost": 41.0
    },
    {
      "threshold": 0.7,
      "correct": 27,
      "false_positive": 5,
      "false_negative": 16,
      "total_cost": 53.0
    }
  ],
  "selected_for_inspection": 0.3,
  "model_threshold_unchanged": 0.5,
  "final_test_used": false
}

In this saved run, the three costs are 24, 41 and 53 units. Threshold 0.5 has 29 correct decisions, compared with 28 at 0.3, yet 0.3 has the lower declared cost. The tradeoff follows the supplied cost matrix; it does not show that 0.3 is generally best.

Read the error counts before the totals. Moving from 0.5 to 0.3 cuts false negatives from 11 to 2 and raises false positives from 8 to 18; the lower total comes from the expensive errors it removes.

This output is from a saved local run in recorded-adaptations/; your own commands use work/. Read the actual command records. Use a fresh work directory for another attempt.

Failure cases

Run test_costs_use_validation_and_do_not_change_model and test_invalid_costs_are_refused. They check that each total equals the false positives plus three times the false negatives, that cost_report refuses a boolean, negative or NaN cost, and that the saved model file keeps the same bytes.

If the cohort file differs from the one the model was fitted on, cost_report refuses it instead of comparing the model with unrelated rows. Nothing in the command stops repeated tuning against validation; decide the candidate policy before you open final test outcomes.

Run the application failure checksTerminal · bash
python -m unittest -v test_workflow.py test_foundations.py

Running and scaling the workshop

This is an offline policy comparison. It does not send messages or deploy a new threshold. The selected policy still needs validation against the application’s real decision costs.

To compare many candidate policies, save the per-case scores once and compute every comparison from that frozen set. Keep selection results separate from the final unbiased assessment.

Key takeaways

  • The fitted probability model and the decision threshold are separate choices.
  • Compare policy costs on exactly the same cases.
  • A threshold selected during development must become an explicit release artifact.

Best practices

Write the cost assumptions before looking for a favorable threshold.

Keep the error counts next to each total cost, so you can see which mistakes drive a policy’s total.

Recompute the comparison when either declared cost changes, because the selected threshold depends on both. cost_report takes the two costs as arguments; the costs command uses its defaults of 1 and 3.

Check your understanding

Why is the most accurate threshold not the cheapest one in this fixture?

Show the explanation

The cost policy assigns three units to each false negative and one to each false positive. Threshold 0.3 produces fewer expensive false negatives, which outweighs its additional false positives under those assumptions.

What does changing the cost assumptions in this threshold comparison change?

Choose one answer, then check your reasoning.

Read the explanation

The comparison applies declared penalties to predictions at each examined threshold. It does not rewrite saved parameters or the saved 0.5 rule.

References

Written by Arjun Prabhulal.

Module 2

Run a manual workflow