Module contents
Lesson 2 of 24Review 75 min

Conditional probability, Bayes' theorem and independence

Conditioning renormalizes the measure over what is known. Review the chain rule, total probability and Bayes’ theorem in odds and log-odds form, using a low-base-rate security-alert triage example. Finish with subtleties of independence: pairwise versus mutual, conditional versus marginal, and Berkson’s paradox.

After this lesson you can

  • Calculate conditional probabilities using the product rule, total probability and Bayes’ theorem.
  • Reason in log-odds and combine conditionally independent evidence by adding log-likelihood ratios.
  • Identify the base-rate fallacy and prosecutor’s fallacy in detection problems.
  • Distinguish pairwise, mutual and conditional independence with explicit counterexamples.
  • Factor a discrete joint distribution using the chain rule.

Before you start

Motivation: one alert among thousands

A static-analysis scanner reviews a repository and examines 10,000 candidate findings. We know three things about it, measured on a manually labeled set:

  • Prevalence (base rate). Only 1 %1\,\% of findings are real vulnerabilities: P(V)=0.01\Pr(V) = 0.01.
  • Sensitivity. When a vulnerability is real, the scanner raises an alert 95 %95\,\% of the time: P(A∣V)=0.95\Pr(A \given V) = 0.95.
  • False-positive rate. When a finding is harmless, it raises an alert 5 %5\,\% of the time: P(A∣¬V)=0.05\Pr(A \given \neg V) = 0.05.

(The figures are illustrative and describe no particular tool.) An alert has just fired. What is the probability it is a real vulnerability? The answer nearly everyone gives, including many technically trained people, is “around 95 %95\,\%”. It is wrong by a factor of six. Count frequencies: of 10,000 findings, 100 are real and the scanner flags 95; of the 9,900 harmless ones it flags 0.05×9 900=4950.05 \times 9\,900 = 495. There are 95+495=59095 + 495 = 590 alerts and only 95 are real:

P(V∣A)=95590≈0.161.\Pr(V \given A) = \frac{95}{590} \approx 0.161.

More than five of every six alerts are false (83.9 %83.9\,\%), with a detector that “gets 95 %95\,\% right”. Intuition fails, not the detector: we confuse P(A∣V)\Pr(A \given V), measuring how good the scanner is on vulnerabilities, with P(V∣A)\Pr(V \given A), what matters to the alert reader. The quantities are related but unequal, and the base rate separates them.

This pattern appears in any detection problem with imbalanced classes: security alert triage, spam filtering, fraud detection, medical tests, language-model security classifiers, anomaly monitoring. Its tools, reviewed here with full measure-theoretic rigor (what can and cannot be claimed, under which assumptions), underpin what follows:

  • The chain rule p(x1,…,xn)=∏ip(xi∣x<i)p(x_1, \dots, x_n) = \prod_i p(x_i \given x_{<i}) is exactly how a language model defines a distribution on sequences (autoregressive factorization).
  • Bayes’ theorem drives Bayesian inference on parameters (prior and posterior) and generative classifiers.
  • Log odds are what logistic regression actually models, and their sum under conditional independence is the Naive Bayes classifier.
  • Conditional independence is the language of Bayesian networks, and its failure causes collider bias.

We work on a probability space (Ω,F,P)(\Omega, \mathcal{F}, \Pr) as in the previous lesson, using only its axioms. The lesson proceeds through conditioning, factoring joint probability, recovering probability from parts, reversing a conditioning (Bayes), when conditioning changes nothing (independence), and when conditioning creates or destroys independence.

Conditioning is renormalization

Knowing event BB occurred discards outcomes outside BB. What remains is reduced sample space BB, with the same relative probabilities as before: if two outcomes in BB were equally likely, they remain so. But they no longer sum to P(B)\Pr(B); they must sum to 1, so divide by P(B)\Pr(B). That is all conditioning means.

Condition P(B)>0\Pr(B) > 0 is essential: without it the ratio is undefined. Conditioning on zero-probability events (for example, “given X=0.3X = 0.3” for a continuous variable) requires another definition, studied with regular conditional distributions and conditional expectation. This lesson uses the elementary definition throughout.

The next result justifies the name “probability” and lets us apply everything already known to P(⋅∣B)\Pr(\cdot \given B).

Proof

It is nonnegative because P(A∩B)≥0\Pr(A \cap B) \ge 0 and P(B)>0\Pr(B) > 0. It satisfies P(Ω∣B)=P(B)/P(B)=1\Pr(\Omega \given B) = \Pr(B)/\Pr(B) = 1. For countable additivity let A1,A2,⋯∈FA_1, A_2, \dots \in \mathcal{F} be disjoint. Sets Ai∩BA_i \cap B are also disjoint, so by σ\sigma-additivity of P\Pr,

P(⋃iAi ∣ B)=P(⋃i(Ai∩B))P(B)=∑iP(Ai∩B)P(B)=∑iP(Ai∣B).\Pr\Big(\bigcup_i A_i \,\Big|\, B\Big) = \frac{\Pr\big(\bigcup_i (A_i \cap B)\big)}{\Pr(B)} = \sum_i \frac{\Pr(A_i \cap B)}{\Pr(B)} = \sum_i \Pr(A_i \given B).

If A⊆BA \subseteq B, then A∩B=AA \cap B = A. ■\blacksquare

∎

Since P(⋅∣B)\Pr(\cdot \given B) is a probability, it satisfies all properties of the preceding lesson: P(Ac∣B)=1−P(A∣B)\Pr(A^c \given B) = 1 - \Pr(A \given B), the union bound, inclusion–exclusion, and so on. Just write “ ∣B\given B ” after each P\Pr.

Bayes as a ratio of areas

There is a way to see the scanner problem without a single formula. Take a unit-area square as sample space. Divide it into a vertical strip of width P(V)\Pr(V) (real findings) and one of width 1−P(V)1 - \Pr(V) (harmless findings). Within each strip, the lower part contains alerts: height P(A∣V)\Pr(A \given V) in the real strip and P(A∣¬V)\Pr(A \given \neg V) in the harmless strip. Then each rectangle’s area is a joint probability: P(V∩A)=P(V)P(A∣V)\Pr(V \cap A) = \Pr(V)\Pr(A \given V), and likewise for the other three. Conditioning on AA retains the two alert rectangles and rescales them to sum to 1.

InteractiveBayes as a ratio of areas
real 1.00 %harmless 99.0 %5.00 % of harmless findings alert(left, 95.0 % of real findings)real16.1 %false alarms83.9 %Only alerts remain; their areas are rescaled to sum to 1.alert proportion in each strip
  • Alert and real: 0.95 %
  • Alert and harmless: 4.95 %
  • Real without alert: 0.050 %
  • Harmless without alert: 94.0 %
