Sign in

Joint marginal

Joint and marginal probability

A table of probabilities for two variables at once, and how to recover from it each variable alone, each given the other, and their covariance.

Overview

A joint distribution is a grid: one row per value of XX, one column per value of YY, 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 XX whatever YY 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 YY once XX 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

  1. Write the joint table with XX on the rows and YY on the columns. Counts are fine: with normalize on, the template divides by the total.
  2. Sum across each row to get the marginal of XX, and down each column to get the marginal of YY.
  3. Divide each row by its row total to get the conditional distribution of YY given each value of XX.
  4. Compare the table with the outer product of the two marginals. If they match within the tolerance, the variables are independent.
  5. Attach numeric values to the rows and columns to compute expectations: weight a function of xx and yy by each cell and add.
  6. Compute the covariance as E[XY]−E[X] E[Y]\mathbb{E}[XY] - \mathbb{E}[X]\,\mathbb{E}[Y], 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

IfUse instead
Variables are continuous with many distinct valuesCovariance and correlation, or bin the values first
There are more than two or three variables and the table grows too largeMultivariate analysis, or a model that assumes conditional independence such as Naive Bayes
You want to test whether the two variables are related at allAssociation analysis, for example a chi-squared test

Math foundations

  1. The joint distribution

    p(x,y)=P(X=x, Y=y),∑x∑yp(x,y)=1p(x, y) = P(X = x,\ Y = y), \qquad \sum_{x}\sum_{y} p(x, y) = 1

    One probability for every pair of values. All the cells together cover every possibility, so they sum to 1.

  2. Marginals

    p(x)=∑yp(x,y),p(y)=∑xp(x,y)p(x) = \sum_{y} p(x, y), \qquad p(y) = \sum_{x} p(x, y)

    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.

  3. Conditionals

    p(y∣x)=p(x,y)p(x)p(y \mid x) = \frac{p(x, y)}{p(x)}

    One row of the table, rescaled to sum to 1. It answers what YY looks like among the cases where XX took the value xx.

  4. Independence

    p(x,y)=p(x) p(y)for all x,yp(x, y) = p(x)\,p(y) \quad \text{for all } x, y

    The joint table is the outer product of its marginals. Equivalently every row, once rescaled, is the same distribution of YY.

  5. Expectation over the joint

    E[f(X,Y)]=∑x∑yf(x,y) p(x,y)\mathbb{E}[f(X, Y)] = \sum_{x}\sum_{y} f(x, y)\,p(x, y)

    The average of any function of the two variables, weighted by how likely each pair is.

  6. Covariance and correlation

    Cov⁡(X,Y)=E[XY]−E[X] E[Y],ρ=Cov⁡(X,Y)σX σY\operatorname{Cov}(X, Y) = \mathbb{E}[XY] - \mathbb{E}[X]\,\mathbb{E}[Y], \qquad \rho = \frac{\operatorname{Cov}(X, Y)}{\sigma_X\,\sigma_Y}

    Covariance is positive when large values of XX tend to come with large values of YY. Dividing by the standard deviations gives a number between −1-1 and 11 that does not depend on units.

Symbols

X, YX,\ Y
the two discrete random variables: rows and columns of the table
x, yx,\ y
particular values of XX and YY
p(x,y)p(x, y)
the joint probability of the pair
p(x), p(y)p(x),\ p(y)
the marginal probabilities
p(y∣x)p(y \mid x)
the conditional probability of yy given xx
ff
any function of the two variables
E\mathbb{E}
expectation: the probability-weighted average
σX, σY\sigma_X,\ \sigma_Y
the standard deviations of XX and YY
ρ\rho
the Pearson correlation

Worked by hand

Let XX and YY each take the values 0 and 1, with joint table rows (0.1,0.2)(0.1, 0.2) for X=0X = 0 and (0.3,0.4)(0.3, 0.4) for X=1X = 1.

p(X=0)=0.1+0.2=0.3,p(X=1)=0.3+0.4=0.7p(X{=}0) = 0.1 + 0.2 = 0.3, \qquad p(X{=}1) = 0.3 + 0.4 = 0.7
p(Y=0)=0.1+0.3=0.4,p(Y=1)=0.2+0.4=0.6p(Y{=}0) = 0.1 + 0.3 = 0.4, \qquad p(Y{=}1) = 0.2 + 0.4 = 0.6
p(Y=1∣X=0)=0.20.3≈0.667,p(Y=1∣X=1)=0.40.7≈0.571p(Y{=}1 \mid X{=}0) = \frac{0.2}{0.3} \approx 0.667, \qquad p(Y{=}1 \mid X{=}1) = \frac{0.4}{0.7} \approx 0.571
E[XY]=1×1×0.4=0.4,E[X]=0.7,E[Y]=0.6\mathbb{E}[XY] = 1 \times 1 \times 0.4 = 0.4, \qquad \mathbb{E}[X] = 0.7, \qquad \mathbb{E}[Y] = 0.6
Cov⁡(X,Y)=0.4−0.7×0.6=−0.02\operatorname{Cov}(X, Y) = 0.4 - 0.7 \times 0.6 = -0.02

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()           # False
Read 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

  1. 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.

  2. Let XX take the values −1,0,1-1, 0, 1 with equal probability and let Y=X2Y = X^{2}. What is the covariance, and are the variables independent?
    A way to think about it

    Compute E[XY]=E[X3]\mathbb{E}[XY] = \mathbb{E}[X^{3}] and E[X]\mathbb{E}[X]. Then ask whether knowing XX tells you YY.

  3. 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.

  4. You have a three-way table over XX, YY and ZZ and want p(x∣z)p(x \mid z). 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.

  5. 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 10−910^{-9}.