Sign in

Association analysis

Association analysis between two variables

Four ways to ask whether two columns are related: the chi-square test, Cramer's V, mutual information and one-way ANOVA.

Overview

Two columns are independent when knowing one tells you nothing about the other. Each tool here measures how far the data are from that state. For two categorical columns, you count how often each pair of labels occurs and compare those counts with the counts independence would produce. For a numeric column against a categorical one, you compare how far the group means sit from each other with how much the values scatter inside each group. A test gives a p-value, the chance of seeing a gap this large if the columns were truly unrelated. An effect size says how strong the relation is, which a p-value does not.

A short history

Karl Pearson published the chi-square test in 1900 to check whether counts in a table depart from what independence predicts. Ronald Fisher developed the analysis of variance at Rothamsted in the 1920s for a numeric outcome across groups. Harald Cramér described the V coefficient in 1946 as a 0 to 1 strength measure built on chi-square, and Claude Shannon's 1948 information theory supplied mutual information, which also detects relationships that are not linear.

How it works

  1. Cross-tabulate the two label columns into a contingency table: a grid of counts with one row per label of the first column and one column per label of the second.
  2. Compute the expected count of each cell under independence: row total times column total, divided by the number of rows of data.
  3. Sum the squared gaps between observed and expected counts, each divided by its expected count. This is the chi-square statistic, and its tail probability is the p-value.
  4. Rescale the statistic to Cramer's V, which runs from 0 (no association) to 1 (one column determines the other) and does not grow with sample size.
  5. For mutual information, turn the table into probabilities and add up how much each cell's probability differs from the product of its row and column probabilities, on a log scale.
  6. For a numeric column and a grouping column, run one-way ANOVA: divide the variation between group means by the variation inside groups to get the F statistic, and report eta squared.

Watch out for

  • With thousands of rows almost any tiny association gives a small p-value, because the chi-square statistic grows with nn. Read Cramer's V or eta squared next to it.
  • The chi-square p-value is an approximation that needs expected counts of about 5 or more in most cells. Sparse tables give p-values that are too small.
  • Mutual information estimated from a table is biased upward on small samples, because random noise in the counts always looks like a little dependence.
  • ANOVA only says that at least one group mean differs. It does not say which one, and it assumes similar spread inside every group.
  • None of these measures gives a direction or a cause. They are symmetric summaries of a table.

Use cases

When to use it

Screening pairs of features, or features against a target, before modelling: chi-square and Cramer's V for two categorical columns, mutual information to rank features against a categorical target, ANOVA for a numeric column against groups.

In industry

Market research
Survey analysts run chi-square tests on cross tabulations to see whether an answer depends on age band or region, and report Cramer's V to say how strong the link is.
Feature screening in ML
Before training a classifier, teams rank columns by mutual information with the label to drop features that carry no signal.
Public health
Epidemiologists test whether a disease outcome is associated with an exposure category using a contingency table of counts.

Choosing it: what must hold

  • Rows that are independent observations: one row per subject, not repeated measurements of the same subject.
  • For chi-square and Cramer's V, two categorical columns with expected counts of about five or more in most cells.
  • For one-way ANOVA, a numeric outcome with roughly normal residuals and similar variance in each group.
  • Enough rows per category for mutual information estimates to be stable.

When to choose something else

IfUse instead
Both columns are numericCorrelation (Pearson, Spearman or Kendall)
The table is 2 by 2 with very small countsFisher's exact test
Groups have very different variances or clear outliersA rank based test such as Kruskal-Wallis, or Welch's ANOVA
You need to know which groups differ, not only that some doPost-hoc comparisons such as Tukey HSD

