Mathematical Foundations

IV.13 · Probability

What changes when two variables share one outcome?

Move probability mass between cells, sum away one coordinate, then restrict to a row or column. The same table answers joint, marginal, and conditional questions.

One table, three distribution views

Exact U,V joint table and marginals · select a row, column or cell
U ↓ / V →Row mass
0.25
0.5
0.25
Column mass0.250.50.251
V = -1 given U = -1= 0.5
V = 0 given U = -1= 0.5
V = 1 given U = -1= 0

U=-1, V=-1: exact joint mass 0.125; U=-1, V=0: exact joint mass 0.125; U=-1, V=1: exact joint mass 0; U=0, V=-1: exact joint mass 0.125; U=0, V=0: exact joint mass 0.25; U=0, V=1: exact joint mass 0.125; U=1, V=-1: exact joint mass 0; U=1, V=0: exact joint mass 0.125; U=1, V=1: exact joint mass 0.125. Dependent U and V. Row and column marginals each sum to one. Conditioning on U = -1 divides the retained row by 0.25.

Selected joint cell
0.125
Selected row marginal
0.25
Selected column marginal
0.25
Column value given selected row
0.5
Row value given selected column
0.5

= exact model quantity · ≈ numerical companion or observed estimate

from 0 to 100, whole numbers only

Dependent U and V. Row and column marginals each sum to one. Conditioning on U = -1 divides the retained row by 0.25.
P(U=ui)=∑jpij,P(V=vj)=∑ipijP(U=u_i)=\sum_jp_{ij},\qquad P(V=v_j)=\sum_ip_{ij}
P(V=−1∣U=−1)=0.1250.25=0.5P(V=-1\mid U=-1)=\frac{0.125}{0.25}=0.5
U⊥V  ⟺  pij=P(U=ui)P(V=vj)for all i,jU\perp V\iff p_{ij}=P(U=u_i)P(V=v_j)\quad\text{for all }i,j

Normalize the nine joint weights

The table is an indexed U,V outcome model. Nonnegative raw weights divide by their positive total.

∑i,jpij=1\sum_{i,j}p_{ij}=1

Inspect the nine raw weights [1,1,0; 1,2,1; 0,1,1]. Select a row or column and compare its marginal mass with the conditional distribution inside it.

Predict whether the upper-left cell has the product of its row and column masses. Then select the top row: which denominator should replace the complete table total?

Intuition: the table keeps the pairing

A marginal distribution describes one variable on its own. It does not say which values occur together. Two households can have the same distribution of daily electricity use and different relationships between morning and evening use. A joint table preserves those pairings.

Each cell represents one pair (U,V)(U,V). A row collects all pairs with a particular UU; a column collects all pairs with a particular VV. Summing a row removes the VV coordinate. Conditioning on that row instead keeps its internal proportions and rescales the retained mass to one.

Definition

For finite variables, the joint PMF is

pij=P(U=ui,V=vj),pij≥0,∑i∑jpij=1.p_{ij}=\mathbb P(U=u_i,V=v_j),\qquad p_{ij}\geq0,\qquad\sum_i\sum_jp_{ij}=1.

The marginals sum across the unobserved coordinate:

pU(ui)=∑jpij,pV(vj)=∑ipij.p_U(u_i)=\sum_jp_{ij},\qquad p_V(v_j)=\sum_ip_{ij}.

If pU(ui)>0p_U(u_i)>0, the conditional PMF of VV given U=uiU=u_i is

pV∣U(vj∣ui)=pijpU(ui).p_{V\mid U}(v_j\mid u_i)=\frac{p_{ij}}{p_U(u_i)}.

The analogous column formula divides by pV(vj)>0p_V(v_j)>0. A zero marginal makes this finite conditioning formula undefined; it does not produce an all-zero or uniform distribution.

Mechanics: one normalization, then a restriction

The stage uses rows and columns at latent values −1,0,1-1,0,1. Its canonical raw weights are [1,1,0;1,2,1;0,1,1][1,1,0;1,2,1;0,1,1], with total 88. Raw weights express relative masses; the model explicitly divides every cell by the complete positive total.

Select a cell to edit its nonnegative integer weight. Row and column selectors choose the conditioning event. Read joint cell masses, both marginal distributions, and the selected conditional distribution together. Zero cells are valid; making the entire table zero is invalid. Reset restores the nine canonical weights and the canonical selections.

The independent example uses outer-product weights [1,2,1;2,4,2;1,2,1][1,2,1;2,4,2;1,2,1]. Its total is 1616. Its marginal distributions match the canonical ones even though its joint masses differ.

