How accuracy studies go wrong
Sensitivity and specificity are estimates from a study, and the design can bend them. Learn the common biases and how to compare two tests on the same patients.
What runs in CodeSplash
- Diagnostic accuracy (sensitivity, specificity, PPV, NPV) Verified in Python and R
- McNemar's test (paired proportions) Verified in Python and R
You will be able to
- Predict how partial verification bends sensitivity and specificity
- Spot spectrum, incorporation and review bias in a study description
- Compare two tests on the same patients, and say what McNemar's test can't show
Only as good as the study
ReadSensitivity and specificity sound like fixed properties of a test. They're estimates from one study, and the way that study ran can push them in a predictable direction.
No formula on the card can detect this. You have to know who got tested, who got the reference, and who knew what.
Who gets the reference?
PredictPredict first
Pathology is invasive. Suppose everyone with an abnormal scan has it, but only half of those with a normal scan do. What happens to the sensitivity you compute?
Reveal
It rises and specificity falls. Half the normal scans vanish from both columns:
On the full data they were 0.90 and 0.63. This is partial verification biasPartial verification biasBias from giving the reference standard mostly to people who test positive. Sensitivity rises and specificity falls..
Other ways to bend the numbers
Read| Problem | What happens | Usual effect | Guard |
|---|---|---|---|
| SpectrumSpectrum effectSensitivity and specificity change with the mix of patients, so severe cases against healthy controls flatter a test. | Severe cases against healthy volunteers | Both look better | Enrol consecutive patients who need the test |
| Differential verification | A different reference depending on the result | Varies | One reference for everyone |
| Incorporation | The test is part of the reference | Both look better | An independent reference |
| Review | Readers know the other result | Both look better | Blind each reading |
| Imperfect reference | The reference itself makes errors | Often look worse | Say so, or use a latent-class model |
Judge a study you know
ReflectThink of a test, a screening tool or a model you've seen validated. Who received the reference, and was it everyone? Who read each result, and what did they know? Were the people like the ones it will be used on?
The STARD checklist asks these questions when you report an accuracy study, and QUADAS-2 asks them when you review one.
Find the row on the card
In the appOpen the assumptions on this card. Everyone verified by the reference is shown for information only, since the data can't reveal how the study ran.
sensitivity = .90, specificity = .63, LR+ = 2.41, LR− = 0.17
- Sensitivity
- 0.8953
- Specificity
- 0.6279
- Positive predictive value
- 0.8783
- Negative predictive value
- 0.6667
Effect size
- Diagnostic odds ratio 14.438 95% CI [7.990, 26.089]
- Youden's J 0.5233 95% CI [0.4145, 0.6320]
Plots
Positive: pathology = abnormal (reference) and scan = abnormal (test).
View data
| Reference: pathology | Count | Test: scan |
|---|---|---|
| Positive | 231 | Positive |
| Positive | 27 | Negative |
| Negative | 32 | Positive |
| Negative | 54 | Negative |
Assumptions
- No empty cells — Every cell has at least one subject.
- Everyone verified by the reference — Rows missing either result were left out; if the reference was applied selectively, sensitivity and specificity are biased.
Test × reference
| scan \ pathology | abnormal (condition) | normal (no condition) | Total |
|---|---|---|---|
| abnormal (positive) | 231 | 32 | 263 |
| normal (negative) | 27 | 54 | 81 |
| Total | 258 | 86 | 344 |
Accuracy measures (95% CI; proportions Clopper–Pearson)
| Measure | Estimate | CI low | CI high |
|---|---|---|---|
| Sensitivity | 0.8953 | 0.8514 | 0.9299 |
| Specificity | 0.6279 | 0.5170 | 0.7298 |
| Positive predictive value | 0.8783 | 0.8326 | 0.9153 |
| Negative predictive value | 0.6667 | 0.5532 | 0.7676 |
| Accuracy | 0.8285 | 0.7844 | 0.8668 |
| Prevalence (sample) | 0.7500 | 0.7008 | 0.7949 |
| Likelihood ratio + | 2.406 | 1.823 | 3.176 |
| Likelihood ratio − | 0.1667 | 0.1126 | 0.2467 |
| Diagnostic odds ratio | 14.438 | 7.990 | 26.089 |
| Youden's J | 0.5233 | 0.4145 | 0.6320 |
| Balanced accuracy | 0.7616 | 0.7072 | 0.8160 |
| F1 score | 0.8868 | — | — |
| Matthews correlation | 0.5340 | — | — |
- Positive test: scan = abnormal; condition present: pathology = abnormal. Likelihood-ratio intervals: Simel et al. (1991).
The exact R script · R R version 4.5.1 (2025-06-13)
# Diagnostic accuracy (sensitivity, specificity, PPV, NPV)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method diagnostic.accuracy 1.0.2 · spec ccb26f33bffe0a0b
# Dataset: liver_scan (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_diag_accuracy (twin of codesplash.stats.diagnostic)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/liver_scan.parquet", col_select = c("scan", "pathology")))
n_input <- nrow(df)
df[["scan"]] <- factor(df[["scan"]], levels = c("normal", "abnormal")) # stored level order
df[["pathology"]] <- factor(df[["pathology"]], levels = c("normal", "abnormal")) # stored level order
df <- df[stats::complete.cases(df[c("scan", "pathology")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("scan", "pathology")) # infinite values stop the run (registry/errors.yaml)
# %% Test
t <- "scan"
r <- "pathology"
test_levels <- c("normal", "abnormal") # stored level order
ref_levels <- c("normal", "abnormal")
test_pos <- test_levels[length(test_levels)] # default: the last level ("true")
ref_pos <- ref_levels[length(ref_levels)] # condition-present level
test_neg <- setdiff(test_levels, test_pos)[1]
ref_neg <- setdiff(ref_levels, ref_pos)[1]
is_tp <- as.character(df[[t]]) == test_pos
is_dp <- as.character(df[[r]]) == ref_pos
tp <- sum(is_tp & is_dp)
fp <- sum(is_tp & !is_dp)
fn <- sum(!is_tp & is_dp)
tn <- sum(!is_tp & !is_dp)
# Sensitivity and specificity need rows with and without the condition.
k_ref <- (tp + fn > 0) + (fp + tn > 0)
if (k_ref < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = r, min = 2, k = k_ref)
conf <- 0.95
ci_method <- "clopper-pearson"
prevalence <- NULL # population prevalence (optional)
acc <- cs_diag_accuracy(tp, fp, fn, tn, conf = conf, ci_method = ci_method, prevalence = prevalence)
# %% Assumptions
cell_names <- c("true positive", "false positive", "false negative", "true negative")
zero <- cell_names[c(tp, fp, fn, tn) == 0]
assumptions <- list(
list(key = "cells", label = "No empty cells", status = if (length(zero)) "warn" else "pass",
detail = if (length(zero)) paste0("Empty ", paste(zero, collapse = " and "), " cell: likelihood ratios can be infinite or undefined; 0.5 was added to every cell for the DOR.") else "Every cell has at least one subject."),
list(key = "verification", label = "Everyone verified by the reference", status = "info",
detail = "Rows missing either result were left out; if the reference was applied selectively, sensitivity and specificity are biased.")
)
# %% Result
ci_label <- c("clopper-pearson" = "Clopper–Pearson", wilson = "Wilson", jeffreys = "Jeffreys", "agresti-coull" = "Agresti–Coull")[[ci_method]]
measures <- list(
c("sensitivity", "Sensitivity"), c("specificity", "Specificity"), c("ppv", "Positive predictive value"), c("npv", "Negative predictive value"),
c("accuracy", "Accuracy"), c("prevalence", "Prevalence (sample)"), c("lr_pos", "Likelihood ratio +"), c("lr_neg", "Likelihood ratio −"),
c("dor", "Diagnostic odds ratio"), c("youden", "Youden's J"), c("balanced_accuracy", "Balanced accuracy")
)
if (!is.null(prevalence)) {
measures <- c(measures, list(c("ppv_adj", sprintf("PPV at prevalence %s", format(prevalence))), c("npv_adj", sprintf("NPV at prevalence %s", format(prevalence)))))
}
rows <- lapply(measures, function(m) list(measure = m[2], estimate = acc[[m[1]]], ci_low = acc[[paste0(m[1], "_ci_low")]], ci_high = acc[[paste0(m[1], "_ci_high")]]))
rows <- c(rows, list(list(measure = "F1 score", estimate = acc$f1, ci_low = NULL, ci_high = NULL),
list(measure = "Matthews correlation", estimate = acc$mcc, ci_low = NULL, ci_high = NULL)))
pct <- sprintf("%.0f%%", conf * 100)
summary <- sprintf("Sensitivity %.1f%% (%d/%d), specificity %.1f%% (%d/%d), PPV %.1f%%, NPV %.1f%%; LR+ %s, LR− %s.",
100 * acc$sensitivity, tp, tp + fn, 100 * acc$specificity, tn, tn + fp, 100 * acc$ppv, 100 * acc$npv,
cs_fmt_num(acc$lr_pos), cs_fmt_num(acc$lr_neg))
values <- acc
values$test_positive <- test_pos
values$reference_positive <- ref_pos
cs_publish(list(
method = "diagnostic.accuracy",
methodVersion = "1.0.2",
title = "Diagnostic accuracy",
engine = cs_engine_info("stats", "nanoparquet"),
n = tp + fp + fn + tn,
summary = summary,
apa = sprintf("sensitivity = %s, specificity = %s, LR+ = %s, LR− = %s", cs_fmt_num(acc$sensitivity, leading_zero = FALSE),
cs_fmt_num(acc$specificity, leading_zero = FALSE), cs_fmt_num(acc$lr_pos), cs_fmt_num(acc$lr_neg)),
statistics = lapply(measures[1:4], function(m) list(key = m[1], label = m[2], value = acc[[m[1]]])),
tables = list(
list(key = "confusion", title = "Test × reference",
columns = list(list(key = "row", label = paste(t, "\\", r), type = "string"), list(key = "pos", label = paste(ref_pos, "(condition)"), type = "integer"),
list(key = "neg", label = paste(ref_neg, "(no condition)"), type = "integer"), list(key = "total", label = "Total", type = "integer")),
rows = list(list(row = paste(test_pos, "(positive)"), pos = tp, neg = fp, total = tp + fp),
list(row = paste(test_neg, "(negative)"), pos = fn, neg = tn, total = fn + tn),
list(row = "Total", pos = tp + fn, neg = fp + tn, total = tp + fp + fn + tn))),
list(key = "measures", title = sprintf("Accuracy measures (%s CI; proportions %s)", pct, ci_label),
columns = list(list(key = "measure", label = "Measure", type = "string"), list(key = "estimate", label = "Estimate", type = "number"),
list(key = "ci_low", label = "CI low", type = "number"), list(key = "ci_high", label = "CI high", type = "number")),
rows = rows)
),
effectSizes = list(
list(key = "dor", label = "Diagnostic odds ratio", value = acc$dor, ciLow = acc$dor_ci_low, ciHigh = acc$dor_ci_high, ciLevel = conf,
method = paste0("Woolf log interval", if (acc$dor_corrected == 1) " (0.5 added to every cell)" else "")),
list(key = "youden", label = "Youden's J", value = acc$youden, ciLow = acc$youden_ci_low, ciHigh = acc$youden_ci_high, ciLevel = conf,
method = "Se + Sp − 1, Wald interval")
),
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(sprintf("Positive test: %s = %s; condition present: %s = %s. Likelihood-ratio intervals: Simel et al. (1991).", t, test_pos, r, ref_pos),
if (!is.null(prevalence)) " Prevalence-adjusted predictive values: Mercaldo et al. (2007) logit intervals." else "")),
# Chart Lab `confusion-matrix`: reference in rows, test in columns, condition-present first (TP top left).
# Its intervals are Wilson intervals, so they show only when the method's own interval is Wilson too.
charts = list(cs_chart(
"confusion", "confusion-matrix", sprintf("Confusion matrix: %s against %s", t, r),
list(actual = cs_col(paste0("Reference: ", r), c("Positive", "Positive", "Negative", "Negative"), levels = c("Positive", "Negative")),
predicted = cs_col(paste0("Test: ", t), c("Positive", "Negative", "Positive", "Negative"), levels = c("Positive", "Negative")),
count = cs_col("Count", as.numeric(c(tp, fn, fp, tn)), kind = "numeric")),
controls = list(positive = "first", view = "compact", intervals = identical(ci_method, "wilson")),
note = sprintf("Positive: %s = %s (reference) and %s = %s (test).", r, ref_pos, t, test_pos)
)),
values = values
))
sensitivity = .90, specificity = .63, LR+ = 2.41, LR− = 0.17
- Sensitivity
- 0.8953
- Specificity
- 0.6279
- Positive predictive value
- 0.8783
- Negative predictive value
- 0.6667
Effect size
- Diagnostic odds ratio 14.438 95% CI [7.990, 26.089]
- Youden's J 0.5233 95% CI [0.4145, 0.6320]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- No empty cells — Every cell has at least one subject.
- Everyone verified by the reference — Rows missing either result were left out; if the reference was applied selectively, sensitivity and specificity are biased.
Test × reference
| scan \ pathology | abnormal (condition) | normal (no condition) | Total |
|---|---|---|---|
| abnormal (positive) | 231 | 32 | 263 |
| normal (negative) | 27 | 54 | 81 |
| Total | 258 | 86 | 344 |
Accuracy measures (95% CI; proportions Clopper–Pearson)
| Measure | Estimate | CI low | CI high |
|---|---|---|---|
| Sensitivity | 0.8953 | 0.8514 | 0.9299 |
| Specificity | 0.6279 | 0.5170 | 0.7298 |
| Positive predictive value | 0.8783 | 0.8326 | 0.9153 |
| Negative predictive value | 0.6667 | 0.5532 | 0.7676 |
| Accuracy | 0.8285 | 0.7844 | 0.8668 |
| Prevalence (sample) | 0.7500 | 0.7008 | 0.7949 |
| Likelihood ratio + | 2.406 | 1.823 | 3.176 |
| Likelihood ratio − | 0.1667 | 0.1126 | 0.2467 |
| Diagnostic odds ratio | 14.438 | 7.990 | 26.089 |
| Youden's J | 0.5233 | 0.4145 | 0.6320 |
| Balanced accuracy | 0.7616 | 0.7072 | 0.8160 |
| F1 score | 0.8868 | — | — |
| Matthews correlation | 0.5340 | — | — |
- Positive test: scan = abnormal; condition present: pathology = abnormal. Likelihood-ratio intervals: Simel et al. (1991).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Diagnostic accuracy (sensitivity, specificity, PPV, NPV)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method diagnostic.accuracy 1.0.2 · spec ccb26f33bffe0a0b
# Dataset: liver_scan (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.stats import diagnostic as csd # every accuracy measure (twin of codesplashr::cs_diag_accuracy)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/liver_scan.parquet", columns=["scan", "pathology"])
n_input = len(df)
df["scan"] = pd.Categorical(df["scan"], categories=["normal", "abnormal"]) # stored level order
df["pathology"] = pd.Categorical(df["pathology"], categories=["normal", "abnormal"]) # stored level order
df = df.dropna(subset=["scan", "pathology"]) # listwise deletion over the analysis columns
df["scan"] = df["scan"].cat.remove_unused_categories()
df["pathology"] = df["pathology"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["scan", "pathology"]) # infinite values stop the run (registry/errors.yaml)
# %% Test
t, r = "scan", "pathology"
test_levels = ["normal", "abnormal"] # stored level order
ref_levels = ["normal", "abnormal"]
test_pos = test_levels[-1] # default: the last level ("true")
ref_pos = ref_levels[-1] # condition-present level
test_neg = next(lv for lv in test_levels if lv != test_pos)
ref_neg = next(lv for lv in ref_levels if lv != ref_pos)
tp_ = df[t].astype(str) == test_pos
dp_ = df[r].astype(str) == ref_pos
tp, fp = int((tp_ & dp_).sum()), int((tp_ & ~dp_).sum())
fn, tn = int((~tp_ & dp_).sum()), int((~tp_ & ~dp_).sum())
# Sensitivity and specificity need rows with and without the condition.
k_ref = int(tp + fn > 0) + int(fp + tn > 0)
if k_ref < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=r, min=2, k=k_ref)
conf = 0.95
ci_method = "clopper-pearson"
prevalence = None # population prevalence (optional)
acc = csd.accuracy(tp, fp, fn, tn, conf=conf, ci_method=ci_method, prevalence=prevalence)
# %% Assumptions
zero = [name for name, x in (("true positive", tp), ("false positive", fp), ("false negative", fn), ("true negative", tn)) if x == 0]
assumptions = [
{"key": "cells", "label": "No empty cells", "status": "warn" if zero else "pass",
"detail": ("Empty " + " and ".join(zero) + " cell: likelihood ratios can be infinite or undefined; 0.5 was added to every cell for the DOR.") if zero else "Every cell has at least one subject."},
{"key": "verification", "label": "Everyone verified by the reference", "status": "info",
"detail": "Rows missing either result were left out; if the reference was applied selectively, sensitivity and specificity are biased."},
]
# %% Result
ci_label = {"clopper-pearson": "Clopper–Pearson", "wilson": "Wilson", "jeffreys": "Jeffreys", "agresti-coull": "Agresti–Coull"}[ci_method]
measures = [
("sensitivity", "Sensitivity"), ("specificity", "Specificity"), ("ppv", "Positive predictive value"), ("npv", "Negative predictive value"),
("accuracy", "Accuracy"), ("prevalence", "Prevalence (sample)"), ("lr_pos", "Likelihood ratio +"), ("lr_neg", "Likelihood ratio −"),
("dor", "Diagnostic odds ratio"), ("youden", "Youden's J"), ("balanced_accuracy", "Balanced accuracy"),
]
if prevalence is not None:
measures += [("ppv_adj", f"PPV at prevalence {prevalence:g}"), ("npv_adj", f"NPV at prevalence {prevalence:g}")]
rows = [{"measure": label, "estimate": acc[k], "ci_low": acc.get(f"{k}_ci_low"), "ci_high": acc.get(f"{k}_ci_high")} for k, label in measures]
rows += [{"measure": "F1 score", "estimate": acc["f1"], "ci_low": None, "ci_high": None},
{"measure": "Matthews correlation", "estimate": acc["mcc"], "ci_low": None, "ci_high": None}]
summary = (
f"Sensitivity {acc['sensitivity']:.1%} ({tp}/{tp + fn}), specificity {acc['specificity']:.1%} ({tn}/{tn + fp}), "
f"PPV {acc['ppv']:.1%}, NPV {acc['npv']:.1%}; LR+ {cs.fmt_num(acc['lr_pos'])}, LR− {cs.fmt_num(acc['lr_neg'])}."
)
values = {k: v for k, v in acc.items()}
values.update({"test_positive": test_pos, "reference_positive": ref_pos})
cs.publish({
"method": "diagnostic.accuracy",
"methodVersion": "1.0.2",
"title": "Diagnostic accuracy",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": tp + fp + fn + tn,
"summary": summary,
"apa": f"sensitivity = {cs.fmt_num(acc['sensitivity'], leading_zero=False)}, specificity = {cs.fmt_num(acc['specificity'], leading_zero=False)}, "
f"LR+ = {cs.fmt_num(acc['lr_pos'])}, LR− = {cs.fmt_num(acc['lr_neg'])}",
"statistics": [{"key": k, "label": label, "value": acc[k]} for k, label in measures[:4]],
"tables": [
{"key": "confusion", "title": "Test × reference",
"columns": [{"key": "row", "label": f"{t} \\ {r}", "type": "string"}, {"key": "pos", "label": f"{ref_pos} (condition)", "type": "integer"},
{"key": "neg", "label": f"{ref_neg} (no condition)", "type": "integer"}, {"key": "total", "label": "Total", "type": "integer"}],
"rows": [{"row": f"{test_pos} (positive)", "pos": tp, "neg": fp, "total": tp + fp},
{"row": f"{test_neg} (negative)", "pos": fn, "neg": tn, "total": fn + tn},
{"row": "Total", "pos": tp + fn, "neg": fp + tn, "total": tp + fp + fn + tn}]},
{"key": "measures", "title": f"Accuracy measures ({conf:.0%} CI; proportions {ci_label})",
"columns": [{"key": "measure", "label": "Measure", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"},
{"key": "ci_low", "label": "CI low", "type": "number"}, {"key": "ci_high", "label": "CI high", "type": "number"}],
"rows": rows},
],
"effectSizes": [
{"key": "dor", "label": "Diagnostic odds ratio", "value": acc["dor"], "ciLow": acc["dor_ci_low"], "ciHigh": acc["dor_ci_high"], "ciLevel": conf,
"method": "Woolf log interval" + (" (0.5 added to every cell)" if acc["dor_corrected"] else "")},
{"key": "youden", "label": "Youden's J", "value": acc["youden"], "ciLow": acc["youden_ci_low"], "ciHigh": acc["youden_ci_high"], "ciLevel": conf,
"method": "Se + Sp − 1, Wald interval"},
],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Positive test: {t} = {test_pos}; condition present: {r} = {ref_pos}. Likelihood-ratio intervals: Simel et al. (1991)."
+ (f" Prevalence-adjusted predictive values: Mercaldo et al. (2007) logit intervals." if prevalence is not None else "")],
# Chart Lab `confusion-matrix`: reference in rows, test in columns, condition-present first (TP top left).
# Its intervals are Wilson intervals, so they show only when the method's own interval is Wilson too.
"charts": [cs.chart(
"confusion", "confusion-matrix", f"Confusion matrix: {t} against {r}",
{"actual": cs.col(f"Reference: {r}", ["Positive", "Positive", "Negative", "Negative"], levels=["Positive", "Negative"]),
"predicted": cs.col(f"Test: {t}", ["Positive", "Negative", "Positive", "Negative"], levels=["Positive", "Negative"]),
"count": cs.col("Count", [tp, fn, fp, tn], kind="numeric")},
controls={"positive": "first", "view": "compact", "intervals": ci_method == "wilson"},
note=f"Positive: {r} = {ref_pos} (reference) and {t} = {test_pos} (test).",
)],
"values": values,
})
The card drops rows that lack either result. If those rows are missing because of the test result, you've got partial verification, and the card can't tell you. When verification depended only on the test result, you can reweight the verified patients. The code below does this.
Two tests, same patients
ExploreTo compare two tests on the same people, keep the pairs and split by truth. Among people with disease, a McNemar test compares sensitivities. Among those without, it compares specificities. Only pairs where the tests disagree carry evidence.
Read "before" as test A and "after" as test B. Change the two disagreeing cells, then the two agreeing cells.
EExplorable · McNemar's discordant pairs
For paired yes/no data, which pairs carry the evidence?
Add 1,000 people who answered yes both times. What happens to the p-value?
| Yes after | No after | |
|---|---|---|
| Yes before | 40 no change | 18 changed |
| No before | 6 changed | 36 no change |
Only the highlighted pairs count. p = .025 whatever the gray cells hold. The change in proportions is 12.0 points out of 100 people.
Commit your prediction above to see the result
Make your prediction to see the result.
Same corrections, two dialects
Readfrom statsmodels.stats.contingency_tables import mcnemar
# Half of the normal scans were verified: count each of them twice (Begg and Greenes, 1983)
tp, fp, fn_seen, tn_seen = 231, 32, 13.5, 27
fn, tn = fn_seen / 0.5, tn_seen / 0.5
print("naive", tp / (tp + fn_seen), tn_seen / (tn_seen + fp))
print("reweighted", tp / (tp + fn), tn / (tn + fp))
# Two tests on the same 100 patients with disease: rows test A, columns test B
print(mcnemar([[40, 18], [6, 36]], exact=True))# Half of the normal scans were verified: count each of them twice (Begg and Greenes, 1983)
tp <- 231; fp <- 32; fn_seen <- 13.5; tn_seen <- 27
fn <- fn_seen / 0.5; tn <- tn_seen / 0.5
c(naive_se = tp / (tp + fn_seen), naive_sp = tn_seen / (tn_seen + fp))
c(weighted_se = tp / (tp + fn), weighted_sp = tn / (tn + fp))
# Two tests on the same 100 patients with disease: rows test A, columns test B
binom.test(18, 18 + 6)$p.value # exact McNemar: only the disagreeing pairsThe reweighted numbers recover the full-data values.
Check your understanding
CheckpointCheck yourself
A biopsy is done mostly on people with a positive test. Compared with verifying everyone, what do you expect?
Show the answer
Answer: a
Unverified negatives are missing from both columns. That removes false negatives (raising sensitivity) and true negatives (lowering specificity).
Check yourself
A blood test is validated on patients with advanced disease and on healthy students. Sensitivity and specificity are 97%. What's the main concern for its use in a clinic?
Show the answer
Answer: c
This is the spectrum effect. The study tested the easiest possible separation, while the clinic faces harder cases.
Check yourself
A test and the reference disagree on 100 patients: 50 each way. McNemar's statistic is 0. What does this tell you?
Show the answer
Answer: c
McNemar's test compares the two margins. Equal margins can sit alongside many errors, which is why you report sensitivity and specificity.
Recap
Recap- Partial verification raises sensitivity and lowers specificity.
- Severe cases against healthy controls make any test look good.
- The data can't reveal these problems, so report how the study ran.
- Compare two tests on the same patients with McNemar's test, within each truth group.
Concepts in this lesson