Math foundations

  1. Expected counts under independence

    Eij=Ri CjnE_{ij} = \frac{R_i \, C_j}{n}

    If the two columns were unrelated, the share of row ii that falls in column jj would be the same as the overall share of column jj. This is the table to compare against.

  2. The chi-square statistic

    χ2=∑i=1r∑j=1c(Oij−Eij)2Eij,dof=(r−1)(c−1)\chi^{2} = \sum_{i=1}^{r} \sum_{j=1}^{c} \frac{(O_{ij} - E_{ij})^{2}}{E_{ij}}, \qquad \text{dof} = (r-1)(c-1)

    Each cell contributes its squared gap, scaled by what was expected. Under independence the sum follows a chi-square distribution with the stated degrees of freedom, which gives the p-value.

  3. Cramer's V

    V=χ2n min⁡(r−1,  c−1)V = \sqrt{\frac{\chi^{2}}{n \, \min(r-1,\; c-1)}}

    Dividing by nn removes the growth with sample size, and dividing by the smaller table dimension minus one caps the result at 1. It is the effect size of the chi-square test.

  4. Mutual information

    I(X;Y)=∑x∑yp(x,y) ln⁡p(x,y)p(x) p(y)I(X;Y) = \sum_{x} \sum_{y} p(x,y) \, \ln \frac{p(x,y)}{p(x)\,p(y)}

    Zero exactly when the joint probabilities equal the product of the marginals. With the natural log the unit is nats. Divide by ln⁡2\ln 2 for bits.

  5. The ANOVA F statistic

    F=SSB/(k−1)SSW/(n−k)F = \frac{SS_{B} / (k-1)}{SS_{W} / (n-k)}

    The numerator is the variation of the group means around the grand mean, per degree of freedom. The denominator is the variation inside groups. A large ratio means the groups differ by more than their internal noise explains.

  6. Eta squared

    η2=SSBSSB+SSW\eta^{2} = \frac{SS_{B}}{SS_{B} + SS_{W}}

    The share of the total variation that the grouping accounts for. It is the effect size to read next to the F test's p-value.

Symbols

OijO_{ij}
observed count in row i, column j of the contingency table
EijE_{ij}
count expected in that cell if the columns were independent
Ri,CjR_i, C_j
total of row i and total of column j
nn
number of observations
r,cr, c
number of rows and columns of the table
p(x,y)p(x,y)
share of observations with labels x and y together
p(x),p(y)p(x), p(y)
share of observations with label x, and with label y
kk
number of groups in the ANOVA
SSBSS_{B}
between-group sum of squares: group size times squared distance of each group mean from the grand mean
SSWSS_{W}
within-group sum of squares: squared distances of values from their own group mean

Worked by hand

Sixty people: 30 smokers of whom 20 are ill and 10 well, and 30 non-smokers of whom 10 are ill and 20 well. Every row total and column total is 30.

Eij=30×3060=15for every cellE_{ij} = \frac{30 \times 30}{60} = 15 \quad \text{for every cell}
χ2=4×(20−15)215=4×2515=6.667\chi^{2} = 4 \times \frac{(20 - 15)^{2}}{15} = 4 \times \frac{25}{15} = 6.667
V=6.66760×1=0.1111=0.333V = \sqrt{\frac{6.667}{60 \times 1}} = \sqrt{0.1111} = 0.333
I=2×13ln⁡1/31/4+2×16ln⁡1/61/4=0.1918−0.1352=0.0566 natsI = 2 \times \tfrac{1}{3} \ln\frac{1/3}{1/4} + 2 \times \tfrac{1}{6} \ln\frac{1/6}{1/4} = 0.1918 - 0.1352 = 0.0566 \text{ nats}

With 1 degree of freedom the statistic 6.667 gives a p-value near 0.0098, so independence is rejected. V of 0.333 says the association is moderate, not strong.

Visual example

Loading the example.

Try this

  • Set all four counts to 15: observed equals expected everywhere and every measure is zero.
  • Double each starting count to 40, 20, 20, 40: chi-square doubles and the p-value shrinks, yet Cramer's V stays at 0.333.
  • Choose a cell to read how its expected count comes from its row total and column total.

Code sample

from impl import AssociationAnalysis
from config import AssociationAnalysisConfig