Derivation: why the conditional row sums to one

For a positive-mass row, its conditional masses satisfy

∑jpV∣U(vj∣ui)=∑jpijpU(ui)=1.\sum_jp_{V\mid U}(v_j\mid u_i) =\frac{\sum_jp_{ij}}{p_U(u_i)}=1.

Multiplying the conditional formula back by its denominator gives the product rule

pij=pU(ui) pV∣U(vj∣ui).p_{ij}=p_U(u_i)\,p_{V\mid U}(v_j\mid u_i).

Independence requires every joint cell to factor:

pij=pU(ui)pV(vj)for all i,j.p_{ij}=p_U(u_i)p_V(v_j)\quad\text{for all }i,j.

For positive conditioning rows, that equality means the conditional distribution equals the unconditional VV marginal. The cellwise test also handles zero rows: every cell there is zero, so both sides of the factorization are zero without dividing by zero.

Worked examples

Both canonical marginals are [1/4,1/2,1/4][1/4,1/2,1/4]. The corner joint mass is 1/81/8, while the product of its marginals is (1/4)(1/4)=1/16(1/4)(1/4)=1/16. These variables are dependent.

Condition on U=−1U=-1. Retained row weights [1,1,0][1,1,0] have total 22, so

pV∣U(⋅∣−1)=[12,12,0].p_{V\mid U}(\cdot\mid-1)=\left[\frac12,\frac12,0\right].

Conditioning on the middle row instead gives [1/4,1/2,1/4][1/4,1/2,1/4], which happens to match the VV marginal. One matching row does not prove independence; the corner test already disproves it.

Worked example: One table, three distribution views

Exact U,V joint table and marginals · select a row, column or cell
U ↓ / V →Row mass
0.25
0.5
0.25
Column mass0.250.50.251
V = -1 given U = -1= 0.5
V = 0 given U = -1= 0.5
V = 1 given U = -1= 0

U=-1, V=-1: exact joint mass 0.125; U=-1, V=0: exact joint mass 0.125; U=-1, V=1: exact joint mass 0; U=0, V=-1: exact joint mass 0.125; U=0, V=0: exact joint mass 0.25; U=0, V=1: exact joint mass 0.125; U=1, V=-1: exact joint mass 0; U=1, V=0: exact joint mass 0.125; U=1, V=1: exact joint mass 0.125. Dependent U and V. Row and column marginals each sum to one. Conditioning on U = -1 divides the retained row by 0.25.

Selected joint cell
0.125
Selected row marginal
0.25
Selected column marginal
0.25
Column value given selected row
0.5
Row value given selected column
0.5

= exact model quantity · ≈ numerical companion or observed estimate

from 0 to 100, whole numbers only

Dependent U and V. Row and column marginals each sum to one. Conditioning on U = -1 divides the retained row by 0.25.
P(U=ui)=∑jpij,P(V=vj)=∑ipijP(U=u_i)=\sum_jp_{ij},\qquad P(V=v_j)=\sum_ip_{ij}
P(V=−1∣U=−1)=0.1250.25=0.5P(V=-1\mid U=-1)=\frac{0.125}{0.25}=0.5
U⊥V  ⟺  pij=P(U=ui)P(V=vj)for all i,jU\perp V\iff p_{ij}=P(U=u_i)P(V=v_j)\quad\text{for all }i,j

Normalize the nine joint weights

The table is an indexed U,V outcome model. Nonnegative raw weights divide by their positive total.

∑i,jpij=1\sum_{i,j}p_{ij}=1

Recover corner mass 1/8 and top-row conditional masses [1/2,1/2,0]. Compare the independent product table, whose marginals stay [1/4,1/2,1/4].

In the independent example the corner mass becomes 1/161/16 and the center mass remains 1/41/4. Every positive row now has conditional distribution [1/4,1/2,1/4][1/4,1/2,1/4]. Changing dependence need not change either marginal.

Executable reference code

The exact reference normalizes nine integer weights with Fraction, sums both marginals, builds conditional rows and columns, and tests every factorization exactly. Assertions cover canonical masses, the independent table, deterministic variables, proportional raw weights, and undefined conditioning.

The NumPy reference makes summation axes explicit: axis=1 removes columns and returns row marginals; axis=0 returns column marginals. It uses a documented floating tolerance for its independence cross-check, which is approximate evidence rather than an exact proof.

code/python/probability_joint.py
"""Exact joint, marginal, conditional masses from a 3x3 raw-weight table."""
from fractions import Fraction as F


