Likelihood ratios and single-number summaries
A likelihood ratio says how far a result moves your odds. Summaries such as the diagnostic odds ratio and F1 are convenient, and each hides something.
What runs in CodeSplash
- Diagnostic accuracy (sensitivity, specificity, PPV, NPV) Verified in Python and R
You will be able to
- Compute likelihood ratios and update pre-test odds to post-test odds
- Explain what the diagnostic odds ratio, Youden's J, F1 and MCC each hide
- Handle a table with an empty cell
Read first
How far does a result move you?
ReadA diagnostic likelihood ratioDiagnostic likelihood ratioHow much a positive (or negative) result multiplies the odds of the condition. compares how likely a result is with and without the disease:
For the liver scan, LR+ is 2.41 and LR− is 0.17. An abnormal scan is about 2.4 times as likely in someone with disease as in someone without.
Prevalence isn't in either formula, so a likelihood ratio travels between settings about as well as sensitivity and specificity do.
Update the odds
PredictPredict first
In a clinic where 10% of patients have the disease, a patient's scan comes back abnormal. What is the chance of disease now?
Make your guess between 0 and 1 chance of disease, then reveal.
Reveal
About 21%. Turn the probability into odds, multiply, and turn it back:
The odds form of Bayes' rule
ReadIt's the PPV formula in another form. At the study's own prevalence the pre-test odds are 3, and , a probability of 0.878: the PPV you met in the last lesson.
As a rough guide (Jaeschke and colleagues, 1994), an LR above 10 or below 0.1 often changes a decision. Near 1, a result tells you little.
Read the card
In the appHere the test is glucose of 126 or more against a diabetes diagnosis, with Interval for proportions set to Jeffreys and 90% intervals.
sensitivity = .67, specificity = .77, LR+ = 2.89, LR− = 0.43
- Sensitivity
- 0.6667
- Specificity
- 0.7690
- Positive predictive value
- 0.5900
- Negative predictive value
- 0.8223
Effect size
- Diagnostic odds ratio 6.659 90% CI [4.767, 9.301]
- Youden's J 0.4357 90% CI [0.3668, 0.5046]
Plots
Positive: type = Yes (reference) and glu_high = true (test).
View data
| Reference: type | Count | Test: glu_high |
|---|---|---|
| Positive | 118 | Positive |
| Positive | 59 | Negative |
| Negative | 82 | Positive |
| Negative | 273 | 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
| glu_high \ type | Yes (condition) | No (no condition) | Total |
|---|---|---|---|
| true (positive) | 118 | 82 | 200 |
| false (negative) | 59 | 273 | 332 |
| Total | 177 | 355 | 532 |
Accuracy measures (90% CI; proportions Jeffreys)
| Measure | Estimate | CI low | CI high |
|---|---|---|---|
| Sensitivity | 0.6667 | 0.6067 | 0.7227 |
| Specificity | 0.7690 | 0.7307 | 0.8041 |
| Positive predictive value | 0.5900 | 0.5321 | 0.6460 |
| Negative predictive value | 0.8223 | 0.7858 | 0.8547 |
| Accuracy | 0.7350 | 0.7026 | 0.7654 |
| Prevalence (sample) | 0.3327 | 0.2998 | 0.3669 |
| Likelihood ratio + | 2.886 | 2.407 | 3.461 |
| Likelihood ratio − | 0.4335 | 0.3616 | 0.5196 |
| Diagnostic odds ratio | 6.659 | 4.767 | 9.301 |
| Youden's J | 0.4357 | 0.3668 | 0.5046 |
| Balanced accuracy | 0.7178 | 0.6834 | 0.7523 |
| F1 score | 0.6260 | — | — |
| Matthews correlation | 0.4238 | — | — |
- Positive test: glu_high = true; condition present: type = Yes. 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 30c689989476c8f4
# Dataset: pima (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/pima.parquet", col_select = c("glu_high", "type")))
n_input <- nrow(df)
df[["glu_high"]] <- factor(df[["glu_high"]], levels = c("false", "true")) # stored level order
df[["type"]] <- factor(df[["type"]], levels = c("No", "Yes")) # stored level order
df <- df[stats::complete.cases(df[c("glu_high", "type")]), , 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("glu_high", "type")) # infinite values stop the run (registry/errors.yaml)
# %% Test
t <- "glu_high"
r <- "type"
test_levels <- c("false", "true") # stored level order
ref_levels <- c("No", "Yes")
test_pos <- test_levels[length(test_levels)] # default: the last level ("true")
ref_pos <- "Yes" # 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.9
ci_method <- "jeffreys"
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 = .67, specificity = .77, LR+ = 2.89, LR− = 0.43
- Sensitivity
- 0.6667
- Specificity
- 0.7690
- Positive predictive value
- 0.5900
- Negative predictive value
- 0.8223
Effect size
- Diagnostic odds ratio 6.659 90% CI [4.767, 9.301]
- Youden's J 0.4357 90% CI [0.3668, 0.5046]
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
| glu_high \ type | Yes (condition) | No (no condition) | Total |
|---|---|---|---|
| true (positive) | 118 | 82 | 200 |
| false (negative) | 59 | 273 | 332 |
| Total | 177 | 355 | 532 |
Accuracy measures (90% CI; proportions Jeffreys)
| Measure | Estimate | CI low | CI high |
|---|---|---|---|
| Sensitivity | 0.6667 | 0.6067 | 0.7227 |
| Specificity | 0.7690 | 0.7307 | 0.8041 |
| Positive predictive value | 0.5900 | 0.5321 | 0.6460 |
| Negative predictive value | 0.8223 | 0.7858 | 0.8547 |
| Accuracy | 0.7350 | 0.7026 | 0.7654 |
| Prevalence (sample) | 0.3327 | 0.2998 | 0.3669 |
| Likelihood ratio + | 2.886 | 2.407 | 3.461 |
| Likelihood ratio − | 0.4335 | 0.3616 | 0.5196 |
| Diagnostic odds ratio | 6.659 | 4.767 | 9.301 |
| Youden's J | 0.4357 | 0.3668 | 0.5046 |
| Balanced accuracy | 0.7178 | 0.6834 | 0.7523 |
| F1 score | 0.6260 | — | — |
| Matthews correlation | 0.4238 | — | — |
- Positive test: glu_high = true; condition present: type = Yes. 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 30c689989476c8f4
# Dataset: pima (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/pima.parquet", columns=["glu_high", "type"])
n_input = len(df)
df["glu_high"] = pd.Categorical(df["glu_high"], categories=["false", "true"]) # stored level order
df["type"] = pd.Categorical(df["type"], categories=["No", "Yes"]) # stored level order
df = df.dropna(subset=["glu_high", "type"]) # listwise deletion over the analysis columns
df["glu_high"] = df["glu_high"].cat.remove_unused_categories()
df["type"] = df["type"].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, ["glu_high", "type"]) # infinite values stop the run (registry/errors.yaml)
# %% Test
t, r = "glu_high", "type"
test_levels = ["false", "true"] # stored level order
ref_levels = ["No", "Yes"]
test_pos = test_levels[-1] # default: the last level ("true")
ref_pos = "Yes" # 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.9
ci_method = "jeffreys"
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,
})
LR+ is 2.89 (2.41 to 3.46) and LR− is 0.43. Useful, though neither would settle a diagnosis alone.
One number for everything?
Read| Measure | Formula | Liver scan |
|---|---|---|
| Diagnostic odds ratioDiagnostic odds ratioThe odds of a positive test in cases over the odds in non-cases, or LR+ divided by LR−. | 14.4 | |
| Youden's JYouden's JSensitivity + specificity − 1; the threshold that maximizes it weighs both errors equally. | 0.52 | |
| Balanced accuracyBalanced accuracyThe average of recall across classes; 0.5 is chance for two classes, whatever the imbalance. | 0.76 | |
| F1F1 scoreThe harmonic mean of precision and recall. It has no term for true negatives. | 0.89 | |
| MCCMatthews correlationThe correlation between a binary prediction and the truth, using all four cells of the table. 0 means no better than chance. | correlation of test and truth | 0.53 |
F1 looks excellent here because F1 ignores true negatives, and most patients have disease. MCC uses all four cells, and it's far more modest.
Same score, opposite tests
PredictPredict first
Test A has sensitivity 90% and specificity 60%. Test B has sensitivity 60% and specificity 90%. Which has the larger diagnostic odds ratio?
Reveal
They tie:
Youden's J ties too, at 0.5. Yet a negative result from A is reassuring, and a positive result from B is persuasive. You choose between them by what the next step in care needs, which no summary knows.
An empty cell
In the appThe rapid test had no false positives. Then LR+ is infinite and the odds ratio divides by zero. The card warns you and adds 0.5 to every cell for the odds ratio.
sensitivity = .80, specificity = 1.00, LR+ = ∞, LR− = 0.20
- Sensitivity
- 0.8000
- Specificity
- 1
- Positive predictive value
- 1
- Negative predictive value
- 0.8696
Effect size
- Diagnostic odds ratio 146.43 95% CI [6.966, 3078.06]
- Youden's J 0.8000 95% CI [0.5976, 1.002]
Plots
Positive: culture = true (reference) and rapid test = true (test).
View data
| Reference: culture | Count | Test: rapid test |
|---|---|---|
| Positive | 12 | Positive |
| Positive | 3 | Negative |
| Negative | 0 | Positive |
| Negative | 20 | Negative |
Assumptions
- No empty cells — Empty false positive cell: likelihood ratios can be infinite or undefined; 0.5 was added to every cell for the DOR.
- 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
| rapid test \ culture | true (condition) | false (no condition) | Total |
|---|---|---|---|
| true (positive) | 12 | 0 | 12 |
| false (negative) | 3 | 20 | 23 |
| Total | 15 | 20 | 35 |
Accuracy measures (95% CI; proportions Wilson)
| Measure | Estimate | CI low | CI high |
|---|---|---|---|
| Sensitivity | 0.8000 | 0.5481 | 0.9295 |
| Specificity | 1 | 0.8389 | 1 |
| Positive predictive value | 1 | 0.7575 | 1 |
| Negative predictive value | 0.8696 | 0.6787 | 0.9546 |
| Accuracy | 0.9143 | 0.7762 | 0.9704 |
| Prevalence (sample) | 0.4286 | 0.2798 | 0.5914 |
| Likelihood ratio + | ∞ | — | — |
| Likelihood ratio − | 0.2000 | 0.0727 | 0.5503 |
| Diagnostic odds ratio | 146.43 | 6.966 | 3078.06 |
| Youden's J | 0.8000 | 0.5976 | 1.002 |
| Balanced accuracy | 0.9000 | 0.7988 | 1.001 |
| PPV at prevalence 0.05 | 1 | — | — |
| NPV at prevalence 0.05 | 0.9896 | — | — |
| F1 score | 0.8889 | — | — |
| Matthews correlation | 0.8341 | — | — |
- Positive test: rapid test = true; condition present: culture = true. Likelihood-ratio intervals: Simel et al. (1991). Prevalence-adjusted predictive values: Mercaldo et al. (2007) logit intervals.
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 94a11659571920b2
# Dataset: rapid_test (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/rapid_test.parquet", col_select = c("rapid test", "culture")))
n_input <- nrow(df)
df[["rapid test"]] <- factor(df[["rapid test"]], levels = c("false", "true")) # stored level order
df[["culture"]] <- factor(df[["culture"]], levels = c("false", "true")) # stored level order
df <- df[stats::complete.cases(df[c("rapid test", "culture")]), , 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("rapid test", "culture")) # infinite values stop the run (registry/errors.yaml)
# %% Test
t <- "rapid test"
r <- "culture"
test_levels <- c("false", "true") # stored level order
ref_levels <- c("false", "true")
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 <- "wilson"
prevalence <- 0.05 # 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 = .80, specificity = 1.00, LR+ = ∞, LR− = 0.20
- Sensitivity
- 0.8000
- Specificity
- 1
- Positive predictive value
- 1
- Negative predictive value
- 0.8696
Effect size
- Diagnostic odds ratio 146.43 95% CI [6.966, 3078.06]
- Youden's J 0.8000 95% CI [0.5976, 1.002]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- No empty cells — Empty false positive cell: likelihood ratios can be infinite or undefined; 0.5 was added to every cell for the DOR.
- 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
| rapid test \ culture | true (condition) | false (no condition) | Total |
|---|---|---|---|
| true (positive) | 12 | 0 | 12 |
| false (negative) | 3 | 20 | 23 |
| Total | 15 | 20 | 35 |
Accuracy measures (95% CI; proportions Wilson)
| Measure | Estimate | CI low | CI high |
|---|---|---|---|
| Sensitivity | 0.8000 | 0.5481 | 0.9295 |
| Specificity | 1 | 0.8389 | 1 |
| Positive predictive value | 1 | 0.7575 | 1 |
| Negative predictive value | 0.8696 | 0.6787 | 0.9546 |
| Accuracy | 0.9143 | 0.7762 | 0.9704 |
| Prevalence (sample) | 0.4286 | 0.2798 | 0.5914 |
| Likelihood ratio + | ∞ | — | — |
| Likelihood ratio − | 0.2000 | 0.0727 | 0.5503 |
| Diagnostic odds ratio | 146.43 | 6.966 | 3078.06 |
| Youden's J | 0.8000 | 0.5976 | 1.002 |
| Balanced accuracy | 0.9000 | 0.7988 | 1.001 |
| PPV at prevalence 0.05 | 1 | — | — |
| NPV at prevalence 0.05 | 0.9896 | — | — |
| F1 score | 0.8889 | — | — |
| Matthews correlation | 0.8341 | — | — |
- Positive test: rapid test = true; condition present: culture = true. Likelihood-ratio intervals: Simel et al. (1991). Prevalence-adjusted predictive values: Mercaldo et al. (2007) logit intervals.
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 94a11659571920b2
# Dataset: rapid_test (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/rapid_test.parquet", columns=["rapid test", "culture"])
n_input = len(df)
df["rapid test"] = pd.Categorical(df["rapid test"], categories=["false", "true"]) # stored level order
df["culture"] = pd.Categorical(df["culture"], categories=["false", "true"]) # stored level order
df = df.dropna(subset=["rapid test", "culture"]) # listwise deletion over the analysis columns
df["rapid test"] = df["rapid test"].cat.remove_unused_categories()
df["culture"] = df["culture"].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, ["rapid test", "culture"]) # infinite values stop the run (registry/errors.yaml)
# %% Test
t, r = "rapid test", "culture"
test_levels = ["false", "true"] # stored level order
ref_levels = ["false", "true"]
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 = "wilson"
prevalence = 0.05 # 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 corrected value is = 146, with an interval from 7 to 3,078. The width tells the real story: a study this small says little about how large the ratio is.
Same measures, two dialects
Readimport numpy as np
from scipy import stats
tp, fp, fn, tn = 231, 32, 27, 54 # the liver scan
se, sp = tp / (tp + fn), tn / (tn + fp)
lr_pos, lr_neg = se / (1 - sp), (1 - se) / sp
dor = (tp * tn) / (fp * fn)
se_log = np.sqrt(1 / tp + 1 / fp + 1 / fn + 1 / tn) # Woolf
z = stats.norm.ppf(0.975)
print(lr_pos, lr_neg, dor, np.exp(np.log(dor) - z * se_log), np.exp(np.log(dor) + z * se_log))tp <- 231; fp <- 32; fn <- 27; tn <- 54 # the liver scan
se <- tp / (tp + fn); sp <- tn / (tn + fp)
lr_pos <- se / (1 - sp); lr_neg <- (1 - se) / sp
dor <- (tp * tn) / (fp * fn)
se_log <- sqrt(1 / tp + 1 / fp + 1 / fn + 1 / tn) # Woolf
z <- qnorm(0.975)
c(lr_pos, lr_neg, dor, exp(log(dor) - z * se_log), exp(log(dor) + z * se_log))Check your understanding
CheckpointCheck yourself
A test has sensitivity 90% and specificity 80%. What is LR+?
Show the answer
Answer: 4.5
0.90 / (1 − 0.80) = 4.5.
Check yourself
The pre-test probability is 20% and LR+ is 4.5. What is the post-test probability after a positive result? Give three decimals.
Show the answer
Answer: 0.529
Pre-test odds are 0.25. Multiplied by 4.5, that's 1.125. As a probability, 1.125 / 2.125.
Check yourself
A result has a likelihood ratio of 1. What does it do?
Show the answer
Answer: a
Multiplying the odds by 1 changes nothing: the result is equally likely with and without the disease.
Check yourself
Why can F1 look good when a model is poor at clearing negatives?
Show the answer
Answer: b
F1 combines precision and recall. Neither uses true negatives, so it can stay high when the positive class is common, whatever happens to the negatives.
Recap
Recap- Multiply pre-test odds by a likelihood ratio to get post-test odds.
- Likelihood ratios leave prevalence out, so you can apply them to your own patients.
- The diagnostic odds ratio, J, F1 and MCC each collapse a trade-off. Report sensitivity and specificity too.
- An empty cell breaks the ratios: read the warning and the interval.
Concepts in this lesson