a = AssociationAnalysis(AssociationAnalysisConfig())
smoker = ["yes"] * 30 + ["no"] * 30
ill = ["ill"] * 20 + ["well"] * 10 + ["ill"] * 10 + ["well"] * 20
test = a.chi_square(smoker, ill)
print(test["statistic"], test["p_value"])       # 6.667 0.0098
print(a.cramers_v(smoker, ill))                 # 0.333
print(a.mutual_information(smoker, ill))        # 0.0566 nats
print(AssociationAnalysis.anova([1, 2, 3, 2, 3, 4, 3, 4, 5], list("aaabbbccc")))   # f = 3.0, p = 0.125
Read the implementation (217 lines)
"""Association analysis: is one variable related to another, and how strongly?

NumPy and the standard library only. Two categorical variables: chi-square test of independence, Cramer's V
(strength, 0 to 1) and mutual information. One numeric variable against a categorical one: one-way ANOVA.
The chi-square and F tail probabilities are computed here from the incomplete gamma and beta functions.
"""
from __future__ import annotations

import math

import numpy as np

try:
    from .config import AssociationAnalysisConfig
except ImportError:  # run from the template's own folder
    from config import AssociationAnalysisConfig

_TINY = 1e-300


def _gammaincc(a: float, x: float) -> float:
    """Regularised upper incomplete gamma function Q(a, x), for a > 0 and x >= 0."""
    if x <= 0.0:
        return 1.0
    log_front = -x + a * math.log(x) - math.lgamma(a)
    if x < a + 1.0:  # series for P(a, x)
        term = total = 1.0 / a
        n = a
        for _ in range(2000):
            n += 1.0
            term *= x / n
            total += term
            if abs(term) < abs(total) * 1e-16:
                break
        return 1.0 - total * math.exp(log_front)
    b = x + 1.0 - a  # continued fraction for Q(a, x), modified Lentz method
    c, d = 1.0 / _TINY, 1.0 / b
    h = d
    for i in range(1, 2000):
        an = -i * (i - a)
        b += 2.0
        d = an * d + b
        d = 1.0 / (d if abs(d) > _TINY else _TINY)
        c = b + an / c
        c = c if abs(c) > _TINY else _TINY
        delta = d * c
        h *= delta
        if abs(delta - 1.0) < 1e-16:
            break
    return math.exp(log_front) * h


def _beta_cf(a: float, b: float, x: float) -> float:
    """Continued fraction of the incomplete beta function (modified Lentz method)."""
    c, d = 1.0, 1.0 - (a + b) * x / (a + 1.0)
    d = 1.0 / (d if abs(d) > _TINY else _TINY)
    h = d
    for m in range(1, 1000):
        for numerator in (
            m * (b - m) * x / ((a + 2 * m - 1.0) * (a + 2 * m)),
            -(a + m) * (a + b + m) * x / ((a + 2 * m) * (a + 2 * m + 1.0)),
        ):
            d = 1.0 + numerator * d
            d = 1.0 / (d if abs(d) > _TINY else _TINY)
            c = 1.0 + numerator / c
            c = c if abs(c) > _TINY else _TINY
            delta = d * c
            h *= delta
        if abs(delta - 1.0) < 1e-15:
            break
    return h


def _betainc(a: float, b: float, x: float) -> float:
    """Regularised incomplete beta function I_x(a, b)."""
    if x <= 0.0:
        return 0.0
    if x >= 1.0:
        return 1.0
    log_front = math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log1p(-x)
    if x < (a + 1.0) / (a + b + 2.0):
        return math.exp(log_front) * _beta_cf(a, b, x) / a
    return 1.0 - math.exp(log_front) * _beta_cf(b, a, 1.0 - x) / b


def chi2_sf(statistic: float, dof: float) -> float:
    """P(X > statistic) for a chi-square variable with `dof` degrees of freedom (the test's p-value)."""
    return _gammaincc(dof / 2.0, statistic / 2.0)