P(V∣A)\Pr(V \given A) by prevalence (drag along the curve)
0 %25 %50 %75 %100 %0.1 %1 %10 %50 %prevalence (log scale)16.1 %
Out of 10 000 findings (expected values)
alertno alerttotalreal955100harmless4959 4059 900total5909 41010 000
There are 590 alerts and only 95 are real: 16.1 %16.1\,\%. (Expected, rounded.)
1.00 %
95.0 %
5.00 %
P(A)\Pr(A)5.90 %
P(V∣A)\Pr(V \given A)16.1 %
P(V∣¬A)\Pr(V \given \neg A)0.053 %
Odds of VV: before → after1 : 99 → 1 : 5.21
Likelihood ratio LR\mathrm{LR}19.0
Prevalence at 50% posterior5.00 %
At this prevalence, 83.9 % of alerts are false even though the detector catches 95.0 % of real problems. Half would be real at prevalence 5.00 %.
Areas are joint probabilities: red for real vulnerabilities, blue for harmless findings, saturated color for alerts. Select ‘Condition on alert’: the two alert rectangles are rearranged and rescaled to sum to 1, and P(V∣A)\Pr(V \given A) is the red fraction. At 1 %1\,\% prevalence the red strip is a sliver and most alert area is blue. Lower prevalence to 0.1 %0.1\,\%, maximize sensitivity and check that it barely helps; then lower false positives. The curve shows every case at once, and its 50 %50\,\% crossing is prevalence P(V)=P(A∣¬V)/(P(A∣V)+P(A∣¬V))\Pr(V) = \Pr(A \given \neg V)/(\Pr(A \given V) + \Pr(A \given \neg V)) where true and false alerts match. Enable comparison: dividing false positives by 10 shifts the curve much more than improving sensitivity.

Three readings deserve emphasis:

  1. Sensitivity moves only the vertical axis of a sliver. At low prevalence, red area is a tiny fraction of the square; increasing sensitivity from 95 %95\,\% to 99.9 %99.9\,\% barely increases it (it was already almost full), while blue alert area (1−P(V))P(A∣¬V)(1 - \Pr(V))\Pr(A \given \neg V) dominates.
  2. What matters is the ratio of the two alert areas, P(V)P(A∣V)\Pr(V)\Pr(A \given V) versus P(¬V)P(A∣¬V)\Pr(\neg V)\Pr(A \given \neg V), not the percentages separately.
  3. False positives are easy to overlook and costly to pay for. 5 %5\,\% false alarms seems small, but applies to the vast majority of the population.

Product and chain rules

Rearranging the definition gives the product rule: if P(B)>0\Pr(B) > 0, P(A∩B)=P(B)P(A∣B)\Pr(A \cap B) = \Pr(B)\Pr(A \given B), and if P(A)>0\Pr(A) > 0, also P(A∩B)=P(A)P(B∣A)\Pr(A \cap B) = \Pr(A)\Pr(B \given A). Both hold simultaneously, which makes Bayes work. Iteration factors the probability of an intersection of any number of events.

We call this the probability chain rule.

Proof

Induct on nn. For n=1n = 1 there is nothing to prove. Assume the formula for n−1n - 1 events. Since A1∩⋯∩An−1⊆A1∩⋯∩AkA_1 \cap \cdots \cap A_{n-1} \subseteq A_1 \cap \cdots \cap A_{k} for every k≤n−1k \le n - 1, assumption P(A1∩⋯∩An−1)>0\Pr(A_1 \cap \cdots \cap A_{n-1}) > 0 ensures all previous conditionals are defined. With E=A1∩⋯∩An−1E = A_1 \cap \cdots \cap A_{n-1}, the product rule gives P(E∩An)=P(E)P(An∣E)\Pr(E \cap A_n) = \Pr(E)\Pr(A_n \given E); replacing P(E)\Pr(E) with its factorization (the induction hypothesis) gives the formula. ■\blacksquare

∎

The chain rule is a language model

When events are values of discrete variables, Ak={Xk=xk}A_k = \{X_k = x_k\}, the formula says

P(X1=x1,…,Xn=xn)=∏k=1nP(Xk=xk∣X1=x1,…,Xk−1=xk−1),\Pr(X_1 = x_1, \dots, X_n = x_n) = \prod_{k=1}^n \Pr(X_k = x_k \given X_1 = x_1, \dots, X_{k-1} = x_{k-1}),

and with pp for masses, p(x1,…,xn)=∏kp(xk∣x<k)p(x_1, \dots, x_n) = \prod_k p(x_k \given x_{<k}). This is not a model, but a theorem: every joint distribution on sequences factors this way without independence assumptions. An autoregressive language model merely parameterizes each factor pθ(xk∣x<k)p_\theta(x_k \given x_{<k}) with a network and softmax; the chain ensures the product is a valid distribution on complete sequences and can be sampled left to right, one token at a time. Maximum-likelihood training minimizes

−log⁡pθ(x1,…,xn)=−∑k=1nlog⁡pθ(xk∣x<k),-\log p_\theta(x_1, \dots, x_n) = -\sum_{k=1}^n \log p_\theta(x_k \given x_{<k}),

which, divided by nn and averaged over the corpus, is mean cross-entropy per token. Two important observations:

  • Order is arbitrary. For two variables, p(x,y)=p(x)p(y∣x)=p(y)p(x∣y)p(x, y) = p(x)p(y \given x) = p(y)p(x \given y), and in general any of n!n! orderings works. Going left to right is an engineering choice, not a law of nature.
  • The chain alone saves nothing. A joint table of nn binary variables has 2n−12^n - 1 free parameters, and factorization requires ∑k=1n2k−1=2n−1\sum_{k=1}^n 2^{k-1} = 2^n - 1 conditional probabilities: the same number. With a vocabulary of 50 00050\,000 tokens and just 1010 positions, the table would have order 50 00010≈104750\,000^{10} \approx 10^{47} entries. What makes the model tractable is sharing parameters across all factors (the network) and, in other models, imposing conditional independences, the subject of the conditional-independence section.

Total probability

The product rule reconstructs a probability from its parts. A partition of Ω\Omega is a countable family {Bi}i∈I\{B_i\}_{i \in I} of pairwise disjoint events with ⋃iBi=Ω\bigcup_i B_i = \Omega.

The law of total probability decomposes an event by the case in which it occurs.

Proof

Since {Bi}\{B_i\} is a partition, A=⋃i(A∩Bi)A = \bigcup_i (A \cap B_i) and sets A∩BiA \cap B_i are disjoint. By σ\sigma-additivity and the product rule, P(A)=∑iP(A∩Bi)=∑iP(A∣Bi)P(Bi)\Pr(A) = \sum_i \Pr(A \cap B_i) = \sum_i \Pr(A \given B_i)\Pr(B_i). ■\blacksquare

