Lawfare Group → Knowledge Institute → Lawfare Academy
← AI 301 — Machine Learning, Neural Networks and Language
Weeks 15–16
Model comparison, drift and deployment decisions
Learning objectives
- Explain and trace the mechanisms in model comparison, drift and deployment decisions.
- Apply the method to the worked example and changed-condition exercise.
- Identify assumptions, failure cases and the evidence needed to justify a result.
- Test the added failure-mode fixture and explain which guarantee the evidence does and does not establish.
Current study directions: use the original Academy preparation chapters, preserved teaching and complete optional worked reasoning on LawfareGroup.com. Retained attributed readings, source exercises and historical assignment directions are optional further study. This notice supersedes earlier textbook-supported directions preserved below and in historical companions. Independent subject review and observed learner testing remain pending.
A model is only one component of a deployed decision process. Inputs must be collected, transformed and checked; outputs must lead to a defined action; errors must be detected and handled. Evaluate the entire pipeline under realistic constraints. A model that improves an offline metric may add review work or fail on the cases most important to users.
Distribution shift changes the relationship between training evidence and deployment. Feature distributions can change, label prevalence can move and the relationship between inputs and outcomes can evolve. Monitor input quality and operational outcomes, but remember that labels may arrive late or only for selected cases. A shift alarm indicates a reason to investigate, not automatic proof that retraining will fix the problem.
A release needs a versioned model, preprocessing, feature schema, evaluation record and rollback plan. Keep a simple fallback for unavailable or out-of-scope inputs. Decide who can approve changes and which evidence triggers retirement. Compare total cost, including inference, data maintenance, review and incidents. If an intervention changes behavior, the data generated after deployment may differ from passive historical data. Treat release as an ongoing empirical responsibility rather than an endpoint reached by one benchmark.
Worked reasoning The guard rejects a currency or hours representation outside the documented model contract. It is only an example of input scope, not a complete drift detector. A value can pass the schema and still be unlike the training population. Log a minimal rejection reason, provide a safe fallback and review rejection patterns without exposing raw confidential records.
Extended teaching and laboratory
Evaluation describes a model under a particular data-generation and decision setting. Feature checks can reject values outside a contract, while distribution shift can occur entirely inside those ranges. Monitor data, predictions and outcomes where outcomes become available, and specify actions for suspected degradation. A model version change can alter behavior even when application code is unchanged.
A release decision should compare a baseline, candidate performance, operational costs and failure cases. Preserve a fallback, record versions and use a rollback trigger tied to observed behavior. Absence of an alarm is not proof that the system remains valid.
Worked problem A model is 94% accurate on an old process and 51% on fictional cases from a changed rule. All input values still pass the schema. Evaluate release readiness.
Step-by-step reasoning 1. The schema confirms representation and range, not stability of the target relationship. Both measurements can be valid for different mechanisms.
- Investigate whether deployment now follows the changed process. If so, the old score does not establish current usefulness.
- Compare the candidate with simple baselines on the relevant new data and inspect errors, costs and subgroup patterns.
- Delay or restrict automated use when the deployment evidence is insufficient. Use a defined fallback and collect feedback rather than silently averaging the two accuracies.
Failure-oriented laboratory: Thresholds, calibration and a held-out decision audit
A predictive score is not a decision rule. A threshold converts a score into action and therefore trades false positives against false negatives. Choose it using a development process aligned with stated costs and capacity, then evaluate it once on held-out evidence. Repeatedly adjusting the threshold after inspecting test errors consumes the independence of that test.
Precision answers how many selected positives are correct; recall answers how many actual positives were selected. Neither establishes calibrated probabilities. Calibration compares predicted probabilities with observed frequencies among comparable predictions, and its assessment requires sample size and uncertainty. A model can rank cases well while reporting unreliable probabilities.
Report counts before ratios, including abstentions and unscored cases. Subgroup or time-slice results can reveal concentrated failure, but tiny samples do not support precise claims. Monitor the consequences of decisions, not only model scores, and preserve a non-model baseline. This laboratory uses fictional labels and does not authorize decisions about real people.
Worked fixture
On a held-out synthetic set, threshold A yields TP=40, FP=10, FN=20, TN=130. Compute precision and recall. Threshold B raises TP to 50 but FP to 40.
Explain the fixture
At A, precision is 40/50 = 0.80 and recall is 40/60 ≈ 0.667. At B, recall is 50/60 ≈ 0.833 and precision is 50/90 ≈ 0.556. Higher recall does not imply universally better decisions. Compare costs and capacity using a development set rather than choosing retrospectively from the final test.
Integrated application: implementation, debugging and local deployment
The complete service-company project is now part of this unit’s applied work. It supplies an inspectable browser interface, HTTP server, persistent SQLite ledger, transaction tests, export recovery, permission-scoped retrieval and a separate synthetic logistic evaluation pipeline. Begin with its actual test suite, then trace one user request from UI to storage and back. The README distinguishes the local teaching environment from a production deployment.
Course-specific investigation
Run evaluate, inspect gradient updates, and reconcile every held-out count. Add calibration bins with counts and proper handling of empty bins. Keep threshold selection on development data and report a fixed test result once.
What the evidence must establish
Precision, recall, calibration and decision cost answer different questions. Preserve an untouched evaluation boundary; do not revise the threshold after inspecting test errors and continue calling that test independent.
Keep a reproducibility log with Python version, launch command, fixture, expected result, observed result and explanation of any discrepancy. Introduce one deliberate defect and show the corresponding failing test before restoring the implementation. Passing an existing test without explaining its boundary is insufficient. The integration project remains optional practice rather than a mandatory capstone submission.
Orion: compare complete learning procedures before choosing a release
Orion is a fictional service operator considering a repeat-visit predictor. At request acceptance, it has estimated hours, customer history available before that time and a short request description. The label is a repeat visit within seven days. Intended deployment concerns new customers next quarter. A final-resolution field and the eventual number of collection attempts appear in a retrospective export. All records, costs and probabilities below are instructional stipulations; no real customer decision is authorized.
Prepare one reproducible dossier that connects task definition, classical and neural fitting, a manual gradient check, decision metrics, probability evaluation and a bounded release recommendation. Explain how customer grouping, chronology and label maturity affect the split. Specify the training-only text vocabulary and numerical transformations. Preserve the supplied neural reference's actual fixed-partition result and changed-mechanism failure as a separate synthetic experiment; do not pass off the following hand record as its output.
For this additional eight-case development record, outcomes are [0,0,0,0,1,1,1,1]. A constant baseline predicts probability .5. A classical candidate supplies [.1,.2,.4,.7,.3,.6,.8,.9]; a neural candidate supplies [.1,.3,.6,.8,.4,.7,.9,.9]. Compare positive-at-threshold policies .5 and .75. A false positive costs two units and a missed positive ten. The batch can support four reviews. Calculate every confusion count, precision, recall, error cost and Brier loss. Interpret whether this record supports a final release. Then change the error costs to ten per false positive and two per missed positive, retaining all probabilities and capacity.
Include a fitting calculation using the existing logistic performance data x=[−1,−2/3,−1/3,1/3,2/3,1], y=[0,0,0,1,1,1]. Begin b=w=0, use mean binary cross-entropy and take one simultaneous rate-.3 update. Supply a gradient-check plan and identify which variables and loss conventions the published neural reference actually checks. For text generation, separately calculate a two-token likelihood with conditional probabilities .5 and .25 and explain why it cannot verify a factual sentence.
Complete dossier and changed-cost reasoning
Information and partition.
Remove final resolution and eventual collection attempts from an acceptance-time predictor. Fit vocabulary, imputation and scaling within training folds. Keep a customer from crossing training and evaluation when testing new customers, enforce the chronological cutoff, and exclude labels whose seven-day observation window is not complete. Record whether a customer's earlier eligible history is permissible under the intended new-customer definition. Reserve the final evaluation after choosing the full pipeline, threshold and review process. A random seed cannot repair an invalid information boundary.
Baseline.
At threshold .5 the constant .5 baseline predicts all cases positive: TP=4, FP=4, FN=0, TN=0. Accuracy=.5, precision=.5, recall=1, error cost=8 and eight reviews. It is infeasible at capacity four. At threshold .75 it predicts all negative: TP=0, FP=0, FN=4, TN=4, accuracy=.5, recall=0 and cost 40. Precision is undefined because there are no alerts; record an explicit empty-denominator state. The baseline Brier loss is .25 at either threshold because the probability forecast did not change.
Classical candidate.
At .5, TP=3, FP=1, FN=1, TN=3: accuracy=.75, precision=.75, recall=.75, four alerts and cost 12. At .75, TP=2, FP=0, FN=2, TN=4: accuracy=.75, precision=1, recall=.5, two alerts and cost 20. The identical accuracy hides a consequential difference under these costs. Squared probability errors sum to 1.4, giving Brier loss 1.4/8=.175. Brier loss evaluates probabilities; it is unchanged by moving the action threshold.
Neural candidate.
At .5, TP=3, FP=2, FN=1, TN=2: accuracy=.625, precision=.6, recall=.75, five alerts and cost 14. This policy exceeds capacity. At .75, TP=2, FP=1, FN=2, TN=3: accuracy=.625, precision=2/3, recall=.5, three alerts and cost 22. Squared probability errors sum to 1.57, giving Brier loss .19625. A neural family name does not entitle the candidate to win: on this record the feasible classical .5 policy has lower stated cost than the other feasible candidates. Selecting it using these cases makes them development evidence, rather than a final independent validation.
Reliability and fitting.
For the classical probabilities, bins [0,.5) and [.5,1] contain four cases each. Mean forecasts are .25 and .75, while observed positive rates are .25 and .75. This exact agreement in two coarse bins on eight constructed cases does not prove calibration, subgroup reliability or transport to another population. Finer bins can expose other patterns and smaller counts. At logistic zero initialization, each p=.5. The intercept gradient is zero and slope gradient−1/3, so rate .3 gives b=0,w=.1. The updated probabilities are approximately [.475021,.483340,.491667,.508333,.516660,.524979], with mean loss .660462, below the initial ln 2≈.693147. Reconcile these numbers independently before interpreting the step. Perturb each parameter at several finite, nonsaturated states and compare centered numerical differences with the analytic gradient, keeping the objective and reduction unchanged. The published reference checks two logistic slope coordinates; it does not by that fact gradient-check every hidden-layer parameter. Its nonlinear training outcome remains a separate experiment.
Language and release.
The stipulated joint token probability is .125, total negative log-likelihood ln 8 and perplexity √8 under this two-token definition. It measures a model's probability assignment, not truth or source support. Evaluate retrieved evidence and the generated claim separately. Freeze the selected prediction pipeline and policy before fresh evaluation; report case counts, uncertainty, subgroup/time results, review labor and delayed labels. Establish fallback and rollback triggers and preserve optimizer/preprocessing/model versions. This small constructed dossier supplies a reasoning model, not a real deployment approval.
Changed costs.
With FP cost 10 and FN cost 2, the classical .5 policy costs 12 and .75 costs 4. The neural .5 policy costs 22 but remains infeasible; neural .75 costs 14. The all-negative baseline costs 8 and is feasible. Under the changed stipulated criteria the classical .75 policy is the least costly of these feasible choices. The probabilities and Brier losses did not change; the utility and action choice did. A different review intervention, ranking policy or capacity would require its own measured counts.
Optional 20-point rubric.
Award 0–4 points for each: (1) task, feature timing and group/time/label boundaries; (2) correctly derived fitting and gradient-check scope; (3) all baseline/classical/neural counts, denominators, costs and capacity; (4) probability loss, bin counts and source-support limitations; (5) changed-cost recommendation, untouched final evaluation and reproducibility/fallback plan. Four means complete correct reasoning with explicit assumptions; three a correct conclusion with a limited omission; two a material reasoning gap; one an unsupported assertion; zero absent or contradictory work. Independent written comparison is optional and does not record learner completion or establish observed competence.
Apply the idea
A model is 94% accurate on an old process and 51% on fictional cases from a changed rule. All input values still pass the schema. Evaluate release readiness.
A monitored model has unchanged feature averages but worse outcomes. What should the investigation include?
Additional laboratory — Assume development-time costs of 2 per false positive and 10 per false negative. Calculate each rule’s illustrative error cost, then explain why selecting on this held-out set invalidates its role as a final unbiased comparison.
Complete-application investigation: Run evaluate, inspect gradient updates, and reconcile every held-out count. Add calibration bins with counts and proper handling of empty bins. Keep threshold selection on development data and report a fixed test result once.
Read the worked reasoning
Check conditional relationships, subgroup composition, label definition and delay, data-pipeline changes and decision thresholds. Equal marginal averages can hide changed relationships or offsetting subgroup shifts. Reproduce the evaluation with versioned inputs and targets, and do not dismiss outcome degradation because one feature summary is stable.
Additional laboratory model — A has cost 10×2 + 20×10 = 220; B has cost 40×2 + 10×10 = 180. Under those fixed costs B looks preferable, but choosing it after inspecting this test makes the score part of selection. Use fresh held-out evidence or disclose the reuse; do not call the reused result an untouched final test.
Application reasoning model: Precision, recall, calibration and decision cost answer different questions. Preserve an untouched evaluation boundary; do not revise the threshold after inspecting test errors and continue calling that test independent.
Check understanding
What is required beyond a strong offline score?
- A validated workflow, monitored outcomes and a recovery policy
Feedback
The system must remain useful under actual operating conditions.
- Immediate unrestricted deployment
Feedback
Scope and consequences still require a bounded deployment decision.
- A promise that distributions will remain fixed
Feedback
Future data can change despite strong historical performance.
Further reading
Current study directions: use the original Academy preparation chapters, preserved teaching and complete optional worked reasoning on LawfareGroup.com. Retained attributed readings, source exercises and historical assignment directions are optional further study. This notice supersedes earlier textbook-supported directions preserved below and in historical companions. Independent subject review and observed learner testing remain pending.
Use the preserved original investigation and connected Academy preparation/application below. Compare your reasoning with its optional complete model. Historical source directions remain in immutable edition4.
- Original on-site preparation/application — Orion: compare complete learning procedures before choosing a release
- 4.7. Environment and Distribution Shift Open the notebook in SageMaker Studio Lab
- 19.1. What Is Hyperparameter Optimization? Open the notebook in SageMaker Studio Lab
- 3.4. Metrics and scoring: quantifying the quality of predictions
- 11. Model persistence
- 10.1. Strategies to scale computationally: bigger data
- Primary documentation for Thresholds, calibration and a held-out decision audit
- Academy — runnable synthetic lab kit and instructions
- Academy — complete application, source, integration tests and local deployment guide