def f_sf(statistic: float, dof1: float, dof2: float) -> float:
    """P(X > statistic) for an F variable with (dof1, dof2) degrees of freedom."""
    if statistic <= 0.0:
        return 1.0
    return _betainc(dof2 / 2.0, dof1 / 2.0, dof2 / (dof2 + dof1 * statistic))


class AssociationAnalysis:
    """Association between two categorical variables, or between a numeric and a categorical one."""

    def __init__(self, config: AssociationAnalysisConfig | None = None) -> None:
        self.config = config or AssociationAnalysisConfig()

    @staticmethod
    def contingency_table(x, y) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
        """Cross-tabulate two label sequences of length n.

        Returns (table, row_labels, column_labels); table has shape (r, c) and table[i, j] counts the
        observations with x == row_labels[i] and y == column_labels[j].
        """
        x = np.asarray(x).ravel()
        y = np.asarray(y).ravel()
        if x.size != y.size or x.size == 0:
            raise ValueError("x and y must have the same non-zero length")
        rows, row_index = np.unique(x, return_inverse=True)
        columns, column_index = np.unique(y, return_inverse=True)
        table = np.zeros((rows.size, columns.size), dtype=float)
        np.add.at(table, (row_index, column_index), 1.0)
        return table, rows, columns

    def _table(self, x, y=None) -> np.ndarray:
        """Accept either two label sequences or one ready-made table of counts, shape (r, c)."""
        if y is not None:
            return self.contingency_table(x, y)[0]
        table = np.asarray(x, dtype=float)
        if table.ndim != 2 or (table < 0).any():
            raise ValueError("a contingency table must be 2-D with non-negative counts")
        table = table[table.sum(axis=1) > 0][:, table.sum(axis=0) > 0]  # empty rows and columns carry nothing
        if table.size == 0:
            raise ValueError("the contingency table is empty")
        return table

    def chi_square(self, x, y=None) -> dict:
        """Pearson's chi-square test of independence.

        x, y: two label sequences of length n, or x alone as a table of counts of shape (r, c).
        Returns {"statistic", "dof", "p_value", "expected"}; expected has the table's shape and holds the counts
        independence would give (row total * column total / n). A small p-value means the variables are related.
        """
        table = self._table(x, y)
        n = table.sum()
        expected = np.outer(table.sum(axis=1), table.sum(axis=0)) / n
        difference = np.abs(table - expected)
        if self.config.yates and table.shape == (2, 2):
            difference = np.maximum(difference - 0.5, 0.0)
        statistic = float((difference**2 / expected).sum())
        dof = (table.shape[0] - 1) * (table.shape[1] - 1)
        p_value = chi2_sf(statistic, dof) if dof > 0 else 1.0
        return {"statistic": statistic, "dof": dof, "p_value": p_value, "expected": expected}

    def cramers_v(self, x, y=None) -> float:
        """Cramer's V = sqrt(chi2 / (n * min(r - 1, c - 1))): strength of association, 0 (none) to 1 (perfect)."""
        table = self._table(x, y)
        n = table.sum()
        r, c = table.shape
        if min(r, c) < 2:
            return 0.0
        expected = np.outer(table.sum(axis=1), table.sum(axis=0)) / n
        phi2 = float(((table - expected) ** 2 / expected).sum()) / n
        if not self.config.bias_corrected:
            return math.sqrt(phi2 / min(r - 1, c - 1))
        phi2 = max(0.0, phi2 - (r - 1) * (c - 1) / (n - 1))
        r_adj = r - (r - 1) ** 2 / (n - 1)
        c_adj = c - (c - 1) ** 2 / (n - 1)
        return math.sqrt(phi2 / min(r_adj - 1, c_adj - 1))

    def mutual_information(self, x, y=None, normalized: bool = False) -> float:
        """Mutual information I(X; Y) = sum p(x, y) * log(p(x, y) / (p(x) p(y))), in nats or bits (config.log_base).

        Zero when the variables are independent; equal to the entropy of X when Y determines X. With
        normalized=True the result is divided by sqrt(H(X) * H(Y)) and lies in [0, 1].
        """
        table = self._table(x, y)
        joint = table / table.sum()
        px, py = joint.sum(axis=1), joint.sum(axis=0)
        positive = joint > 0
        mi = float((joint[positive] * np.log(joint[positive] / np.outer(px, py)[positive])).sum())
        hx = float(-(px * np.log(px)).sum())
        hy = float(-(py * np.log(py)).sum())
        mi = max(mi, 0.0)
        if normalized:
            return mi / math.sqrt(hx * hy) if hx > 0 and hy > 0 else 0.0
        return mi / math.log(2.0) if self.config.log_base == "2" else mi

    @staticmethod
    def anova(values, groups) -> dict:
        """One-way ANOVA: do the group means of a numeric variable differ?

        values: shape (n,) numbers. groups: shape (n,) group label of each value.
        Returns {"f", "df_between", "df_within", "p_value", "eta_squared"}; eta_squared is the share of the
        variance explained by the grouping.
        """
        v = np.asarray(values, dtype=float).ravel()
        g = np.asarray(groups).ravel()
        if v.size != g.size:
            raise ValueError("values and groups must have the same length")
        labels = np.unique(g)
        df_between, df_within = labels.size - 1, v.size - labels.size
        if df_between < 1 or df_within < 1:
            raise ValueError("ANOVA needs at least two groups and more observations than groups")
        grand_mean = v.mean()
        ss_between = sum(v[g == k].size * (v[g == k].mean() - grand_mean) ** 2 for k in labels)
        ss_within = sum(((v[g == k] - v[g == k].mean()) ** 2).sum() for k in labels)
        if ss_within == 0:
            f = math.inf if ss_between > 0 else float("nan")
            p_value = 0.0 if ss_between > 0 else float("nan")
        else:
            f = float((ss_between / df_between) / (ss_within / df_within))
            p_value = f_sf(f, df_between, df_within)
        total = ss_between + ss_within
        return {
            "f": f,
            "df_between": int(df_between),
            "df_within": int(df_within),
            "p_value": p_value,
            "eta_squared": float(ss_between / total) if total > 0 else 0.0,
        }
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
9, run with python3 -m unittest -v