∎

It is a weighted average: P(A)\Pr(A) is the mean of conditional probabilities P(A∣Bi)\Pr(A \given B_i) with weights P(Bi)\Pr(B_i), which sum to 1. With expectations this becomes the tower property of conditional expectation. If any BiB_i had zero probability, simply omit it from the sum because its contribution to P(A)\Pr(A) is zero.

Bayes’ theorem

The two product-rule forms say P(A∣B)P(B)=P(B∣A)P(A)\Pr(A \given B)\Pr(B) = \Pr(B \given A)\Pr(A). Rearranging one and expanding the denominator with total probability gives the lesson’s central result.

Proof

By the product rule, P(Bj∩A)=P(Bj∣A)P(A)=P(A∣Bj)P(Bj)\Pr(B_j \cap A) = \Pr(B_j \given A)\Pr(A) = \Pr(A \given B_j)\Pr(B_j). Rearrange for P(Bj∣A)\Pr(B_j \given A) (with P(A)>0\Pr(A) > 0) and replace P(A)\Pr(A) using total probability. ■\blacksquare

∎

This formula is Bayes’ theorem. Each term has a name used constantly: P(Bj)\Pr(B_j) is the prior distribution (what we believed before seeing AA), P(A∣Bj)\Pr(A \given B_j) the likelihood (how expected AA is if BjB_j holds), P(A)\Pr(A) the evidence or normalizing constant, and P(Bj∣A)\Pr(B_j \given A) the posterior distribution. Notice the denominator does not depend on jj: posterior is proportional to prior times likelihood, P(Bj∣A)∝P(Bj)P(A∣Bj)\Pr(B_j \given A) \propto \Pr(B_j)\Pr(A \given B_j), and evidence only normalizes it to sum to 1. This proportionality is used throughout Bayesian inference.

With partition {V,¬V}\{V, \neg V\} and the scanner numbers,

P(V∣A)=P(A∣V)P(V)P(A∣V)P(V)+P(A∣¬V)P(¬V)=0.95⋅0.010.95⋅0.01+0.05⋅0.99=0.00950.059≈0.161.\Pr(V \given A) = \frac{\Pr(A \given V)\Pr(V)}{\Pr(A \given V)\Pr(V) + \Pr(A \given \neg V)\Pr(\neg V)} = \frac{0.95 \cdot 0.01}{0.95 \cdot 0.01 + 0.05 \cdot 0.99} = \frac{0.0095}{0.059} \approx 0.161.

The two denominator terms are exactly the alert areas in the preceding figure. The result is very sensitive to prevalence:

P(V)\Pr(V)Prior oddsP(V∣A)\Pr(V \given A) with sensitivity 0.950.95 and false positives 0.050.05
0.1 %0.1\,\%1:9991 : 9991.9 %1.9\,\%
1 %1\,\%1:991 : 9916.1 %16.1\,\%
5 %5\,\%1:191 : 1950.0 %50.0\,\%
10 %10\,\%1:91 : 967.9 %67.9\,\%
50 %50\,\%1:11 : 195.0 %95.0\,\%

Only at prevalence 50 %50\,\% does alert precision match sensitivity. Ignoring the base rate (the base-rate fallacy) and treating P(A∣V)\Pr(A \given V) as P(V∣A)\Pr(V \given A) (transposing the conditional, called the prosecutor’s fallacy in a legal context, discussed at the end) are two sides of the same error.

Odds and log odds: evidence adds

Posterior proportionality gives a cleaner form of Bayes. The odds of event HH are P(H)/P(Hc)\Pr(H)/\Pr(H^c): how many times more likely it is to occur than not. Write both versions of Bayes, for HH and HcH^c, and divide: evidence P(E)\Pr(E) cancels.

P(H∣E)=P(E∣H)P(H)P(E)\Pr(H \given E) = \frac{\Pr(E \given H)\Pr(H)}{\Pr(E)}
Bayes for H; Pr(E) > 0 because Pr(E | H) Pr(H) > 0.
1/4

The interpretation is clean: each observation multiplies odds by its likelihood ratio, depending only on how much better HH than HcH^c explains observed evidence, not on base rate. For the scanner, LR+=0.95/0.05=19\mathrm{LR}_{+} = 0.95/0.05 = 19 for an alert and posterior odds are 199×19=1999≈0.192\frac{1}{99} \times 19 = \frac{19}{99} \approx 0.192, or probability 0.192/(1+0.192)=0.1610.192/(1 + 0.192) = 0.161. If the scanner is silent, the ratio is LR−=0.05/0.95≈0.053\mathrm{LR}_{-} = 0.05/0.95 \approx 0.053: vulnerability odds fall to 1:18811 : 1881, probability 0.053 %0.053\,\%. As probabilities the two effects look very different (alert moves 1 %1\,\% to 16.1 %16.1\,\%; silence moves 1 %1\,\% to 0.053 %0.053\,\%), but in odds they weigh exactly the same: factor 1919 upward and factor 1919 downward, because sensitivity 0.950.95 and false positives 0.050.05 give LR−=1/LR+\mathrm{LR}_{-} = 1/\mathrm{LR}_{+}. This symmetry appears only in odds.

Taking logs turns multiplication into addition. Log odds (or logit) are logit⁡(p)=log⁡p1−p\operatorname{logit}(p) = \log\frac{p}{1 - p}, and the formula reads

logit⁡P(H∣E)⏟posterior=logit⁡P(H)⏟prior+log⁡LR⏟peso de la evidencia.\underbrace{\operatorname{logit}\Pr(H \given E)}_{\text{posterior}} = \underbrace{\operatorname{logit}\Pr(H)}_{\text{prior}} + \underbrace{\log \mathrm{LR}}_{\text{peso de la evidencia}}.

The log-likelihood ratio is called weight of evidence (I. J. Good) and is measured in units of the log base: nats with natural logarithms, bits with base 2, or decibels with 10log⁡1010\log_{10}, as Jaynes measures it in Probability Theory: The Logic of Science (chapter 4). One bit doubles odds and equals 3.013.01 dB. For the scanner, prior is log⁡2(1/99)=−6.63\log_2(1/99) = -6.63 bits, an alert adds log⁡219=+4.25\log_2 19 = +4.25 bits and posterior is −2.38-2.38 bits, or odds of 0.1920.192. To reach odds 1:11 : 1 (probability 1/21/2) would take 6.636.63 evidence bits, likelihood ratio 9999, and a single alert gives only 1919. Adding bits also explains why probabilities near 00 and 11 are so “expensive”: moving from 1 %1\,\% to 99 %99\,\% costs 13.2613.26 bits, twice moving from 1 %1\,\% to 50 %50\,\%.