def joint(weights):
    if len(weights) != 9 or any(type(w) is not int or not 0 <= w <= 1_000_000 for w in weights):
        raise ValueError("Require nine nonnegative integer weights, each at most 1000000")
    total = sum(weights)
    if total == 0:
        raise ValueError("The complete table needs positive weight")
    p = [[F(weights[3*i+j], total) for j in range(3)] for i in range(3)]
    rows = [sum(row, F(0)) for row in p]
    columns = [sum((p[i][j] for i in range(3)), F(0)) for j in range(3)]
    row_conditionals = [None if rows[i] == 0 else [v/rows[i] for v in p[i]] for i in range(3)]
    column_conditionals = [None if columns[j] == 0 else [p[i][j]/columns[j] for i in range(3)] for j in range(3)]
    independent = all(p[i][j] == rows[i]*columns[j] for i in range(3) for j in range(3))
    assert sum(rows) == sum(columns) == 1
    for conditional in (*row_conditionals, *column_conditionals):
        assert conditional is None or sum(conditional) == 1
    return p, rows, columns, row_conditionals, column_conditionals, independent


def main():
    p, rows, columns, row_given, col_given, independent = joint([1,1,0,1,2,1,0,1,1])
    assert p[0][0] == F(1,8) and p[1][1] == F(1,4)
    assert rows == columns == [F(1,4), F(1,2), F(1,4)]
    assert row_given[0] == [F(1,2), F(1,2), F(0)] and not independent
    assert col_given[1] == [F(1,4), F(1,2), F(1,4)]
    assert joint([1,2,1,2,4,2,1,2,1])[-1]
    empty_row = joint([0,0,0,1,0,0,0,0,0])
    assert empty_row[3][0] is None and empty_row[4][1] is None
    assert empty_row[-1]  # A deterministic pair factors, including its zero cells.
    for factor in (1, 2, 10):
        assert joint([factor*w for w in [1,1,0,1,2,1,0,1,1]]) == joint([1,1,0,1,2,1,0,1,1])
    for bad in ([0]*9, [-1]+[1]*8, [1]*8, [True]+[1]*8, [1.5]+[1]*8):
        try:
            joint(bad)
        except ValueError:
            pass
        else:
            raise AssertionError("Invalid table accepted")
    print("Joint mass:", p, "marginals:", rows, columns)
    print("V given U=-1:", row_given[0], "independent:", independent)
    print("Zero-mass conditioning is None, never an invented distribution.")


if __name__ == "__main__":
    main()
code/python/probability_joint_numpy.py
"""NumPy joint-table operations; float equality is an approximate cross-check."""
import numpy as np


def joint(weights):
    w = np.asarray(weights, dtype=float)
    if w.shape != (3,3) or not np.all(np.isfinite(w)) or np.any(w < 0) or not np.isfinite(w.sum()) or w.sum() <= 0:
        raise ValueError("Require a finite nonnegative 3x3 table of positive total")
    p = w/w.sum()
    rows, columns = p.sum(axis=1), p.sum(axis=0)
    row_given = [None if mass == 0 else p[i]/mass for i, mass in enumerate(rows)]
    col_given = [None if mass == 0 else p[:,j]/mass for j, mass in enumerate(columns)]
    factors = np.outer(rows, columns)
    independent = bool(np.allclose(p, factors, rtol=0, atol=1e-14))
    return p, rows, columns, row_given, col_given, independent


def main():
    w = np.array([[1,1,0],[1,2,1],[0,1,1]])
    p, rows, cols, rg, cg, independent = joint(w)
    np.testing.assert_allclose(rows, [.25,.5,.25], rtol=0, atol=1e-14)
    np.testing.assert_allclose(cols, [.25,.5,.25], rtol=0, atol=1e-14)
    np.testing.assert_allclose(rg[0], [.5,.5,0], rtol=0, atol=1e-14)
    np.testing.assert_allclose(cg[1], [.25,.5,.25], rtol=0, atol=1e-14)
    assert p[0,0] == .125 and not independent
    assert joint(np.outer([1,2,1],[1,2,1]))[-1]
    zero = joint([[0,0,0],[1,0,0],[0,0,0]])
    assert zero[3][0] is None and zero[4][1] is None and zero[-1]
    for bad in (np.zeros((3,3)), -w, [[1]], np.full((3,3), np.nan)):
        try:
            joint(bad)
        except ValueError:
            pass
        else:
            raise AssertionError("Invalid table accepted")
    print("Joint mass ≈", p, "row/column marginals ≈", rows, cols)
    print("Conditional row ≈", rg[0], "independent within atol=1e-14:", independent)
    print("Use exact fractions for a mathematical proof of factorization.")


