AI Wiki中文/EN

Model evaluation and experimental design

工程评测与实验设计

Build credible baselines, prevent leakage, and report metrics, differences, and uncertainty.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

First ask: what decision should the score support?

A model with 95% test accuracy can still be useless. If 95% of examples are negative, always predicting negative achieves the same score. Evaluation should begin with the use case, error costs, and decision—not the most flattering metric.

An equipment-warning system may care about missed failures, the number of alerts operators can handle, and whether warnings arrive early enough. Offline classification accuracy captures only part of that problem. Establish majority-class, simple-rule, or linear-model baselines before deciding whether a complex model offers a sufficient, reliable improvement.

Data splits and metrics

Training data fits parameters, validation data selects models and hyperparameters, and test data supports final evaluation. Preprocessing is part of learning: fit scaling, imputation, feature selection, and vocabularies on training data. Forecasting needs temporal separation. Related records from the same patient, user, or device often require grouped splitting. A random split is not universally correct. Cross-validation guide

For binary classification, let TP, FP, and FN mean true positives, false positives, and false negatives:

Precision=TPTP+FP,Recall=TPTP+FN,F1=2PRP+R.Precision=\frac{TP}{TP+FP},\quad Recall=\frac{TP}{TP+FN},\quad F_1=\frac{2PR}{P+R}.

Specify conventions when denominators are zero. Probabilities also require calibration assessment: strong ranking does not imply trustworthy probabilities. AUC, F1, and actual error costs measure different things and cannot substitute for one another. Metrics guide

Repeatedly selecting the best experiment creates selection bias. Nested cross-validation performs selection inside an inner loop and generalization assessment in an outer loop, addressing this issue under suitable assumptions. It increases computational cost and cannot repair an invalid split. Cawley and Talbot

Check a misleadingly strong-looking result

def binary_metrics(truth, prediction):
    if not truth or len(truth) != len(prediction):
        raise ValueError("nonempty equal-length arrays required")
    if any(type(v) is not int or v not in (0, 1)
           for v in [*truth, *prediction]):
        raise ValueError("labels must be integer 0 or 1")
    tp = sum(y == 1 and p == 1 for y, p in zip(truth, prediction))
    fp = sum(y == 0 and p == 1 for y, p in zip(truth, prediction))
    fn = sum(y == 1 and p == 0 for y, p in zip(truth, prediction))
    tn = len(truth)-tp-fp-fn
    precision = tp/(tp+fp) if tp+fp else 0.0
    recall = tp/(tp+fn) if tp+fn else 0.0
    f1 = 2*tp/(2*tp+fp+fn) if 2*tp+fp+fn else 0.0
    return {"tp": tp, "fp": fp, "fn": fn, "tn": tn,
            "accuracy": (tp+tn)/len(truth), "precision": precision,
            "recall": recall, "f1": f1}

truth = [0]*95 + [1]*5
baseline = binary_metrics(truth, [0]*100)
assert baseline["accuracy"] == 0.95 and baseline["recall"] == 0
# Illustrative predictions: 10 false alerts and 4 detected failures.
model = binary_metrics(truth, [1]*10 + [0]*85 + [1]*4 + [0])
assert (model["tp"], model["fp"], model["fn"], model["tn"]) == (4, 10, 1, 85)
assert abs(model["f1"]-8/19) < 1e-12
assert model["accuracy"] == 0.89
assert 100*baseline["fn"] + 2*baseline["fp"] == 500
assert 100*model["fn"] + 2*model["fp"] == 120
assert binary_metrics([0], [0])["f1"] == 0
assert binary_metrics([1], [1])["f1"] == 1
for y, p in (([], []), ([0], [0, 1]), ([2], [1]), ([0], [float("nan")])):
    try:
        binary_metrics(y, p)
    except ValueError:
        pass
    else:
        raise AssertionError("invalid labels accepted")

Here the positive class is integer 1. Precision is zero with no positive predictions, recall is zero with no actual positives, and F1 is zero when its denominator is zero. Counting takes O(n)O(n) time; the concatenated input-validation list uses O(n)O(n) temporary space. Real reports should also include sample counts, thresholds, the positive-class definition, group slices, and uncertainty. A fixed random seed makes reruns easier, but a single seed does not establish stability.