The inverse logit is the sigmoid, p=σ(z)=1/(1+e−z)p = \sigma(z) = 1/(1 + e^{-z}). Thus logistic regression, which models logit⁡P(Y=1∣x)=w⊤x+b\operatorname{logit}\Pr(Y = 1 \given \vb{x}) = \vb{w}\T\vb{x} + b, is literally an evidence accumulator: each feature adds a contribution to log odds. The next section explains when the sum is exact.

Independence

Until now, conditioning on BB changed the probability of AA (the initial 6 moved from 1/61/6 to 1/21/2). Probability’s most important notion describes cases where nothing changes.

This is event independence, with immediate consequences below.

The first equivalence is the definition of P(A∣B)\Pr(A \given B) rearranged: BB provides no information about AA. Proving complements is a guided exercise below; the idea is P(A∩Bc)=P(A)−P(A∩B)\Pr(A \cap B^c) = \Pr(A) - \Pr(A \cap B). Three points are often confused:

  • Independent does not mean disjoint. If A∩B=∅A \cap B = \emptyset and both have positive probability, P(A∩B)=0≠P(A)P(B)\Pr(A \cap B) = 0 \neq \Pr(A)\Pr(B): they are dependent because knowing one occurred guarantees the other did not.
  • Independence is a property of the measure, not just sets. The same events can be independent under one P\Pr and dependent under another.
  • It concerns products, not causes. Events can be independent without guaranteeing that they “do not influence each other” in the real world, and dependent without either causing the other.

Independence of random variables means independence of all event pairs they generate, {X∈S}\{X \in S\} and {Y∈T}\{Y \in T\} for measurable S,TS, T (lesson 7), and is what “iid” throughout machine learning means.

Pairwise is not mutual

For a family of n≥3n \ge 3 events, mutual independence requires 2n−n−12^n - n - 1 equations (subsets of size at least 2: 4 for n=3n = 3, 11 for n=4n = 4), not just (n2)\binom{n}{2} pair equations. Can the pair equations hold while the triple fails? Yes: the canonical counterexample is parity.

InteractivePairwise is not mutual
Mutual independence: P(x,y,z)=P(x)P(y)P(z)\Pr(x, y, z) = \Pr(x)\Pr(y)\Pr(z) in all eight cells
0.000.1250.250 0 000 0 100 1 00 1 101 0 01 0 11 1 001 1 1values of (x, y, z); recall z = x xor y
  • actual P(x,y,z)\Pr(x, y, z)
  • P(x)P(y)P(z)\Pr(x)\Pr(y)\Pr(z) if mutually independent
X,YX, Y✓ independent
y=0y=10.500.50x=00.50x=10.500.250prod. 0.2500.250prod. 0.2500.250prod. 0.2500.250prod. 0.250maximum deviation 0.000
X,ZX, Z✓ independent
z=0z=10.500.50x=00.50x=10.500.250prod. 0.2500.250prod. 0.2500.250prod. 0.2500.250prod. 0.250maximum deviation 0.000
Y,ZY, Z✓ independent
z=0z=10.500.50y=00.50y=10.500.250prod. 0.2500.250prod. 0.2500.250prod. 0.2500.250prod. 0.250maximum deviation 0.000
0.50
0.50
Condition X,YX, Y on
P(Z=1)\Pr(Z = 1)0.500
Deviation of X,YX, Y0.000
Deviation of X,ZX, Z0.000
Deviation of Y,ZY, Z0.000
Triple deviation0.125
Pairwise / mutualyes / no
All three pairs are independent, yet the triple is not: P(X=1,Y=1,Z=1)=0\Pr(X{=}1, Y{=}1, Z{=}1) = 0 while the marginal product is 0.125. Pairwise independence does not imply mutual independence.
Above, eight joint probabilities P(x,y,z)\Pr(x, y, z) (bars) versus the product of marginals (dashed outline). Mutual independence requires agreement in all eight cells. Below, each pair's 2×22 \times 2 table, with the product of marginals in each cell. At p=q=0.5p = q = 0.5 all three pairs are independent and the triple is not. Move only pp: XX and YY remain independent (chosen separately) while pair (Y,Z)(Y, Z) breaks; move only qq and (X,Z)(X, Z) breaks. Then condition on ZZ: independent XX and YY cease to be independent.

Behavior as the coins move follows in one line. With P(X=1)=p\Pr(X = 1) = p and P(Y=1)=q\Pr(Y = 1) = q, P(Z=1)=p(1−q)+q(1−p)\Pr(Z = 1) = p(1 - q) + q(1 - p), and for 2×22 \times 2 tables one cell suffices (others follow from the preceding theorem): X⊥ ⁣ ⁣ ⁣⊥ZX \indep Z requires p(1−q)=p [ p(1−q)+q(1−p) ]p(1 - q) = p\,[\,p(1-q) + q(1-p)\,], which for p∈(0,1)p \in (0, 1) is equivalent to (1−p)(1−2q)=0(1 - p)(1 - 2q) = 0, namely q=1/2q = 1/2. Likewise Y⊥ ⁣ ⁣ ⁣⊥ZY \indep Z requires p=1/2p = 1/2 (or YY constant). All three pairs are independent simultaneously only when both coins are fair (or in the degenerate case where both are constant), and then the triple fails. Practically, pairwise correlations or independence never suffice for reasoning about multiple variables.

Conditional independence and redundant evidence

Independence is relative to a probability measure, and P(⋅∣C)\Pr(\cdot \given C) is one. Thus we can ask whether two events are independent inside CC.

This is conditional independence. Once CC is known, learning BB changes nothing about AA. It is neither stronger nor weaker than marginal independence: neither implies the other, and conditioning can destroy or create independence.

These are the two basic graph structures: a fork (common cause, D1←V→D2D_1 \leftarrow V \to D_2) and a collider (common effect, X→Z←YX \to Z \leftarrow Y). Conditioning on the common cause blocks dependence; conditioning on the common effect opens it. This is the content of dd-separation in Bayesian networks.

Evidence adds under conditional independence

Conditional independence generalizes the Bayes section conveniently. Let HH be a hypothesis and E1,…,EkE_1, \dots, E_k observations.

Proof

Apply Bayes in odds form with E=E1∩⋯∩EkE = E_1 \cap \cdots \cap E_k. The likelihood ratio of EE is P(E∣H)/P(E∣Hc)\Pr(E \given H)/\Pr(E \given H^c), and conditional independence (given HH in the numerator and HcH^c in the denominator) makes it the product of ratios for each EiE_i. Take logarithms. ■\blacksquare

∎

