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 of findings are real vulnerabilities: .
- Sensitivity. When a vulnerability is real, the scanner raises an alert of the time: .
- False-positive rate. When a finding is harmless, it raises an alert of the time: .
(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 ”. 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 . There are alerts and only 95 are real:
More than five of every six alerts are false (), with a detector that “gets right”. Intuition fails, not the detector: we confuse , measuring how good the scanner is on vulnerabilities, with , 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 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 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 occurred discards outcomes outside . What remains is reduced sample space , with the same relative probabilities as before: if two outcomes in were equally likely, they remain so. But they no longer sum to ; they must sum to 1, so divide by . That is all conditioning means.
Condition is essential: without it the ratio is undefined. Conditioning on zero-probability events (for example, “given ” 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 .
Proof
It is nonnegative because and . It satisfies . For countable additivity let be disjoint. Sets are also disjoint, so by -additivity of ,
If , then .
∎Since is a probability, it satisfies all properties of the preceding lesson: , the union bound, inclusion–exclusion, and so on. Just write “ ” after each .
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 (real findings) and one of width (harmless findings). Within each strip, the lower part contains alerts: height in the real strip and in the harmless strip. Then each rectangle’s area is a joint probability: , and likewise for the other three. Conditioning on retains the two alert rectangles and rescales them to sum to 1.
Three readings deserve emphasis:
- Sensitivity moves only the vertical axis of a sliver. At low prevalence, red area is a tiny fraction of the square; increasing sensitivity from to barely increases it (it was already almost full), while blue alert area dominates.
- What matters is the ratio of the two alert areas, versus , not the percentages separately.
- False positives are easy to overlook and costly to pay for. 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 , , and if , also . 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 . For there is nothing to prove. Assume the formula for events. Since for every , assumption ensures all previous conditionals are defined. With , the product rule gives ; replacing with its factorization (the induction hypothesis) gives the formula.
∎The chain rule is a language model
When events are values of discrete variables, , the formula says
and with for masses, . 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 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
which, divided by and averaged over the corpus, is mean cross-entropy per token. Two important observations:
- Order is arbitrary. For two variables, , and in general any of orderings works. Going left to right is an engineering choice, not a law of nature.
- The chain alone saves nothing. A joint table of binary variables has free parameters, and factorization requires conditional probabilities: the same number. With a vocabulary of tokens and just positions, the table would have order 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 is a countable family of pairwise disjoint events with .
The law of total probability decomposes an event by the case in which it occurs.
Proof
Since is a partition, and sets are disjoint. By -additivity and the product rule, .
∎It is a weighted average: is the mean of conditional probabilities with weights , which sum to 1. With expectations this becomes the tower property of conditional expectation. If any had zero probability, simply omit it from the sum because its contribution to is zero.
Bayes’ theorem
The two product-rule forms say . Rearranging one and expanding the denominator with total probability gives the lesson’s central result.
Proof
By the product rule, . Rearrange for (with ) and replace using total probability.
∎This formula is Bayes’ theorem. Each term has a name used constantly: is the prior distribution (what we believed before seeing ), the likelihood (how expected is if holds), the evidence or normalizing constant, and the posterior distribution. Notice the denominator does not depend on : posterior is proportional to prior times likelihood, , and evidence only normalizes it to sum to 1. This proportionality is used throughout Bayesian inference.
With partition and the scanner numbers,
The two denominator terms are exactly the alert areas in the preceding figure. The result is very sensitive to prevalence:
| Prior odds | with sensitivity and false positives | |
|---|---|---|
Only at prevalence does alert precision match sensitivity. Ignoring the base rate (the base-rate fallacy) and treating as (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 are : how many times more likely it is to occur than not. Write both versions of Bayes, for and , and divide: evidence cancels.
The interpretation is clean: each observation multiplies odds by its likelihood ratio, depending only on how much better than explains observed evidence, not on base rate. For the scanner, for an alert and posterior odds are , or probability . If the scanner is silent, the ratio is : vulnerability odds fall to , probability . As probabilities the two effects look very different (alert moves to ; silence moves to ), but in odds they weigh exactly the same: factor upward and factor downward, because sensitivity and false positives give . This symmetry appears only in odds.
Taking logs turns multiplication into addition. Log odds (or logit) are , and the formula reads
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 , as Jaynes measures it in Probability Theory: The Logic of Science (chapter 4). One bit doubles odds and equals dB. For the scanner, prior is bits, an alert adds bits and posterior is bits, or odds of . To reach odds (probability ) would take evidence bits, likelihood ratio , and a single alert gives only . Adding bits also explains why probabilities near and are so “expensive”: moving from to costs bits, twice moving from to .
The inverse logit is the sigmoid, . Thus logistic regression, which models , 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 changed the probability of (the initial 6 moved from to ). 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 rearranged: provides no information about . Proving complements is a guided exercise below; the idea is . Three points are often confused:
- Independent does not mean disjoint. If and both have positive probability, : 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 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, and for measurable (lesson 7), and is what “iid” throughout machine learning means.
Pairwise is not mutual
For a family of events, mutual independence requires equations (subsets of size at least 2: 4 for , 11 for ), not just pair equations. Can the pair equations hold while the triple fails? Yes: the canonical counterexample is parity.
Behavior as the coins move follows in one line. With and , , and for tables one cell suffices (others follow from the preceding theorem): requires , which for is equivalent to , namely . Likewise requires (or 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 is one. Thus we can ask whether two events are independent inside .
This is conditional independence. Once is known, learning changes nothing about . 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, ) and a collider (common effect, ). Conditioning on the common cause blocks dependence; conditioning on the common effect opens it. This is the content of -separation in Bayesian networks.
Evidence adds under conditional independence
Conditional independence generalizes the Bayes section conveniently. Let be a hypothesis and observations.
Proof
Apply Bayes in odds form with . The likelihood ratio of is , and conditional independence (given in the numerator and in the denominator) makes it the product of ratios for each . Take logarithms.
∎This is the formula used by Naive Bayes classifiers and to combine detectors. Both independence assumptions (given and ) 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 fire, actual evidence is that of one, , not : the naive model counts the same evidence twice.
Overconfidence has a concrete consequence for automatic triage: in the figure’s initial scenario the naive model announces where the correct one gives , 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 (theory and practical test scores, for example) and a program admitting highest-scoring candidates. The figure simulates candidates and lets you choose the scoring rule and admitted fraction.
There is an exact formula for the sum rule, and its proof shows why it works.
Proof
and are jointly normal with , hence independent, and . Conditioning on an event depending only on changes neither the law of nor its independence of . Since and , with :
The ratio is . Truncating a normal to a half-line reduces variance, so and .
∎With admitted, correlation among admitted candidates is ; with , . This dependence is created by selection: population correlation remains zero. The mechanism is explaining away: among admitted candidates, a mediocre is explained only by an excellent . 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 . 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 mean “car behind door ” ( each) and mean “host opens door 3 and it has a goat”. With a random host, , and , and Bayes gives . With a knowing host, by contrast, (no alternative) and . 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: . In one day there are legitimate events and one genuinely malicious event, which matches. A match is observed. What is the probability it is malicious? We expect chance matches versus real one, so , not . The fallacy is to read “probability that a legitimate event matches is ” as “probability that a matching event is legitimate is ”. 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 . 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.
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.
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 (the figure’s copy model), and compare naive posterior, which sums both weights, with the correct one using joint likelihood.
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 there is no difference (naive is exact); as 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.
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.
| What | Tool | Notes |
|---|---|---|
| Stable logit and sigmoid | scipy.special.logit, scipy.special.expit | prevent overflow for large |
| Sum of probabilities on log scale | scipy.special.logsumexp | Bayes denominator without underflow |
| Naive Bayes with binary features | sklearn.naive_bayes.BernoulliNB | estimates evidence weights and prior from data |
| Gaussian / categorical Naive Bayes | GaussianNB, CategoricalNB | same conditional-independence assumptions |
| Sequence log probability | torch.log_softmax plus indexing | chain rule in a language model |
| Joint tables and marginalization | np.einsum, np.sum(axis=...) | probabilities of multiple discrete variables |
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
More than one answer may be correct.
Step 1 of 3. How do you express in known terms?
Step 1 of 4. For “conditional but not marginal”, which construction works?
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 resultadoSummary
- (with ) is a probability measure on , rescaled. Every property of holds with “ ”. Iterating the product rule gives , how an autoregressive model defines .
- Total probability, , and Bayes’ theorem, , convert “how likely is evidence if the hypothesis holds” into “how plausible is the hypothesis given evidence”.
- In odds form, posterior = prior , 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 with .
- means . Independence of a family requires a product equality for every subset; pairwise is insufficient (XOR of two coins). Disjoint does not mean independent.
- is independence under , 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 and . Redundant signals are overcounted, producing overconfident probabilities.