Practice

Create an AssociationAnalysis and call chi_square, cramers_v and mutual_information on the smoker and ill lists from the worked example. Then repeat every label ten times so the table is ten times larger. Record which of the three numbers change and which stay the same, and explain why.

Check on learning

  1. You multiply every count in a table by 10. What happens to the chi-square statistic, the p-value and Cramer's V, and what does that tell you about which one measures strength?
    A way to think about it

    Look at how OO and EE scale in the chi-square formula, then at what dividing by nn does in V.

  2. Two columns have a Pearson correlation of zero but a mutual information well above zero. How can both be true?
    A way to think about it

    Correlation only sees straight-line relations. Think of a relation where one variable depends on the other in a curved or symmetric way.

  3. A table has a cell with an expected count of 0.8. Why does that one cell make the chi-square p-value unreliable?
    A way to think about it

    The cell's term divides by EijE_{ij}. Consider how much one extra observation in that cell moves the statistic, and what the chi-square approximation assumes about counts.

  4. ANOVA on three groups gives F=3.0F = 3.0 with a p-value of 0.125 and eta squared of 0.5. How can half the variance be explained and the test still not reject?
    A way to think about it

    Count the observations. With 9 values the within-group estimate has only 6 degrees of freedom, so a large effect is still compatible with chance.

  5. When would you turn on bias_corrected for Cramer's V, and what would you expect the plain V to do on two unrelated columns with few rows?
    A way to think about it

    Random counts never match the expected table exactly, so the chi-square statistic is positive even under independence. Think about what its square root does for small nn.