This is the formula used by Naive Bayes classifiers and to combine detectors. Both independence assumptions (given HH and HcH^c) are necessary, and are violated in practice: redundant signals (two rules triggered by the same syntax, two models trained on the same data) are not conditionally independent even if they appear so. If two copies of one rule with LR=8\mathrm{LR} = 8 fire, actual evidence is that of one, 88, not 8×8=648 \times 8 = 64: the naive model counts the same evidence twice.

InteractiveLog-odds evidence accumulator
Naive: adds every copyPrior−6.6 bitsRule ×3 · alert+9.0 bitsPattern ×1 · alert+3.8 bitsModel ×1 · alert+2.2 bitsPosterior+8.3 bits = 99.7 %Correct: joint likelihoodPrior−6.6 bitsRule ×3 · alert+3.7 bitsPattern ×1 · alert+3.8 bitsModel ×1 · alert+2.2 bitsPosterior+3.0 bits = 89.1 %0.1 %1 %10 %50 %90 %99 %99.9 %−10−50+5+10log odds in bits (bottom) and corresponding probability (top)
  • evidence favoring a real vulnerability
  • evidence favoring a harmless finding
  • prior
  • naive posterior
  • correct posterior
1.00 %
0.80
Scenario
Static rule
LR alert 8.0 · silent 0.22
3 copies
Flow analysis
LR alert 30.0 · silent 0.41
1 copy
Known pattern
LR alert 14.0 · silent 0.32
1 copy
Model score
LR alert 4.5 · silent 0.12
1 copy
Prior log odds−6.6 bits (1 : 99)
Evidence added: naive+15.0 bits
Evidence added: correct+9.7 bits
Naive posterior99.7 %
Correct posterior89.1 %
Excess bits (overconfidence)5.3 bits
The naive model adds 5.3 extra bits: it counts the same evidence repeatedly and moves from 89.1 % to 99.7 %. Copies are not independent given true state, so joint likelihood is not a product.
Each bar is a detector's evidence contribution in bits, chained from the prior. Above, the naive model adds each copy's weight as though independent; below, the correct model uses joint likelihood of copies, assuming each repeats a shared observation with probability ρ\rho. With ρ=0\rho = 0 copies are independent and models match. With ρ=1\rho = 1 they are identical and evidence of mm copies equals one. In ‘Redundant’, three copies of the static rule inflate the naive posterior. Switch to ‘Diverse’ (one detector of each type, no copies) and the excess disappears; make some fire and others silent in ‘Mixed’. Notice how probability saturates at extremes while bits grow without bound.

Overconfidence has a concrete consequence for automatic triage: in the figure’s initial scenario the naive model announces 99.7 %99.7\,\% where the correct one gives 89.1 %89.1\,\%, so alerts are prioritized above others that deserved it more. Below we measure this in a calibration simulation. The practical remedy is to group correlated signals into one (or model their dependence), or learn weights with a discriminative model such as logistic regression, which distributes weight across redundant features instead of counting them all.

Conditioning on a common effect: Berkson’s paradox

The collider is subtler than a common cause because it does not look like an error. Joseph Berkson noted in 1946 that, in hospital data, two diseases independent in the general population may appear associated among admitted patients: admission occurs for someone with either disease, and admission is a common effect. The same mechanism operates in selection depending on two traits at once.

A minimal model: independent traits A,B∼iidN(0,1)A, B \iid \Normal(0, 1) (theory and practical test scores, for example) and a program admitting highest-scoring candidates. The figure simulates 900900 candidates and lets you choose the scoring rule and admitted fraction.

InteractiveBerkson's paradox
  • selected
  • not selected
  • regression of BB on AA (selected)
  • regression (population) and boundary
Theoretical correlation among selected by ff
  • best of the two
  • both high (minimum)
  • only A
  • sum A + B (selected)
The more selective the A+BA + B or best-of-two rule, the more negative the correlation; with only AA or both high it stays at 0.
Select by
20.0 %
Selected / total180 / 900
rr in full population0.040
rr among selected−0.635
Exact theoretical rr−0.641
Among selected, r=−0.64r = −0.64 (theory −0.64), but in the full population r=0.04r = 0.04. AA and BB are independent: selection on their common effect creates dependence.
Points are candidates with independent traits AA and BB; admitted candidates are magenta. With the ‘sum A+BA + B’ rule and 20 %20\,\% admitted, the admitted cloud has a negative slope (magenta line) even though population correlation is almost zero (dashed line). Make the rule more selective and correlation approaches −1-1 in the theoretical-correlation graph. Try other rules: ‘best of the two’ also creates dependence; ‘both high’ (minimum) and ‘only AA’ do not, because the admitted region is a product of one condition on AA and another on BB. Readouts compare sample with exact theoretical correlation; select ‘New sample’ to see variation.

There is an exact formula for the sum rule, and its proof shows why it works.

Proof

S=A+BS = A + B and D=A−BD = A - B are jointly normal with Cov⁡(S,D)=Var⁡A−Var⁡B=0\Cov(S, D) = \Var A - \Var B = 0, hence independent, and Var⁡D=2\Var D = 2. Conditioning on an event depending only on SS changes neither the law of DD nor its independence of SS. Since A=(S+D)/2A = (S + D)/2 and B=(S−D)/2B = (S - D)/2, with v=Var⁡(S∣S≥t)v = \Var(S \given S \ge t):

Var⁡(A∣⋅)=v+24,Cov⁡(A,B∣⋅)=v−24.\Var(A \given \cdot) = \frac{v + 2}{4}, \qquad \Cov(A, B \given \cdot) = \frac{v - 2}{4}.

The ratio is ρt\rho_t. Truncating a normal to a half-line reduces variance, so v<2=Var⁡Sv < 2 = \Var S and ρt<0\rho_t < 0. ■\blacksquare

∎

With f=20 %f = 20\,\% admitted, correlation among admitted candidates is ρ≈−0.64\rho \approx -0.64; with f=5 %f = 5\,\%, −0.76-0.76. This dependence is created by selection: population correlation remains zero. The mechanism is explaining away: among admitted candidates, a mediocre AA is explained only by an excellent BB. Two consequences for data work:

  • Filtering data by a criterion depending on multiple variables can induce correlations absent at source. A quality-threshold “curated” dataset, or training set built from examples passing a filter, is a selected sample. Associations observed in it must be read conditional on passing the filter (selection bias is treated in statistics and causality).
  • Controlling for a variable is not always harmless. Adding a covariate that is a common effect of two others to regression conditions on a collider and can open a dependence path that did not exist.

Three paradoxes to check your understanding

