Overview
ANOVA compares groups on one outcome. With several outcomes you could run one ANOVA per outcome, but that multiplies the chance of a false alarm and ignores how the outcomes move together. MANOVA (multivariate analysis of variance) treats each observation as a vector. The sums of squares become matrices: holds the scatter of the group mean vectors around the grand mean, and holds the scatter of observations around their own group mean. The test asks whether is large relative to in any direction. Groups that overlap on every single outcome can still separate clearly along a combination of them, and MANOVA can see that.
A short history
MANOVA extends Fisher's analysis of variance to several outcomes at once. Harold Hotelling published the two group case, the T squared statistic, in 1931, and Samuel Wilks introduced the lambda criterion for several groups in 1932. Later statistics by Lawley, Hotelling, Roy and K. C. S. Pillai offer different trade offs, and Pillai's trace from 1955 is valued for its robustness. Testing the outcomes jointly controls the false alarm rate and uses their correlations.
How it works
- Stack each group as an array of shape and compute its mean vector and the grand mean vector.
- Build by adding, for each group, times the outer product of its mean's offset from the grand mean.
- Build by adding the outer products of every observation's offset from its own group mean.
- Compute the eigenvalues of . Each one is a between-to-within ratio along one direction.
- Combine the eigenvalues into the four classic statistics: Wilks, Pillai, Hotelling-Lawley and Roy.
- Convert each statistic to an value and a p-value. The configured
statisticdecidesreject.
Watch out for
- A significant result says that the mean vectors differ, not on which outcome, so follow up with single-outcome tests or by inspecting the leading direction.
- The test assumes every group has the same covariance matrix. Unequal covariances with unequal group sizes distort the p-values, and Pillai's trace is the most robust of the four.
- must be invertible, which needs more error degrees of freedom than outcomes. With many outcomes and few observations the test has little power or cannot run.
- The values are approximations outside a few exact cases, and Roy's is an upper bound, so its p-value is a lower bound and too optimistic.
Use cases
When to use it
Comparing groups on several related numeric outcomes measured on the same subjects, when you want one overall test that respects the correlation between the outcomes.
In industry
- Psychology
- Researchers compare therapy groups on several related scores, such as anxiety, mood and sleep, in one test before looking at each score.
- Agriculture and biology
- Field trials compare plant varieties on yield, height and protein content together, since these traits are correlated.
- Product testing
- Sensory panels rate products on several attributes, and a single multivariate test checks whether the products differ at all.
Choosing it: what must hold
- Two or more numeric outcomes that are moderately correlated and measured on every subject.
- Independent observations with more subjects in each group than there are outcomes.
- Outcomes that are roughly multivariate normal within groups, with similar covariance matrices.
- No outcome that is nearly a linear combination of the others.
When to choose something else
| If | Use instead |
|---|---|
| There is only one outcome | One-way ANOVA or two-way ANOVA |
| Outcomes are uncorrelated or you care about each one separately | Separate ANOVAs with a Bonferroni correction |
| Normality or equal covariance clearly fails | A permutation based test such as PERMANOVA |
Math foundations
The hypotheses
Each is a vector of population means, one per outcome. The null hypothesis says the groups agree on all of them at once.
Between-group scatter
The matrix version of the between-group sum of squares. Its diagonal holds the ordinary of each outcome and its off-diagonal entries record how the group means move together.
Within-group scatter
The matrix version of the within-group sum of squares. It measures noise, including the correlation between outcomes inside a group.
Eigenvalues
Each is the between-to-within ratio along the direction . They play the role of , one per independent direction in which groups can differ.
Wilks' lambda
The share of the generalised variance that is not explained by the groups. It lies between 0 and 1, and small values are evidence against the null hypothesis.
The other three statistics
Pillai's trace , the Hotelling-Lawley trace and Roy's largest root as the template reports it. They weight the eigenvalues differently, so they agree when one direction dominates and can disagree when the difference is spread over several.
Symbols
- number of groups
- number of outcome variables
- number of observations in group i
- outcome vector of observation j in group i
- mean vector of group i and grand mean vector
- population mean vector of group i
- between-group and within-group scatter matrices, both p by p
- eigenvalue m of the matrix product and its direction
- Wilks' lambda, Pillai's trace, Hotelling-Lawley trace, Roy's largest root
Worked by hand
Take two outcomes with and . Both are diagonal, so the eigenvalues of are the ratios of the diagonal entries.
Both routes give : 60% of the generalised variance is tied to the groups. The first outcome carries most of the separation, which is why Roy's root is 1 while the second eigenvalue adds little.
Visual example
Loading the example.
Try this
- Turn the direction to 45 degrees: the shift now runs along the clouds and the multivariate test loses its advantage.
- Set the correlation to 0 and compare the three p-values again.
- Raise the size of the shift until both single outcomes become significant too.
Code sample
import numpy as np
from impl import Manova
from config import ManovaConfig
rng = np.random.default_rng(0)
groups = [rng.normal(size=(15, 3)) + 0.6 * i for i in range(3)] # 3 groups, 3 outcomes
result = Manova(ManovaConfig(statistic="wilks")).fit(groups)
print(result["wilks"]["value"], result["wilks"]["f"], result["p_value"], result["reject"])Read the implementation (145 lines)
"""MANOVA: one-way multivariate analysis of variance with the four classic test statistics.
NumPy and the standard library only. The F tail probability comes from the regularized incomplete beta
function defined in this file.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import ManovaConfig
except ImportError: # run from the template's own folder
from config import ManovaConfig
def _betacf(a: float, b: float, x: float) -> float:
"""Continued fraction of the incomplete beta function (modified Lentz method)."""
tiny = 1e-300
qab, qap, qam = a + b, a + 1.0, a - 1.0
c = 1.0
d = 1.0 - qab * x / qap
d = 1.0 / (d if abs(d) > tiny else tiny)
h = d
for m in range(1, 2000):
m2 = 2 * m
for aa in (
m * (b - m) * x / ((qam + m2) * (a + m2)),
-(a + m) * (qab + m) * x / ((a + m2) * (qap + m2)),
):
d = 1.0 + aa * d
d = 1.0 / (d if abs(d) > tiny else tiny)
c = 1.0 + aa / 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:
"""Regularized incomplete beta function I_x(a, b), for a, b > 0 and 0 <= x <= 1."""
if x <= 0.0:
return 0.0
if x >= 1.0:
return 1.0
front = math.exp(
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 front * _betacf(a, b, x) / a
return 1.0 - front * _betacf(b, a, 1.0 - x) / b
def f_sf(f: float, df1: float, df2: float) -> float:
"""P(F > f) for an F variable with (`df1`, `df2`) degrees of freedom."""
if f <= 0.0:
return 1.0
return betainc(0.5 * df2, 0.5 * df1, df2 / (df2 + df1 * f))
def f_cdf(f: float, df1: float, df2: float) -> float:
"""P(F <= f) for an F variable with (`df1`, `df2`) degrees of freedom."""
return 1.0 - f_sf(f, df1, df2)
class Manova:
"""Compares the between-group scatter matrix H with the within-group scatter matrix E."""
def __init__(self, config: ManovaConfig | None = None) -> None:
self.config = config or ManovaConfig()
@staticmethod
def scatter_matrices(groups) -> tuple[np.ndarray, np.ndarray]:
"""Between-group (H) and within-group (E) sums of squares and cross products, both (p, p).
groups: a sequence of arrays of shape (n_i, p).
"""
samples = [np.asarray(g, dtype=float) for g in groups]
grand = np.vstack(samples).mean(axis=0)
p = grand.size
h, e = np.zeros((p, p)), np.zeros((p, p))
for s in samples:
centre = s.mean(axis=0)
h += s.shape[0] * np.outer(centre - grand, centre - grand)
e += (s - centre).T @ (s - centre)
return h, e
def fit(self, groups) -> dict:
"""Run the test.
groups: a sequence of g >= 2 arrays of shape (n_i, p): n_i observations of p outcome variables.
A 1-D array is read as one variable (p = 1).
Returns a dict with `H`, `E` (p, p), `eigenvalues` of inv(E) H (largest first), and one entry per
statistic (`wilks`, `pillai`, `hotelling_lawley`, `roy`), each holding `value`, `f`, `df1`, `df2`,
`p_value`. `p_value` and `reject` at the top level belong to the configured statistic.
The F values are exact for Wilks when p <= 2 or g <= 3, exact for all four when g = 2, and
approximations otherwise. Roy's F is an upper bound, so its p-value is a lower bound.
"""
samples = [np.asarray(g, dtype=float) for g in groups]
samples = [s.reshape(-1, 1) if s.ndim == 1 else s for s in samples]
if len(samples) < 2:
raise ValueError("need at least 2 groups")
p = samples[0].shape[1]
if any(s.ndim != 2 or s.shape[1] != p for s in samples):
raise ValueError("every group must have shape (n_i, p) with the same p")
n_total, g = sum(s.shape[0] for s in samples), len(samples)
q, df_error = g - 1, n_total - g # hypothesis and error degrees of freedom
if df_error < p:
raise ValueError("need at least p more observations than groups")
h, e = self.scatter_matrices(samples)
eig = np.sort(np.clip(np.linalg.eigvals(np.linalg.solve(e, h)).real, 0.0, None))[::-1]
s = min(p, q)
eig_s = eig[:s] # the other eigenvalues are zero
m = (abs(p - q) - 1) / 2.0
n = (df_error - p - 1) / 2.0
wilks = float(np.prod(1.0 / (1.0 + eig_s)))
denom = p * p + q * q - 5
t = math.sqrt((p * p * q * q - 4) / denom) if denom > 0 else 1.0
df1 = float(p * q)
df2 = (df_error + q - (p + q + 1) / 2.0) * t - (p * q - 2) / 2.0
root = wilks ** (1.0 / t)
stats = {"wilks": self._entry(wilks, (1.0 - root) / root * df2 / df1, df1, df2)}
pillai = float(np.sum(eig_s / (1.0 + eig_s)))
df1, df2 = s * (2 * m + s + 1), s * (2 * n + s + 1)
stats["pillai"] = self._entry(pillai, pillai / (s - pillai) * df2 / df1, df1, df2)
trace = float(np.sum(eig_s))
df1, df2 = s * (2 * m + s + 1), 2 * (s * n + 1)
stats["hotelling_lawley"] = self._entry(trace, trace * df2 / (s * df1), df1, df2)
d = max(p, q)
df1, df2 = float(d), float(df_error - d + q)
stats["roy"] = self._entry(float(eig_s[0]), float(eig_s[0]) * df2 / df1, df1, df2)
chosen = stats[self.config.statistic]
return {"H": h, "E": e, "eigenvalues": eig, **stats,
"p_value": chosen["p_value"], "reject": chosen["p_value"] < self.config.alpha}
@staticmethod
def _entry(value: float, f: float, df1: float, df2: float) -> dict:
"""One row of the result: the statistic, its F approximation and the p-value."""
return {"value": value, "f": float(f), "df1": float(df1), "df2": float(df2),
"p_value": f_sf(float(f), df1, df2)}- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Generate three groups of 20 two-dimensional points with means , and and correlated noise. Call Manova().fit(groups) and read eigenvalues and the four statistics. Use Manova.scatter_matrices(groups) to get H and E and confirm that wilks equals .
Check on learning
- Two groups overlap heavily on outcome 1 and on outcome 2 when each is viewed alone, yet MANOVA rejects strongly. Sketch a data picture in which this happens.
A way to think about it
Think of two long, thin, parallel clouds of points lying along a diagonal. Project them onto each axis, then onto the direction across the clouds.
- With three groups whose mean vectors lie on one straight line, how many eigenvalues do you expect to be clearly above zero, and which statistic uses that fact best?
A way to think about it
The eigenvalues count independent directions of separation. Compare a statistic that looks only at the largest with ones that sum over all.
- Why does running separate ANOVAs at level not control the error rate the way one MANOVA does?
A way to think about it
Work out the chance of at least one false rejection across several tests, then consider that correlated outcomes make the tests overlap in what they detect.
- What happens to when you have 10 outcomes but only 8 error degrees of freedom, and why does the template raise an error in that case?
A way to think about it
A sum of 8 independent outer products can have rank at most 8. Ask whether a 10 by 10 matrix of rank 8 can be inverted.