Forward Deployed EngineeringAI EngineeringClassification Evaluation
You're building a classifier that flags risky contract clauses. Do you optimize for precision or recall?
Question 25 of 73 · Updated
On this page
- Interview-ready answer
- 1. Define the business objective before the metric
- 2. Understand the confusion matrix
- 3. Numerical example: why accuracy alone is misleading
- 4. Translate asymmetric error costs into decisions
- 5. Threshold tuning and calibration
- A constrained operating point
- 6. Tested Python implementations
- 7. Human review and severity-aware triage
- 8. Data and evaluation design
- 9. Production engineering and monitoring
- 10. Practical FDE interview scenario
- Likely interviewer follow-ups
Interview-ready answer#
I would usually prioritize recall for a classifier that assists lawyers or contract reviewers, because missing a genuinely risky clause can expose the customer to significant legal or financial harm. A false positive generally creates additional review work; a false negative can leave a consequential obligation, liability or exception undiscovered.
However, I would not optimize recall in isolation. Flagging every clause achieves perfect recall on a dataset containing positives but may overwhelm reviewers and make the system unusable. I would agree with the customer on what constitutes risk, define the cost of missed risks and unnecessary reviews, and select an operating threshold that satisfies a minimum recall requirement while maintaining acceptable precision and review capacity.
For example, I might require particularly high recall for uncapped liability or other critical customer-defined risk categories, while using a different threshold for lower-severity issues. Ambiguous or out-of-distribution clauses should go to qualified human review. A low-risk prediction should not be treated as a legal clearance.
I would validate this approach on a held-out, expert-labeled dataset split by contract rather than randomly by clause. I would measure precision, recall, per-category misses, calibration, reviewer workload and end-to-end review outcomes, then monitor drift and adjust thresholds using new validated data. The classifier is a decision-support tool, not a substitute for legal judgment.
1. Define the business objective before the metric#
The positive class is a clause that warrants flagging under the customer's applicable risk policy. That definition depends on contract type, negotiating position, jurisdiction, related provisions, effective policy and the customer's risk appetite. A clause is not universally risky merely because it contains a particular word.
Work with qualified domain experts to define a rubric covering risk categories, severity, exceptions, contextual evidence and uncertain cases. Separate document extraction failures from classification errors. If a relevant clause is omitted during parsing, a classifier that correctly labels every extracted clause can still miss the underlying contract risk.
For an initial deployment I would explicitly define:
- The review task and which contract categories are in scope.
- What the model flags, what it does not decide, and who makes final decisions.
- The severity and expected consequences of a miss or an unnecessary flag.
- The available reviewer capacity and turnaround requirements.
- The minimum acceptable critical-risk recall and other launch gates.
The right objective is effective risk triage within business constraints, not maximum performance on an isolated statistical metric.
2. Understand the confusion matrix#
Treat risky clauses as the positive class.
| Actual class | Flagged | Not flagged |
|---|---|---|
| Risky | True positive (TP): correctly surfaced for review | False negative (FN): risk missed |
| Not risky | False positive (FP): unnecessary review | True negative (TN): correctly not flagged |
Precision = TP / (TP + FP)
Recall = TP / (TP + FN)
Specificity = TN / (TN + FP)
False-negative rate = FN / (TP + FN) = 1 − recall.
Precision answers: of the clauses flagged, how many actually warrant review? Recall answers: of the genuinely risky clauses, how many did the system identify?
F1 = 2 × precision × recall / (precision + recall), when defined. F-beta weights recall more strongly than precision when beta > 1. For example, F2 can be a useful secondary summary for recall-oriented classification, but neither F1 nor F2 directly represents a customer's legal risk, error costs or queue capacity.
Handle undefined denominators explicitly. A model that produces no flags has no defined precision under this mathematical convention; a test slice with no positive examples has no defined recall. Report these cases, sample counts and the metric library's chosen convention rather than treating missing evidence of performance as perfect performance.
3. Numerical example: why accuracy alone is misleading#
Consider 1,000 fictional clauses, of which 50 are genuinely risky. A classifier produces the following results at two illustrative operating points.
| Metric | Lower threshold | Higher threshold |
|---|---|---|
| TP | 48 | 35 |
| FP | 100 | 15 |
| FN | 2 | 15 |
| TN | 850 | 935 |
| Precision | 32.43% | 70.00% |
| Recall | 96.00% | 70.00% |
| Accuracy | 89.80% | 97.00% |
| Review queue | 148 | 50 |
The higher threshold looks attractive by accuracy and precision, but misses 15 risky clauses rather than two. The lower threshold surfaces more genuine risks at the cost of 98 additional reviews. The comparison assumes the same labeled population and no separate abstention route.
A trivial classifier that predicts every clause as non-risky would achieve 95% accuracy while missing every risky clause. This is why accuracy alone is particularly misleading for rare risk categories.
These numbers are synthetic teaching examples, not observed customer data.
4. Translate asymmetric error costs into decisions#
Suppose missing a risky clause incurs an illustrative expected loss of 1,000 cost units, while an unnecessary review incurs 10 cost units.
For the example above:
| Operating point | Illustrative total loss |
|---|---|
| Lower threshold | 2 × 1,000 + 100 × 10 = 3,000 |
| Higher threshold | 15 × 1,000 + 15 × 10 = 15,150 |
This simplified model excludes costs shared by all reviewed clauses, downstream human errors, severity variation and other workflow consequences. In a real deployment, estimate costs with customer stakeholders and include reviewer time, escalation, potential delays and risk severity. Some critical obligations are better modeled as hard safety requirements rather than monetary trade-offs.
If p is a calibrated probability that a clause is risky, and the only costs are for flagging a non-risky clause and for not flagging a risky clause, then:
Expected loss if flagged = (1 − p) ×
Expected loss if not flagged = p ×
Under those assumptions, flag when p ≥ / ( + ). With the example costs, the threshold is about 0.0099. This result illustrates the asymmetry; it is not a recommended legal-production threshold. Review capacity, imperfect human review, uncertainty, unequal costs, and miscalibration can materially change the optimal policy. Raw model scores need not be probabilities.
5. Threshold tuning and calibration#
A classifier may output a continuous risk score. A threshold converts that score into a flag. For a fixed scored population and a greater-than-or-equal rule, lowering the threshold cannot reduce recall because the predicted positive set only grows. Precision often falls but is not guaranteed to move monotonically across every threshold on finite data.
Use a validation split to select the threshold. Plot the precision-recall curve and estimate reviewer workload at candidate thresholds. For rare positives, precision-recall analysis is often more informative about the flagging workload than ROC-AUC alone. ROC-AUC still provides a complementary ranking measure. Report the positive prevalence alongside average precision; the random-ranking baseline is related to prevalence.
If scores are used as probabilities, assess reliability diagrams and calibration metrics such as Brier score. Fit any calibrator on data separated from model training and final test evaluation. Choose between methods such as sigmoid or isotonic calibration using appropriate validation and sample size. Calibration does not turn a classifier into an authoritative legal decision-maker.
Select thresholds on validation data and freeze them before evaluating the final holdout. Do not repeatedly tune against the final test set.
A constrained operating point#
A practical selection rule could be:
- Require at least the customer-agreed recall for critical risks.
- Respect the maximum review queue capacity over the relevant period.
- Among feasible thresholds, minimize estimated loss or maximize another agreed utility.
- If no threshold satisfies the constraints, do not quietly relax the critical-risk gate. Improve the model or parsing, change the review workflow, add review capacity, or restrict launch scope.
For multi-label contract classification, different categories may require separate thresholds. A single clause may trigger several flags. Estimate workload after deduplicating flags into actual review tasks, and monitor both per-category performance and the overall queue.
6. Tested Python implementations#
The first function calculates binary confusion-matrix counts and precision/recall for a fixed threshold. The second selects a cost-minimizing feasible threshold under a recall constraint and a review capacity.
PYTHONimport math def metrics(y, scores, threshold): if len(y) != len(scores) or not y or any(v not in (0, 1) for v in y): raise ValueError('Invalid labels or lengths') if not 0 <= threshold <= 1 or any(not 0 <= s <= 1 for s in scores): raise ValueError('Expected scores and threshold in [0, 1]') tp = fp = tn = fn = 0 for actual, score in zip(y, scores): pred = score >= threshold tp += int(actual == 1 and pred) fp += int(actual == 0 and pred) tn += int(actual == 0 and not pred) fn += int(actual == 1 and not pred) return {'tp': tp, 'fp': fp, 'tn': tn, 'fn': fn, 'precision': tp/(tp+fp) if tp+fp else None, 'recall': tp/(tp+fn) if tp+fn else None} def choose_threshold(y, scores, min_recall, capacity, c_fn, c_fp): if not 0 <= min_recall <= 1 or capacity < 0 or any( not math.isfinite(c) or c < 0 for c in (c_fn, c_fp) ): raise ValueError('Invalid constraints') metrics(y, scores, 0) options = [] for threshold in sorted(set(scores) | {0.0, 1.0}): m = metrics(y, scores, threshold) if (m['recall'] is not None and m['recall'] >= min_recall and m['tp'] + m['fp'] <= capacity): loss = c_fn*m['fn'] + c_fp*m['fp'] options.append((loss, -threshold, m)) if not options: return None loss, neg_threshold, m = min(options, key=lambda x: x[:2]) return {'threshold': -neg_threshold, 'loss': loss, **m} result = choose_threshold( [1, 0, 1, 0, 0], [.9, .8, .4, .3, .1], min_recall=1, capacity=3, c_fn=10, c_fp=1 ) print(result) # threshold=0.4, loss=1, tp=2, fp=1, tn=2, fn=0 # precision=0.6666666666666666, recall=1.0
The inputs are nonempty sequences of binary labels and finite numeric scores in [0,1], an integer nonnegative review capacity, and nonnegative finite costs. The threshold domain is [0,1], with scores equal to the threshold flagged. All distinct observed prediction sets attainable in that domain are represented by observed scores or endpoints; the explicit all-negative policy is not representable if a score equals 1. A production optimizer can include an explicit no-flag action if needed. A minimum recall constraint cannot be verified on a validation set with no positives; the helper returns no feasible result in that case.
This simple reference implementation scans n examples for each of u distinct candidate thresholds, taking O(nu + u log u) time and O(u) auxiliary space. A more scalable implementation sorts by score once and accumulates counts in tied-score groups in O(n log n) time. Never split tied scores implicitly when the deployed decision rule is a scalar threshold.
Local verification: The exact functions were executed against independent set-based reference calculations. All 21,764 checks passed: 21,756 exhaustive metric/threshold-selection combinations over binary label sequences and scores drawn from {0, 0.5, 1} for lengths one through four, plus eight invalid-input tests. The explicit five-clause example also executed successfully. Tests cover undefined precision/recall, tied scores, zero capacity, infeasible constraints and cost-minimizing tie-breaking. They validate the metric and selection logic on synthetic data, not the predictive quality or legal reliability of a trained classifier.
7. Human review and severity-aware triage#
Design the workflow to support qualified reviewers rather than automate contract approval. A flag should identify the source clause, category, relevant evidence, applicable policy and uncertainty. It should not silently rewrite a contract or recommend signing.
Critical deterministic policy checks may supplement model predictions when rules are reliable. For ambiguous cases, low confidence, unfamiliar contract types or parsing failures, use an explicit review or abstention route. An unflagged clause is not certified safe; periodically audit unflagged cases to estimate misses. Keep approved human review for contracts where the consequences demand it.
For high-volume review, prioritize the queue by severity and urgency, not only model score. Do not suppress critical cases merely to improve dashboard precision or meet a throughput target. If capacity is inadequate, report the risk and adjust scope or staffing.
8. Data and evaluation design#
A credible evaluation dataset needs domain-expert annotations for both positive and negative examples, with an agreed risk rubric. Include rare critical risks, amended contracts, negotiated exceptions, multiple contract types, long clauses, references to other sections, scanned pages, and ambiguous examples. Preserve the relevant surrounding context and record annotation disagreement. Resolve uncertainty with qualified reviewers or label it separately.
Split by contract, template family, customer or time period as appropriate to avoid leakage from near-identical clauses. Use training data for model fitting, validation data for calibration and threshold tuning, and a held-out test set for final acceptance. Avoid overrepresenting easy negatives or synthetically generated positives as a substitute for representative risk cases.
| Evaluation metric | Why it matters |
|---|---|
| Per-category and severity recall | Reveals missed risks hidden by an aggregate score |
| Precision and review rate | Measures usefulness and actual workload |
| PR curve and average precision | Evaluates ranking across thresholds for rare positive cases |
| Document-level risk coverage | Detects misses in entire contracts, including upstream extraction errors |
| Calibration and uncertainty | Supports meaningful score-based triage |
| Reviewer agreement and final decisions | Measures label quality and downstream workflow performance |
| Turnaround, cost and rework | Tests whether the system improves the actual review process |
Report absolute counts and confidence intervals, especially for rare critical risks. Because clauses within one contract are correlated, consider uncertainty estimation at the contract or other independent sampling-unit level. Zero observed misses in a small evaluation set does not establish zero production risk.
Evaluate the full workflow: ingestion, context assembly, prediction, thresholding, review and recorded resolution. Use shadow testing before changing an existing review process. Expert review of a representative sample of unflagged clauses helps estimate missed risks; reviewing only model flags creates selective-label bias.
9. Production engineering and monitoring#
Version the extraction pipeline, policy rubric, model, calibration and thresholds. Store source references and model decisions in an access-controlled audit trail, including enough context to reproduce the decision. Enforce contract-level authorization before retrieval or processing. Contract text is confidential customer data; use approved storage, processing endpoints, retention and logging practices.
Monitor input distribution, score distribution, flag rate, reviewer capacity, category-level errors, extraction failures and changes to policy or templates. A rising flag rate may indicate actual risk changes, drift, model degradation or a new document type. Investigate before changing a threshold.
Deploy with a restricted pilot, explicit safety gates and a rollback plan. If the system encounters unsupported contract categories, material extraction errors, a severe recall regression or overloaded review queues, route to the existing manual process rather than silently allowing unreviewed decisions.
Feedback from lawyers is valuable, but do not automatically train on every reviewer action. Verify labels, account for selection bias, preserve a stable evaluation set and version new releases. Ensure reviewer corrections are attributed and audited.
10. Practical FDE interview scenario#
Imagine a customer reviewing supplier agreements where a missed uncapped-liability provision could have greater consequences than an unnecessary review of a standard clause. I would first agree on the risk taxonomy and policy with their legal team, then build a representative dataset containing positive examples and difficult non-risk examples such as clauses with explicit exceptions.
I would start with a high-recall candidate flagger, separately measure critical-category misses and reviewer workload, and use qualified reviewers to resolve uncertain cases. If the threshold that meets critical recall produces too many review tasks, I would investigate whether better document context, stronger features, improved calibration, severity-aware rules or additional review capacity can resolve the conflict.
The success criterion is not just that the model flags more clauses. It is that the customer finds consequential risks reliably, reviewers have a manageable workload, and the end-to-end review process is measurably useful without making unsafe automated decisions.
This is a hypothetical example, not a claim about any actual customer deployment.
Likely interviewer follow-ups#
Would you always prioritize recall? No. For risk discovery with costly misses, recall is usually the first constraint. If flags trigger expensive irreversible actions without review, false positives may carry much greater costs. Define the action and its consequences first.
Why not set the threshold to zero? Every example would be flagged under the stated score range. Recall would be perfect if there are positives, but the review workload could make the system pointless.
What if the model has 99% recall? Ask about the number of positives, confidence intervals, critical risk categories, contract-level coverage, held-out performance and extraction failures. Aggregate recall can conceal serious misses.
How do you handle a rare risk category? Collect expert-labeled examples, evaluate separately, use suitable contextual features or deterministic checks, and route uncertain cases to reviewers. Do not claim reliable performance from an inadequate test sample.
Why not optimize F1? F1 gives equal harmonic weighting to precision and recall. It does not express severity, actual error costs, reviewer capacity or minimum recall requirements.
What would make you block launch? A failed critical-risk recall gate, unresolved security issue, unreliable extraction, inability to manage review capacity or insufficient evidence of safety on the intended contract population.
References
- 1.scikit-learn — Classification metrics (not live-verified)scikit-learn.org
- 2.
- 3.scikit-learn — Probability calibration (not live-verified)scikit-learn.org
- 4.
- 5.
Related questions
Explore other topics:AI AgentsAI System DesignLarge Language Models