1. Monty Hall with a different host. In the classic version, the host knows where the car is and always opens an unchosen goat door: switching wins with probability 2/32/3. Change the protocol. You chose door 1 and the host opens door 2 or 3 at random, revealing a goat (it could have been the car). Should you switch? Let CiC_i mean “car behind door ii” (P=1/3\Pr = 1/3 each) and G3G_3 mean “host opens door 3 and it has a goat”. With a random host, P(G3∣C1)=1/2\Pr(G_3 \given C_1) = 1/2, P(G3∣C2)=1/2\Pr(G_3 \given C_2) = 1/2 and P(G3∣C3)=0\Pr(G_3 \given C_3) = 0, and Bayes gives P(C1∣G3)=(1/3)(1/2)(1/3)(1/2)+(1/3)(1/2)=12\Pr(C_1 \given G_3) = \frac{(1/3)(1/2)}{(1/3)(1/2) + (1/3)(1/2)} = \frac{1}{2}. With a knowing host, by contrast, P(G3∣C2)=1\Pr(G_3 \given C_2) = 1 (no alternative) and P(C1∣G3)=1/61/6+1/3=13\Pr(C_1 \given G_3) = \frac{1/6}{1/6 + 1/3} = \frac{1}{3}. The same observed event, “a goat behind door 3”, has different likelihoods according to the generating protocol. Without knowing how data are generated, Bayes cannot be applied. You will check this by simulation below.

2. The prosecutor’s fallacy in security. An indicator of compromise (IOC), for example a malicious artifact signature, matches one in a million legitimate events by chance: P(coincide∣legıˊtimo)=10−6\Pr(\text{coincide} \given \text{legítimo}) = 10^{-6}. In one day there are 10710^7 legitimate events and one genuinely malicious event, which matches. A match is observed. What is the probability it is malicious? We expect ≈10\approx 10 chance matches versus 11 real one, so P(malicioso∣coincide)≈1/11≈9 %\Pr(\text{malicioso} \given \text{coincide}) \approx 1/11 \approx 9\,\%, not 1−10−61 - 10^{-6}. The fallacy is to read “probability that a legitimate event matches is 10−610^{-6}” as “probability that a matching event is legitimate is 10−610^{-6}”. This transposes the conditional and is disastrous at such low base rates.

3. A real case combining both. In the Sally Clark case (UK, convicted in 1999 of the deaths of her two children), an expert presented “one in 73 million” as the probability of two sudden deaths in one family, obtained by squaring 1/85431/8543. That assumes the two deaths are independent, a strong and probably false assumption (shared genetic and environmental factors exist); even if correct, the figure is probability of evidence given innocence, not innocence given evidence, which also needed comparison with the very small probability of double murder. The Royal Statistical Society criticized the reasoning in a 2001 statement and the conviction was overturned in 2003. It is the most-cited example of two errors from this lesson—assuming independence and transposing a conditional—in one argument.

Implementation from scratch

First, Bayes’ theorem for the scanner and a simulation checking it by frequencies. The header function is used throughout the rest.

[ ]Bayes and verification by simulationBrowser
import numpy as np

def posterior(prior, sens, fpr):
    """P(V | alerta) por Bayes, con la ley de la probabilidad total en el denominador."""
    evidencia = prior * sens + (1 - prior) * fpr
    return prior * sens / evidencia

print("posterior exacto:", round(posterior(0.01, 0.95, 0.05), 4))

rng = np.random.default_rng(7)
n = 1_000_000
es_real = rng.random(n) < 0.01                        # tasa base
alerta = np.where(es_real, rng.random(n) < 0.95, rng.random(n) < 0.05)
n_alertas, n_reales = alerta.sum(), (alerta & es_real).sum()
print(f"alertas: {n_alertas}   reales entre ellas: {n_reales}   precisión empírica: {n_reales / n_alertas:.4f}")
print(f"P(V | sin alerta) empírica: {(~alerta & es_real).sum() / (~alerta).sum():.5f}   exacta: {0.01 * 0.05 / (0.01 * 0.05 + 0.99 * 0.95):.5f}")

print("\nprevalencia -> precisión de una alerta")
for pi in [0.001, 0.01, 0.05, 0.1, 0.5]:
    print(f"  {pi:6.3f}  ->  {posterior(pi, 0.95, 0.05):.3f}")

Now the log-odds version with several conditionally independent detectors. Simulate a stream of findings, compute posterior by adding evidence weights, and measure calibration: grouping alerts by predicted probability, observed frequency of real vulnerabilities should match prediction.

[ ]Bayesian triage: adding log odds and calibrationBrowser
import numpy as np

def logit(p): return np.log(p / (1 - p))
def expit(z): return 1 / (1 + np.exp(-z))

DET = {"regla": (0.80, 0.10), "flujo": (0.60, 0.02), "patron": (0.70, 0.05), "modelo": (0.90, 0.20)}
prior = 0.01

def peso(sens, fpr, salta):
    """log LR de una observación (nats): log(sens/fpr) si salta, log((1-sens)/(1-fpr)) si calla."""
    return np.where(salta, np.log(sens / fpr), np.log((1 - sens) / (1 - fpr)))

rng = np.random.default_rng(11)
n = 400_000
es_real = rng.random(n) < prior
# cada detector se activa con su propia tasa, SOLO en función de la clase: independencia condicional
X = np.column_stack([np.where(es_real, rng.random(n) < s, rng.random(n) < f) for s, f in DET.values()])

z = logit(prior) + sum(peso(s, f, X[:, j]) for j, (s, f) in enumerate(DET.values()))
p_hat = expit(z)

# comprobación: la suma de log-odds es el mismo posterior que Bayes con la verosimilitud conjunta
patron = X[0]
lik_v = np.prod([s if a else 1 - s for a, (s, f) in zip(patron, DET.values())])
lik_n = np.prod([f if a else 1 - f for a, (s, f) in zip(patron, DET.values())])
bayes = prior * lik_v / (prior * lik_v + (1 - prior) * lik_n)
print("patrón del primer hallazgo:", patron.astype(int), "  suma de log-odds:", round(float(p_hat[0]), 6), "  Bayes conjunto:", round(float(bayes), 6))

def calibracion(p, y, bordes):
    print("   p prevista   hallazgos   media prevista   frecuencia observada")
    for a, b in zip(bordes[:-1], bordes[1:]):
        m = (p >= a) & (p < b)
        if m.sum() >= 30:
            print(f"   [{a:4.2f},{b:4.2f})  {m.sum():9d}   {p[m].mean():14.3f}   {y[m].mean():20.3f}")

calibracion(p_hat, es_real, [0, 0.01, 0.05, 0.2, 0.5, 0.8, 0.95, 1.0001])
logloss = -np.mean(np.where(es_real, np.log(p_hat), np.log(1 - p_hat)))
print(f"log-loss del posterior exacto: {logloss:.4f}")

