The two-by-two table: sensitivity and specificity
Cross a test with a reference standard and read down the columns. Sensitivity and specificity describe the test, given the truth.
What runs in CodeSplash
- Diagnostic accuracy (sensitivity, specificity, PPV, NPV) Verified in Python and R
You will be able to
- Build the two-by-two table of a test against a reference standard
- Compute sensitivity and specificity, and say what each one conditions on
- Explain why accuracy alone can mislead
Read first
A test against the truth
ReadAltman and Bland report a study of 344 patients who had a liver scan and then pathology. Pathology is the reference standardReference standardThe best available way to tell who truly has the condition; sensitivity and specificity are measured against it.: the best available statement of who really has the disease.
| Disease | No disease | |
|---|---|---|
| Scan abnormal | 231 | 32 |
| Scan normal | 27 | 54 |
The cells have names. Top row, left to right: true positives, false positives. Bottom row: false negatives, true negatives.
Read down a column
PredictPredict first
Take only the patients who truly have disease, the left column. What share of them did the scan flag?
Make your guess between 0 and 1 share of patients, then reveal.
Reveal
= 0.895. That's the sensitivity. You used one column, and the patients without disease played no part.
Two conditional questions
ReadSensitivitySensitivityThe share of real positives the test catches. and specificitySpecificityThe share of real negatives the test correctly clears. each start from the truth:
Here specificity is 0.628. So the scan catches most disease, and it also flags more than a third of the patients without it.
Machine learning calls sensitivity recall. The number is the same.
The test that flags everyone
PredictPredict first
A lazy test calls every patient abnormal without looking at anything. What are its sensitivity and specificity?
Reveal
Sensitivity 100%, specificity 0%. It can't miss disease, because it flags everyone. Either number alone can be made perfect, so always read the two together.
Why accuracy isn't enough
ReadAccuracyAccuracyThe share of predictions that are right; misleading when classes are imbalanced. is the share of all patients classified correctly, here 82.8%. It mixes the two rates, weighted by prevalence :
PrevalencePrevalenceHow common the condition is in the population tested; it drives predictive values. in this study is 75.0%, so the lazy test already scores 75% without examining anyone. The scan's lead over doing nothing is much smaller than its accuracy suggests.
Try the lazy model
ExploreAnswer the prompt first. Then lower Share of positives and compare Accuracy with Always negative. What happens to Recall?
HExplorable · Rare events and the decision threshold
Why can a 98% accurate model be useless, and where should the threshold go?
A lazy model calls every case negative. What accuracy does it score?
| flagged | passed | |
|---|---|---|
| pos | 52 | 62 |
| neg | 312 | 4574 |
Bars are drawn to one count scale, so a rare positive class looks as rare as it is. The ROC curve barely notices the imbalance; the precision–recall curve shows it. Cheapest threshold here: 1.14; the binormal formula gives 1.35.
Commit your prediction above to see the result
Make your prediction to see the result.
Read the card
In the appThe card shows the Test × reference table and a heat map, then Accuracy measures with intervals.
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,
})
Sensitivity runs from 0.85 to 0.93, specificity from 0.52 to 0.73. Specificity's interval is wider because only patients lacked disease.
Check Positive test level and Condition-present level before reading anything: swap one, and every measure changes meaning.
Same table, two dialects
ReadBoth compute the exact Clopper–Pearson interval, which the card uses by default. Interval for proportions offers three others.
import pandas as pd
from statsmodels.stats.proportion import proportion_confint
df = pd.read_csv("liver_scan.csv")
t = pd.crosstab(df["scan"], df["pathology"])
tp, fn = t.loc["abnormal", "abnormal"], t.loc["normal", "abnormal"]
tn, fp = t.loc["normal", "normal"], t.loc["abnormal", "normal"]
print(tp / (tp + fn), proportion_confint(tp, tp + fn, method="beta"))
print(tn / (tn + fp), proportion_confint(tn, tn + fp, method="beta"))df <- read.csv("liver_scan.csv")
t <- table(scan = df$scan, pathology = df$pathology)
tp <- t["abnormal", "abnormal"]; fn <- t["normal", "abnormal"]
tn <- t["normal", "normal"]; fp <- t["abnormal", "normal"]
binom.test(tp, tp + fn)[c("estimate", "conf.int")]
binom.test(tn, tn + fp)[c("estimate", "conf.int")]Check your understanding
CheckpointCheck yourself
Of the patients without disease, 54 scanned normal and 32 scanned abnormal. What is the specificity? Give three decimals.
Show the answer
Answer: 0.627906976744186
Specificity uses only people without disease: 54 / (54 + 32).
Check yourself
A test has 90% sensitivity. Which statement is right?
Show the answer
Answer: a
Sensitivity conditions on having the condition. The second option is the positive predictive value, the next lesson's subject. The last option describes specificity.
Check yourself
Fraud affects 1% of transactions. A model reports 99% accuracy. What should you do first?
Show the answer
Answer: b
Accuracy is dominated by the common class. A model that never flags anything has 99% accuracy and 0% sensitivity.
Recap
Recap- Compare the test with a reference standard in a two-by-two table.
- Sensitivity and specificity read down the columns: they start from the truth.
- Read them together, because either alone can be made perfect.
- Accuracy depends on prevalence, so compare it with what doing nothing would score.
Concepts in this lesson