Carry the example through: 100 checks include five real failures. Suppose a missed failure costs 100 units and a false alert costs two; these are teaching assumptions, not industry prices. Never alerting costs 5×100=5005\times100=500. A model detecting four failures with ten false alerts has only 89% accuracy, but costs 1×100+10×2=1201\times100+10\times2=120 and issues 14 alerts. Its usefulness still depends on operators’ capacity and the validity of the failure definition, labels, and time horizon.

If pp is a calibrated failure probability and these are the only error costs, alerting has conditional expected loss 2(1−p)2(1-p), while staying silent costs 100p100p. Alert when the former is smaller: p>2/102p>2/102. Capacity limits, handling delays, or varying costs require another threshold decision. This example’s threshold is not an equipment safety standard.

Write the reproducible procedure before inspecting test results. This teaching protocol needs explicit dataset versions and date boundaries in a real project.

ItemConcrete agreement
Prediction taskUse only sensor information available at inspection to predict failure in the next 24 hours; exclude fields entered after completed repairs
SplitFor future performance on existing devices, split chronologically and remove overlapping label windows across boundaries; for new devices, additionally hold out unseen devices
ComparisonsUse the same split for never-alert, existing fixed-rule, linear-model, and candidate baselines; determine rules and thresholds during training/validation only
SelectionOn validation data, choose a threshold within handling capacity, then compare cost, recall, alert volume, and lead time; freeze before test evaluation
ReproductionRecord data hashes, feature code, environment versions, all candidates and seeds, commands, inference time, and failure examples
Deployment decisionBegin with shadow operation to measure actual alert volume, handling time, and missed failures; specify thresholds and fallback criteria before evaluation

For within-device dependence, assess uncertainty across devices or time blocks instead of assuming independent rows. Too few independent units also make intervals unstable; more resampling does not create new evidence.

Limitations: a test set is still a sample

A test score estimates performance under particular data-generating conditions. Distribution shifts, contamination, and labeling errors can change its meaning. Keeping the best test result after many attempts effectively turns the test set into validation data. If a team repeatedly uses it for decisions, fresh independent evaluation data is needed.

For language models, examine train-test overlap, prompt sensitivity, evaluator bias, and generation randomness. For an entire product, assess latency, recovery, cost, and actual human use. An offline improvement does not automatically establish a deployment benefit.

Completion tasks

  1. Why does the example’s 95% accuracy fail to establish usefulness? Answer: it misses every positive and does not outperform the majority-class baseline.
  2. Is it appropriate to standardize all data before splitting? Answer: this generally leaks information about the test distribution; split first and fit preprocessing on training data.
  3. How should prediction of tomorrow’s data be evaluated? Answer: generally with time-respecting training and evaluation that prevent future information from entering features.
  4. Write a one-page evaluation protocol: problem, baseline, split, metrics, threshold, repetitions, failure slices, and deployment criteria. Another person should be able to reproduce every item.

Research connections

Ablations test whether a component contributes to a result. Effect sizes and confidence intervals describe the magnitude and uncertainty of a difference. Shift evaluation and monitoring test whether conclusions carry over to new data conditions. Separate algorithm changes from data quantity, compute, tuning budget, and selection procedures to identify the real source of an improvement.

Make a prediction, then check

What does a model always predicting a 95% majority class demonstrate?

Choose one answer

Learning objectives

  • Choose data splits and baselines around temporal or entity boundaries.
  • Distinguish tuning, final testing, and post-deployment monitoring.

Prerequisites & connections

Explore related knowledge →

References

  1. Cross-validation: evaluating estimator performance
    scikit-learn developers
  2. On Over-fitting in Model Selection and Subsequent Selection Bias in Performance Evaluation
    Gavin C. Cawley; Nicola L. C. Talbot · 2010
  3. Model evaluation: quantifying the quality of predictions
    scikit-learn developers

Version2 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: cited-source comparison, re-derivation and recalculation, bilingual argument comparison, and executed Python assertions; no independent human peer review.

  • Enumerated 256 four-sample binary outcomes and independently checked confusion matrices and F1; recomputed 95%/89% accuracy and 500/120 cost.
  • Checked the cost and calibration assumptions behind threshold 2/102; added time/device splits, label windows, shadow operation, and a reproducible protocol.
  • Compared the main claims, assumptions, examples, exercises, and citations across languages; structural checks additionally compare display equations, code, and source IDs. This is an AI technical check, not independent human peer review.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.