The result is as expected: under conditional independence, posterior is calibrated in every band (mean prediction matches observed frequency apart from sampling noise in bands with few cases). Now break the assumption. Add a replica of the static rule: each of two copies repeats a shared observation with probability ρ\rho (the figure’s copy model), and compare naive posterior, which sums both weights, with the correct one using joint likelihood.

[ ]Correlated detectors: overconfidenceBrowser
import numpy as np

def logit(p): return np.log(p / (1 - p))
def expit(z): return 1 / (1 + np.exp(-z))
def peso(sens, fpr, salta): return np.where(salta, np.log(sens / fpr), np.log((1 - sens) / (1 - fpr)))

def lik_par(x1, x2, p1, rho):
    """P(x1, x2 | clase) cuando x2 repite el resultado z de la observación compartida con prob. rho."""
    tot = 0.0
    for z in (0, 1):
        pz = p1 if z == 1 else 1 - p1
        f1 = rho * (x1 == z) + (1 - rho) * np.where(x1 == 1, p1, 1 - p1)
        f2 = rho * (x2 == z) + (1 - rho) * np.where(x2 == 1, p1, 1 - p1)
        tot = tot + pz * f1 * f2
    return tot

sens, fpr = 0.80, 0.10          # la regla estática y su copia
s_fl, f_fl = 0.60, 0.02         # un tercer detector, independiente de los otros dos
prior, n = 0.01, 400_000
rng = np.random.default_rng(5)

for rho in [0.0, 0.5, 0.9]:
    es_real = rng.random(n) < prior
    p1 = np.where(es_real, sens, fpr)
    z0 = rng.random(n) < p1                                          # observación compartida
    x1 = np.where(rng.random(n) < rho, z0, rng.random(n) < p1)       # cada copia repite z0 con prob. rho
    x2 = np.where(rng.random(n) < rho, z0, rng.random(n) < p1)       # o da una respuesta propia
    x3 = np.where(es_real, rng.random(n) < s_fl, rng.random(n) < f_fl)

    z_ing = logit(prior) + peso(sens, fpr, x1) + peso(sens, fpr, x2) + peso(s_fl, f_fl, x3)
    lr_par = lik_par(x1.astype(int), x2.astype(int), sens, rho) / lik_par(x1.astype(int), x2.astype(int), fpr, rho)
    z_cor = logit(prior) + np.log(lr_par) + peso(s_fl, f_fl, x3)
    p_ing, p_cor = expit(z_ing), expit(z_cor)

    alta = p_ing > 0.9                                              # lo que el modelo ingenuo llama «casi seguro»
    ll = lambda p: -np.mean(np.where(es_real, np.log(p), np.log(1 - p)))
    print(f"rho = {rho:.1f}   con p_ingenuo > 0.9: {alta.sum():5d} hallazgos | prevista ingenua {p_ing[alta].mean():.3f}"
          f" | prevista correcta {p_cor[alta].mean():.3f} | frecuencia observada {es_real[alta].mean():.3f}"
          f" | log-loss ingenuo {ll(p_ing):.4f} vs correcto {ll(p_cor):.4f}")

With ρ=0\rho = 0 there is no difference (naive is exact); as ρ\rho rises, the probability naive calls “almost certain” diverges from observed frequency, while the joint-likelihood model remains calibrated and naive log loss worsens. This is the measured version of the accumulator figure.

Finally, paradoxes by simulation: Monty Hall with the two host protocols.

[ ]Monty Hall: protocol mattersBrowser
import numpy as np

rng = np.random.default_rng(3)
n = 600_000
coche = rng.integers(0, 3, n)                  # puertas 0, 1, 2; tú eliges siempre la 0

# Protocolo A: el presentador sabe dónde está el coche y abre una puerta con cabra entre la 1 y la 2
abre_a = np.where(coche == 0, rng.integers(1, 3, n), 3 - coche)       # si el coche está en 1 abre la 2, y viceversa
cambio_a = 3 - abre_a                          # la puerta que queda cerrada, a la que se cambia
print("presentador que sabe:  cambiar gana", round(np.mean(cambio_a == coche), 4))

# Protocolo B: abre al azar la 1 o la 2; nos quedamos con los casos en que NO era el coche
abre_b = rng.integers(1, 3, n)
con_cabra = abre_b != coche
print(f"presentador al azar:   cambiar gana {np.mean(coche[con_cabra] != 0):.4f}   (casos con cabra: {con_cabra.mean():.3f} del total)")

The professional version

The above uses a few NumPy, SciPy and scikit-learn functions. Only convenience and numerical stability change.

WhatToolNotes
Stable logit and sigmoidscipy.special.logit, scipy.special.expitprevent overflow for large ∣z∣\abs{z}
Sum of probabilities on log scalescipy.special.logsumexpBayes denominator without underflow
Naive Bayes with binary featuressklearn.naive_bayes.BernoulliNBestimates evidence weights and prior from data
Gaussian / categorical Naive BayesGaussianNB, CategoricalNBsame conditional-independence assumptions
Sequence log probabilitytorch.log_softmax plus indexingchain rule in a language model
Joint tables and marginalizationnp.einsum, np.sum(axis=...)probabilities of multiple discrete variables
[ ]BernoulliNB reproduces the sum of log oddsBrowser
import numpy as np
from scipy.special import expit, logit
from sklearn.naive_bayes import BernoulliNB

rng = np.random.default_rng(11)
DET = [(0.80, 0.10), (0.60, 0.02), (0.70, 0.05), (0.90, 0.20)]
prior, n = 0.01, 400_000
y = rng.random(n) < prior
X = np.column_stack([np.where(y, rng.random(n) < s, rng.random(n) < f) for s, f in DET]).astype(int)

nb = BernoulliNB(alpha=1e-6).fit(X, y)         # alpha casi 0: sin suavizado de Laplace
p_nb = nb.predict_proba(X)[:, 1]

# la misma cuenta a mano, con los parámetros verdaderos
z = logit(prior) + sum(np.where(X[:, j] == 1, np.log(s / f), np.log((1 - s) / (1 - f))) for j, (s, f) in enumerate(DET))
p_mano = expit(z)
print("diferencia máxima entre BernoulliNB y la cuenta a mano:", float(np.abs(p_nb - p_mano).max()))
print("prior estimado:", round(float(np.exp(nb.class_log_prior_[1])), 4), "  sensibilidades estimadas:", np.round(np.exp(nb.feature_log_prob_[1]), 3))

BernoulliNB estimates the prior and each detector’s probabilities from data, and its predict_proba is exactly the posterior under conditional independence, with estimated weights. Small differences from hand calculation come from estimating parameters on a finite sample. In PyTorch, a language model’s chain rule is this, without executing:

import torch