if __name__ == "__main__":
    main()

Explore

Predict which marginal entries change when one corner weight increases. After normalization, even unchanged raw cells can receive different probabilities because the complete denominator changes. Verify the total mass and inspect both affected marginal families.

Use the empty-row or empty-column preset, leaving positive weight elsewhere. Explain why the overall distribution remains valid while that conditional distribution becomes undefined. Restore the row and compare its conditional probabilities with the unconditional column marginal. Multiply all weights by the same positive integer: which probabilities should remain exactly fixed?

Common mistakes and counterexamples

Summing and conditioning answer different questions. The canonical top-row marginal is 1/41/4; its conditional distribution has total 11. Keeping the global denominator in a conditional row would leave total 1/41/4 and fail normalization.

Marginals do not determine the joint table. The canonical and independent tables have identical marginals but different corner masses. Also, checking only one row, one covariance, or one cell cannot establish independence across all cells. A mismatch in any cell does suffice to disprove it.

Numerical considerations

In this bounded table, integer weights and normalized fractions support exact sums and comparisons. An all-zero total is rejected; individual zero rows and columns are preserved and reported explicitly. Display rounding never decides whether a conditional denominator is zero or whether the table factors.

With floating data, very small positive marginals can amplify relative errors during conditional division. Distinguish an exact zero from a small positive quantity, and document any numerical comparison tolerance. Do not round a valid row to zero before computing its conditional probabilities.

Engineering and ML connections

A classification confusion matrix records joint behavior between a label and a prediction. Row and column normalization answer different conditional questions, while global normalization answers joint frequency questions. Always state which coordinate is conditioned on and which denominator is used.

Feature marginals alone cannot reveal all dependence between features. A generative model that replaces a joint distribution by the product of marginals makes an independence assumption; it needs justification beyond matching each feature histogram separately.

Exercises

Use exact fractions and state which normalization each answer uses.

calculation

Normalize and sum a row

Rows U = −1, 0, 1 and columns V = −1, 0, 1 have raw weights [1,1,0; 1,2,1; 0,1,1]. Give the total weight, P(U = 0), and P(U = −1, V = −1).

calculation

Restrict to the selected row

For the same table, give P(V = −1 | U = −1), P(V = 0 | U = −1), P(V = 1 | U = −1).

construction

Construct a product table

Independent U and V both have marginals [1/4,1/2,1/4] at −1,0,1. Give P(U = −1,V = −1), P(U = 0,V = 0), and P(V = 0 | U = −1).

explanation

Condition on an empty row

All three weights in the selected row are zero; another row has positive total. What is the selected conditional distribution?

Choose one answer

explanation

Do marginals determine dependence?

The canonical table and the independent product table share marginals [1/4,1/2,1/4]. Are their joint distributions necessarily equal?

Choose one answer

Summary and checkpoints

A joint distribution preserves pairing. Marginalization adds away a coordinate; conditioning restricts and renormalizes positive retained mass. Check that you can recover both canonical marginals, normalize the top row, explain an empty condition, and test independence by every joint cell’s factorization.

The map of the book

97 of 97 chapters written · eight Parts

demo Foundation demo Try the live vector example Open as a page

Part I

Mathematical Language

The notation and mental objects everything else uses.

9 of 9 chapters written

  1. I.1 Scalars, quantities, units, powers and roots available
  2. I.2 Coordinates and points available
  3. I.3 Vectors: components, magnitude, and direction reference chapter available
  4. I.4 Algebraic expressions, equations and inequalities available
  5. I.5 Functions as input → transformation → output available
  6. I.6 Essential function families available
  7. I.7 Sets, intervals, and relations available
  8. I.8 Indexed quantities and summation available
  9. I.9 The notation map for ML available

Part II

Linear Algebra

Matrices as transformations: the strongest foundation in the book.

19 of 19 chapters written

  1. II.1 Vector addition and subtraction available
  2. II.2 Scalar multiplication and vector scaling available
  3. II.3 Norms, magnitude, and normalization available
  4. II.4 Dot product, angle, and orthogonality available
  5. II.5 Projection and distance to a direction available
  6. II.6 Linear combinations and span available
  7. II.7 Linear independence, basis, and coordinates available
  8. II.8 Matrices as linear transformations available
  9. II.9 Matrix × vector available
  10. II.10 Matrix × matrix as composition available
  11. II.11 Transpose and orthogonality available
  12. II.12 Determinant: orientation and area/volume scaling available
  13. II.13 Linear systems as intersecting constraints available
  14. II.14 Gaussian elimination and row operations available
  15. II.15 Rank and invertibility available
  16. II.16 Inverse matrices available
  17. II.17 Eigenvalues and eigenvectors available
  18. II.18 Orthogonal bases and least-squares geometry available
  19. II.19 Singular Value Decomposition available

