Overview
A joint distribution is a grid: one row per value of , one column per value of , and in each cell the probability of that pair. Everything about the two variables is in that grid. Summing a row gives the chance of that value of whatever does, and those totals, written in the margin of the table, are the marginal distribution. Dividing a row by its total gives the distribution of once is known. If every cell equals its row total times its column total, the variables are independent and the grid holds no more than its margins.
A short history
Tables that cross two categories were common in statistics by the late 1800s, and Karl Pearson named them contingency tables around 1900. The word marginal comes from the row and column totals written in the margins of such a table. Andrey Kolmogorov's 1933 axioms gave the general definition of a joint distribution, and the sum and product rules became the basic operations of probabilistic modelling.
How it works
- Write the joint table with on the rows and on the columns. Counts are fine: with normalize on, the template divides by the total.
- Sum across each row to get the marginal of , and down each column to get the marginal of .
- Divide each row by its row total to get the conditional distribution of given each value of .
- Compare the table with the outer product of the two marginals. If they match within the tolerance, the variables are independent.
- Attach numeric values to the rows and columns to compute expectations: weight a function of and by each cell and add.
- Compute the covariance as , and divide by both standard deviations for the correlation.
Watch out for
- The marginals do not determine the joint. Many different tables share the same row and column totals, so you cannot rebuild dependence from the margins.
- Zero covariance does not mean independence. Covariance only detects straight-line relationships, and a table can have zero covariance while its cells differ from the product of marginals.
- A row with total probability zero has no conditional distribution. The template returns NaN for that row.
- A table built from few samples almost never passes the independence test exactly, even when the variables are independent. That needs a statistical test, not a tolerance.
- Covariance and correlation use x_values and y_values. If the categories have no real numeric meaning, the default values 0, 1, 2 make these numbers arbitrary.
Use cases
When to use it
Studying how two categorical or discrete variables relate, for example in a contingency table, and as the concrete picture behind marginalization in larger probabilistic models.
In industry
- Epidemiology
- Researchers tabulate exposure against disease to compare the disease rate among exposed and unexposed people.
- Marketing analytics
- Analysts cross customer segment with purchase outcome to see which segments convert, and sum over segments to get the overall rate.
- Natural language processing
- Word co-occurrence counts form a joint table from which measures such as pointwise mutual information are computed.
Choosing it: what must hold
- Paired observations: both variables recorded for the same unit.
- Few enough distinct values per variable that every cell of the table has a reasonable count.
- Probabilities, or counts divided by the total, that sum to 1 over the whole table.
When to choose something else
| If | Use instead |
|---|---|
| Variables are continuous with many distinct values | Covariance and correlation, or bin the values first |
| There are more than two or three variables and the table grows too large | Multivariate analysis, or a model that assumes conditional independence such as Naive Bayes |
| You want to test whether the two variables are related at all | Association analysis, for example a chi-squared test |
Math foundations
The joint distribution
One probability for every pair of values. All the cells together cover every possibility, so they sum to 1.
Marginals
To ignore a variable, sum over all its values. This is called marginalizing it out, and the function marginalize does the same for tables with more than two axes.
Conditionals
One row of the table, rescaled to sum to 1. It answers what looks like among the cases where took the value .
Independence
The joint table is the outer product of its marginals. Equivalently every row, once rescaled, is the same distribution of .
Expectation over the joint
The average of any function of the two variables, weighted by how likely each pair is.
Covariance and correlation
Covariance is positive when large values of tend to come with large values of . Dividing by the standard deviations gives a number between and that does not depend on units.
Symbols
- the two discrete random variables: rows and columns of the table
- particular values of and
- the joint probability of the pair
- the marginal probabilities
- the conditional probability of given
- any function of the two variables
- expectation: the probability-weighted average
- the standard deviations of and
- the Pearson correlation
Worked by hand
Let and each take the values 0 and 1, with joint table rows for and for .
The two conditional rows differ, so the variables are dependent, and the covariance is slightly negative. An independent table with these margins would have 0.12 in the top-left cell, not 0.1.
Visual example
Loading the example.
Try this
- Set the first slider to 0, then click each given X button: the bottom row does not move, which is independence.
- Push the slider to 1 and condition on X = 2. All of the row's probability sits on Y = 2.
- Go negative and watch the covariance change sign.
Code sample
from impl import JointDistribution
# rows: X in {0, 1}, columns: Y in {0, 1, 2}
joint = JointDistribution([[0.10, 0.20, 0.10],
[0.30, 0.10, 0.20]])
joint.marginal_x() # [0.4, 0.6]
joint.marginal_y() # [0.4, 0.3, 0.3]
joint.conditional_y_given_x() # each row sums to 1
joint.covariance() # -0.04
joint.is_independent() # FalseRead the implementation (123 lines)
"""Joint and marginal probability for two discrete variables.
`JointDistribution` wraps a table P(X = x_i, Y = y_j) and derives the marginals, the conditionals, expectations,
covariance and correlation, and tests independence. `marginalize` sums any axes out of an N-dimensional table.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import JointMarginalConfig
except ImportError: # run from the template's own folder
from config import JointMarginalConfig
def marginalize(table, keep) -> np.ndarray:
"""Sum an N-dimensional joint table over every axis not listed in `keep`.
table: array of any shape holding joint probabilities.
keep: axis index or tuple of axis indices to keep.
Returns the marginal table over the kept axes, in their original order.
"""
table = np.asarray(table, dtype=float)
keep = (keep,) if isinstance(keep, int) else tuple(keep)
if any(not -table.ndim <= k < table.ndim for k in keep):
raise ValueError(f"keep holds an axis outside 0..{table.ndim - 1}")
kept = {k % table.ndim for k in keep}
drop = tuple(a for a in range(table.ndim) if a not in kept)
return table.sum(axis=drop)
class JointDistribution:
"""Joint distribution of two discrete variables X (rows) and Y (columns).
table: array (n_x, n_y) of probabilities, or of counts when config.normalize is True.
x_values: numeric values of X, array (n_x,); defaults to 0..n_x-1.
y_values: numeric values of Y, array (n_y,); defaults to 0..n_y-1.
"""
def __init__(self, table, x_values=None, y_values=None, config: JointMarginalConfig | None = None) -> None:
self.config = config or JointMarginalConfig()
table = np.asarray(table, dtype=float)
if table.ndim != 2 or np.any(table < 0):
raise ValueError("table must be 2-D and non-negative")
total = table.sum()
if self.config.normalize:
if total <= 0:
raise ValueError("table sums to zero")
table = table / total
elif abs(total - 1.0) > self.config.tolerance:
raise ValueError(f"table must sum to 1, got {total}")
self.table = table
self.x_values = np.arange(table.shape[0], dtype=float) if x_values is None else np.asarray(x_values, dtype=float)
self.y_values = np.arange(table.shape[1], dtype=float) if y_values is None else np.asarray(y_values, dtype=float)
if self.x_values.shape != (table.shape[0],) or self.y_values.shape != (table.shape[1],):
raise ValueError("x_values and y_values must match the table's shape")
@classmethod
def from_samples(cls, x, y, config: JointMarginalConfig | None = None) -> "JointDistribution":
"""Empirical joint distribution of paired numeric samples x and y, arrays (n,)."""
x, y = np.asarray(x, dtype=float), np.asarray(y, dtype=float)
if x.shape != y.shape or x.ndim != 1 or x.size == 0:
raise ValueError("x and y must be 1-D, non-empty and of equal length")
x_values, xi = np.unique(x, return_inverse=True)
y_values, yi = np.unique(y, return_inverse=True)
counts = np.zeros((x_values.size, y_values.size))
np.add.at(counts, (xi, yi), 1.0)
return cls(counts / counts.sum(), x_values, y_values, config)
@classmethod
def from_marginals(cls, p_x, p_y, config: JointMarginalConfig | None = None) -> "JointDistribution":
"""Joint distribution of two independent variables: the outer product of their marginals."""
return cls(np.outer(p_x, p_y), config=config)
def marginal_x(self) -> np.ndarray:
"""P(X = x) = sum over y of P(x, y), array (n_x,)."""
return self.table.sum(axis=1)
def marginal_y(self) -> np.ndarray:
"""P(Y = y) = sum over x of P(x, y), array (n_y,)."""
return self.table.sum(axis=0)
def conditional_y_given_x(self) -> np.ndarray:
"""P(Y = y | X = x), array (n_x, n_y). Rows sum to 1; rows with P(x) = 0 are NaN."""
with np.errstate(invalid="ignore", divide="ignore"):
return self.table / self.table.sum(axis=1, keepdims=True)
def conditional_x_given_y(self) -> np.ndarray:
"""P(X = x | Y = y), array (n_x, n_y). Columns sum to 1; columns with P(y) = 0 are NaN."""
with np.errstate(invalid="ignore", divide="ignore"):
return self.table / self.table.sum(axis=0, keepdims=True)
def is_independent(self) -> bool:
"""True when the table equals the outer product of its marginals, within the tolerance."""
return bool(np.abs(self.table - np.outer(self.marginal_x(), self.marginal_y())).max() <= self.config.tolerance)
def expectation(self, func) -> float:
"""E[f(X, Y)] for a vectorized function of two arrays that broadcasts over the (n_x, n_y) grid."""
values = func(self.x_values[:, None], self.y_values[None, :])
return float((self.table * values).sum())
def mean_x(self) -> float:
return float(np.dot(self.marginal_x(), self.x_values))
def mean_y(self) -> float:
return float(np.dot(self.marginal_y(), self.y_values))
def covariance(self) -> float:
"""Cov(X, Y) = E[XY] - E[X] E[Y]."""
return self.expectation(lambda x, y: x * y) - self.mean_x() * self.mean_y()
def correlation(self) -> float:
"""Pearson correlation Cov(X, Y) / (sd(X) sd(Y))."""
var_x = float(np.dot(self.marginal_x(), self.x_values**2)) - self.mean_x() ** 2
var_y = float(np.dot(self.marginal_y(), self.y_values**2)) - self.mean_y() ** 2
if var_x <= 0 or var_y <= 0:
raise ValueError("correlation is undefined when a variable is constant")
return self.covariance() / math.sqrt(var_x * var_y)
def conditional_mean_y(self) -> np.ndarray:
"""E[Y | X = x] for every x, array (n_x,)."""
return self.conditional_y_given_x() @ self.y_values- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Build JointDistribution([[10, 20], [30, 40]]) and print marginal_x, marginal_y, conditional_y_given_x, covariance and is_independent to confirm the worked example. Then build JointDistribution.from_marginals with the same two marginals and compare the tables cell by cell. Use marginalize on a 2 by 2 by 2 table of your own to sum out the last axis.
Check on learning
- Two different joint tables have exactly the same marginals. What information does the joint carry that the marginals lose?
A way to think about it
Build the independent table from the margins and compare it with the worked one. The difference between them is the dependence.
- Let take the values with equal probability and let . What is the covariance, and are the variables independent?
A way to think about it
Compute and . Then ask whether knowing tells you .
- Why does the correlation fail to exist when one variable is constant, and what does the template do then?
A way to think about it
Look at the denominator. A constant has zero spread, so there is nothing to compare its movement against.
- You have a three-way table over , and and want . Which sums and which division do you need?
A way to think about it
Marginalize out the variable you do not care about first, then condition exactly as in the two-variable case.
- A table built with from_samples from 30 independent pairs fails is_independent. Does that show dependence?
A way to think about it
Sample frequencies wobble around the true probabilities. Think about how large that wobble is compared with a tolerance of .