# logits: (T, V) con las predicciones del modelo para cada posición; tokens: (T,) los tokens reales
logp = torch.log_softmax(logits, dim=-1)                       # log p(. | x_<k) para cada posición k
seq_logp = logp[torch.arange(len(tokens)), tokens].sum()       # log p(x_1..x_T) = suma de log p(x_k | x_<k)
loss = -seq_logp / len(tokens)                                 # entropía cruzada media por token

Common errors

Exercises

NumericPrecision of an alert
Prevalence P(V)=0.01\Pr(V) = 0.01, sensitivity P(A∣V)=0.95\Pr(A \given V) = 0.95 and false-positive rate P(A∣¬V)=0.05\Pr(A \given \neg V) = 0.05. Calculate P(V∣A)\Pr(V \given A).
NumericThe chain rule in a language model
An autoregressive model assigns four-token sequence x1x2x3x4x_1 x_2 x_3 x_4 conditional probabilities p(x1)=0.5p(x_1) = 0.5, p(x2∣x1)=0.25p(x_2 \given x_1) = 0.25, p(x3∣x1,x2)=0.8p(x_3 \given x_1, x_2) = 0.8 and p(x4∣x1,x2,x3)=0.1p(x_4 \given x_1, x_2, x_3) = 0.1. What is mean cross-entropy per token in bits?
NumericA second independent detector
After the first alert, posterior is 0.1610.161. A second detector conditionally independent of the first given class has sensitivity 0.90.9 and false-positive rate 0.10.1, and also fires. What is P(V∣las dos alertas)\Pr(V \given \text{las dos alertas}) now?
NumericHow many detectors are needed?
Each detector has LR=19\mathrm{LR} = 19 when it fires, and detectors are conditionally independent given class. With prevalence 1 %1\,\%, what is the minimum number that must fire for P(V∣alertas)≥0.99\Pr(V \given \text{alertas}) \ge 0.99?
NumericThe prosecutor’s fallacy in numbers
A signature matches one in every 10 00010\,000 legitimate events by chance. There are 10610^6 events total, one malicious (which always matches). If all events are equally likely a priori and a match is observed, what is the probability it is malicious?
QuizMonty Hall with a random host
You choose door 1 of three, with a car behind one. The host, who does not know where the car is, opens door 2 or 3 at random: it is 3 and has a goat. What is the probability of winning if you switch to door 2?
QuizTrue or false?
Which statements hold for events on the same probability space?

More than one answer may be correct.

QuizSelection by sum
A selective program admits candidates with highest nota teoˊrica+nota praˊctica\text{nota teórica} + \text{nota práctica}. In the candidate population the scores are independent. An analyst examines only admitted candidates and finds a strong negative correlation. Which conclusion is correct?
ProofIndependence passes to complements
Prove: If AA and BB are independent, so are AA and BcB^c, and AcA^c and BcB^c.
0
Assume P(A∩B)=P(A)P(B)\Pr(A \cap B) = \Pr(A)\Pr(B).

Step 1 of 3. How do you express P(A∩Bc)\Pr(A \cap B^c) in known terms?

ProofConditional and marginal do not imply each other
Prove: Conditional independence does not imply marginal independence, and marginal does not imply conditional independence.
0
Construct two explicit examples, one per direction.

Step 1 of 4. For “conditional but not marginal”, which construction works?

CodeIndependences of a three-variable joint table
Implement independencias(P, tol=1e-9). P is an array of shape (a, b, c) with joint probabilities of three discrete variables X0, X1, X2 (nonnegative and summing to 1). Return a set of strings with all independences: for each marginally independent pair i < j, string 'Xi _|_ Xj'; and for each pair i < j independent given the third variable Xk, string 'Xi _|_ Xj | Xk'. Conditional independence given Xk requires P(xi, xj | xk) = P(xi | xk) P(xj | xk) for every value xk with P(Xk = xk) > 0 (zero-probability values are ignored). Quantities are equal if they differ by less than tol.
import numpy as np

def independencias(P, tol=1e-9):
  """Conjunto de cadenas con las independencias marginales y condicionales (dada la tercera variable)."""
  P = np.asarray(P, dtype=float)
  resultado = set()
  # tu código: recorre los pares (i, j) con i < j y la variable restante k;
  # marginal: compara la tabla conjunta de (Xi, Xj) con el producto de sus marginales
  # condicional: haz lo mismo dentro de cada rebanada con P(Xk = v) > 0, renormalizada
  return resultado
Shift+Enter to run

Summary

Key idea
Conditioning renormalizes the measure over what we know; Bayes reverses a conditional using base rate and likelihood, and in log odds evidence adds, but only while signals are conditionally independent given the hypothesis.
  • P(A∣B)=P(A∩B)/P(B)\Pr(A \given B) = \Pr(A \cap B)/\Pr(B) (with P(B)>0\Pr(B) > 0) is a probability measure on BB, rescaled. Every property of P\Pr holds with “ ∣B\given B ”. Iterating the product rule gives P(⋂kAk)=∏kP(Ak∣A1∩⋯∩Ak−1)\Pr(\bigcap_k A_k) = \prod_k \Pr(A_k \given A_1 \cap \cdots \cap A_{k-1}), how an autoregressive model defines p(x1,…,xn)p(x_1, \dots, x_n).
  • Total probability, P(A)=∑iP(A∣Bi)P(Bi)\Pr(A) = \sum_i \Pr(A \given B_i)\Pr(B_i), and Bayes’ theorem, P(Bj∣A)∝P(A∣Bj)P(Bj)\Pr(B_j \given A) \propto \Pr(A \given B_j)\Pr(B_j), convert “how likely is evidence if the hypothesis holds” into “how plausible is the hypothesis given evidence”.
  • In odds form, posterior = prior ×\times LR\mathrm{LR}, and in log odds, posterior = prior ++ weight of evidence. At low prevalence, a detector with good sensitivity and few false positives has low precision: base rate dominates. Do not confuse P(A∣V)\Pr(A \given V) with P(V∣A)\Pr(V \given A).
  • A⊥ ⁣ ⁣ ⁣⊥BA \indep B means P(A∩B)=P(A)P(B)\Pr(A \cap B) = \Pr(A)\Pr(B). Independence of a family requires a product equality for every subset; pairwise is insufficient (XOR of two coins). Disjoint does not mean independent.
  • A⊥ ⁣ ⁣ ⁣⊥B∣CA \indep B \given C is independence under P(⋅∣C)\Pr(\cdot \given C), neither implying nor implied by marginal independence: a common cause makes dependent variables conditionally independent, and a common effect makes independent variables dependent (Berkson’s paradox, selection bias).
  • Adding log-likelihood ratios is exact only if signals are conditionally independent given HH and HcH^c. Redundant signals are overcounted, producing overconfident probabilities.