Part III

Calculus

Change, local approximation, and sensitivity made visible.

15 of 15 chapters written

  1. III.1 Limits through approach available
  2. III.2 Continuity and local behavior available
  3. III.3 Derivative as secant → tangent available
  4. III.4 Derivative as rate of change and local linear model available
  5. III.5 Derivative rules available
  6. III.6 Chain rule available
  7. III.7 Multivariable functions and partial derivatives available
  8. III.8 Gradient and directional derivatives available
  9. III.9 Jacobian available
  10. III.10 Computational graphs and automatic differentiation available
  11. III.11 Hessian and curvature available
  12. III.12 Integrals as accumulation available
  13. III.13 Fundamental derivative/integral connection available
  14. III.14 Numerical differentiation available
  15. III.15 Numerical integration available

Part IV

Probability

Uncertainty through sample spaces, evidence, and repetition.

16 of 16 chapters written

  1. IV.1 Random experiments, outcomes, and sample spaces available
  2. IV.2 Events and probability mass available
  3. IV.3 Counting and finite probability where needed available
  4. IV.4 Conditional probability as restricted sample space available
  5. IV.5 Independence available
  6. IV.6 Bayes' theorem as probability-mass update available
  7. IV.7 Random variables available
  8. IV.8 PMF, PDF, and CDF available
  9. IV.9 Bernoulli and Binomial distributions available
  10. IV.10 Uniform and Gaussian distributions available
  11. IV.11 Expectation available
  12. IV.12 Variance and standard deviation available
  13. IV.13 Joint, marginal, and conditional distributions available
  14. IV.14 Covariance and correlation available
  15. IV.15 Law of Large Numbers available
  16. IV.16 Central Limit Theorem available

Part V

Statistics

From observed data to estimates, intervals, and likelihood.

10 of 10 chapters written

  1. V.1 Data summaries: mean, median, mode available
  2. V.2 Spread: variance, standard deviation, robust interpretation available
  3. V.3 Population, sample, and sampling variability available
  4. V.4 Estimators and estimation available
  5. V.5 Confidence intervals through repeated sampling available
  6. V.6 Covariance matrices and multivariate spread available
  7. V.7 Regression fundamentals available
  8. V.8 Likelihood available
  9. V.9 Maximum Likelihood Estimation available
  10. V.10 Maximum A Posteriori estimation available

Part VI

Optimization

Learning as repeated parameter updates governed by an objective.

10 of 10 chapters written

  1. VI.1 Objective functions and optimization landscapes available
  2. VI.2 Local vs global optima and stationary points available
  3. VI.3 Convexity available
  4. VI.4 Gradient descent flagship chapter available
  5. VI.5 Learning rate and convergence behavior available
  6. VI.6 Momentum available
  7. VI.7 Stochastic and mini-batch gradient descent available
  8. VI.8 Adam intuition available
  9. VI.9 Constraints and projected/penalized intuition available
  10. VI.10 Numerical stopping and optimization diagnostics available

Part VII

Information Theory

Logarithms, entropy, and the loss behind token prediction.

8 of 8 chapters written

  1. VII.1 Logarithms and log probabilities in computation available
  2. VII.2 Self-information available
  3. VII.3 Entropy available
  4. VII.4 Cross entropy and negative log-likelihood available
  5. VII.5 KL divergence available
  6. VII.6 Logits and softmax available
  7. VII.7 Numerical stability: log-sum-exp and stable softmax available
  8. VII.8 From token logits to language-model loss available

Part VIII

Numerical Computing

Why equivalent expressions behave differently on real machines.

10 of 10 chapters written

  1. VIII.1 Floating-point representation available
  2. VIII.2 Rounding and representation error available
  3. VIII.3 Error propagation and conditioning available
  4. VIII.4 Catastrophic cancellation available
  5. VIII.5 Overflow and underflow available
  6. VIII.6 Stable algorithms available
  7. VIII.7 Numerical linear algebra realities available
  8. VIII.8 Sparse matrices and sparse structure available
  9. VIII.9 Vectorized computation available
  10. VIII.10 Reproducibility, random seeds, and nondeterminism available