Skip to content

Conditional probability and Bayes' rule

The chance of A given B isn't the chance of B given A. Work it out with counts of people, then with Bayes' rule, and see how the same trap catches p-values.

Introductory ~11 min9 steps

What runs in CodeSplash

You will be able to

  • Compute a conditional probability from a table of counts
  • Apply Bayes' rule to reverse a conditional probability
  • Avoid transposing the conditional, in tests and in p-values

Read first

01

Restrict the world

Read

A conditional probabilityConditional probabilityHow likely A is among only the cases where B happened. Pr⁡(A∣B)\Pr(A \mid B) asks how likely AA is, among only the cases where BB happened.

Pr⁡(A∣B)=Pr⁡(A and B)Pr⁡(B)\Pr(A \mid B) = \frac{\Pr(A \text{ and } B)}{\Pr(B)}

Think of it as shrinking the world to BB and asking what share of that smaller world is AA.

02

Are these the same?

Predict

Predict first

Among people with a disease, 90% test positive. Does that mean about 90% of people who test positive have the disease?

Yes: they must be about the sameNo: they can be far apart
Reveal

No. Pr⁡(positive∣disease)\Pr(\text{positive} \mid \text{disease}) and Pr⁡(disease∣positive)\Pr(\text{disease} \mid \text{positive}) can be far apart. All cats are mammals, and few mammals are cats. The next step shows how far apart they get with a real test.

03

Grow the tree

Explore

Follow the people down each branch. Guess first, then change Base rate P(D). Compare P(D | +) with P(+ | D).

AExplorable · The conditional probability tree

If a test is positive, how likely is the condition — and why is that not the test's sensitivity?

A person tests positive. What is the chance they have the condition?

0.50
How sure?
0.020
0.90
0.90
1000
1000 people20.0 with itP(D) = 0.020980.0 without1 − P(D)18.0 test positiveP(+ | D) = 0.902.0 test negative98.0 test positiveP(+ | not D) = 0.10882.0 test negative

P(D | +) = 18.0 / (18.0 + 98.0) = 0.155. Reading the tree the other way round gives P(+ | D) = 0.90: the two are not the same question.

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

04

Count people, not percentages

Read

Take 1,000 people, with 2% having the disease, and a test that has 90% sensitivity and 90% specificity.

Reversing a conditional by counting

Count each group, and try the last step yourself.

  1. 20 people have the disease, and 18 of them test positive.
  2. 980 people don't, and 98 of them test positive anyway.
  3. Try this step yourself, then reveal it
    Of the 18+98=11618 + 98 = 116 positives, 18 have the disease: 18/116≈0.1618 / 116 \approx 0.16.
05

Bayes' rule

Read

The same arithmetic as a formula is Bayes' ruleBayes' ruleThe rule that reverses a conditional probability, using a base rate.:

Pr⁡(D∣+)=Pr⁡(+∣D) Pr⁡(D)Pr⁡(+∣D) Pr⁡(D)+Pr⁡(+∣not D) Pr⁡(not D)\Pr(D \mid +) = \frac{\Pr(+ \mid D)\,\Pr(D)}{\Pr(+ \mid D)\,\Pr(D) + \Pr(+ \mid \text{not } D)\,\Pr(\text{not } D)}

Pr⁡(D)\Pr(D) is the prior belief, before the test. The result is the posterior. Same idea, in words: new belief is old belief, reweighted by how well each explanation predicts what you saw.

06

The same trap in p-values

Explore

A p-value is about the data given the null: Pr⁡(data this extreme∣H0)\Pr(\text{data this extreme} \mid H_0). Many people read it as Pr⁡(H0∣data)\Pr(H_0 \mid \text{data}). Change Share of real effects to see how far apart the two can be.

BExplorable · P(H₀ | p < .05)

When p < .05, how likely is it that there was no effect after all?

Of the results with p < .05, what share come from true nulls?

0.50
How sure?
0.20
0.50
30
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

07

Check your reading

Checkpoint

Check yourself

Of 200 customers, 50 bought a warranty, and 20 of those 50 filed a claim. What is Pr⁡(claim∣warranty)\Pr(\text{claim} \mid \text{warranty})?

Show the answer

Answer: 0.4

Shrink the world to the 50 warranty buyers: 20/50=0.420 / 50 = 0.4.

Check yourself

A condition affects 10% of people. A test has 90% sensitivity and 90% specificity. What is the chance of having the condition, given a positive test?

Show the answer

Answer: 0.5

Out of 1,000: 100 have it, and 90 test positive. Of the 900 without it, 90 test positive. So 90/180=0.590 / 180 = 0.5.

Check yourself

A study reports p = 0.01. Which reading is right?

Show the answer

Answer: b

The p-value conditions on the null, and doesn't give a probability for it. To go the other way you'd need a prior: that's Bayes' rule again.

08

Try it with a real test

In the app

Diagnostic accuracy in Analyze reports both directions. For a liver scan, sensitivity is 89.5%, the chance of a positive scan given disease. The positive predictive value is 87.8%, the chance of disease given a positive scan.

Diagnostic accuracyRecorded · Python and R agreeRecorded 2026-11-17 · 43 values compared
R

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

Confusion matrix: scan against pathologyHow often is each class predicted correctly, which errors does the model make, and what do sensitivity, specificity, precision and the other rates come to?

Positive: pathology = abnormal (reference) and scan = abnormal (test).

View data
Reference: pathologyCountTest: scan
Positive231Positive
Positive27Negative
Negative32Positive
Negative54Negative

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 \ pathologyabnormal (condition)normal (no condition)Total
abnormal (positive)23132263
normal (negative)275481
Total25886344

Accuracy measures (95% CI; proportions Clopper–Pearson)

MeasureEstimateCI lowCI high
Sensitivity0.89530.85140.9299
Specificity0.62790.51700.7298
Positive predictive value0.87830.83260.9153
Negative predictive value0.66670.55320.7676
Accuracy0.82850.78440.8668
Prevalence (sample)0.75000.70080.7949
Likelihood ratio +2.4061.8233.176
Likelihood ratio −0.16670.11260.2467
Diagnostic odds ratio14.4387.99026.089
Youden's J0.52330.41450.6320
Balanced accuracy0.76160.70720.8160
F1 score0.8868——
Matthews correlation0.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
))
Python

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 \ pathologyabnormal (condition)normal (no condition)Total
abnormal (positive)23132263
normal (negative)275481
Total25886344

Accuracy measures (95% CI; proportions Clopper–Pearson)

MeasureEstimateCI lowCI high
Sensitivity0.89530.85140.9299
Specificity0.62790.51700.7298
Positive predictive value0.87830.83260.9153
Negative predictive value0.66670.55320.7676
Accuracy0.82850.78440.8668
Prevalence (sample)0.75000.70080.7949
Likelihood ratio +2.4061.8233.176
Likelihood ratio −0.16670.11260.2467
Diagnostic odds ratio14.4387.99026.089
Youden's J0.52330.41450.6320
Balanced accuracy0.76160.70720.8160
F1 score0.8868——
Matthews correlation0.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,
})
09

Recap

Recap
  • Pr⁡(A∣B)\Pr(A \mid B) shrinks the world to BB. It usually differs from Pr⁡(B∣A)\Pr(B \mid A).
  • To reverse a conditional, count people, or use Bayes' rule with a base rate.
  • A p-value is Pr⁡(data∣H0)\Pr(\text{data} \mid H_0). It isn't Pr⁡(H0∣data)\Pr(H_0 \mid \text{data}).

Concepts in this lesson