Levene's Test for Homogeneity of Variances
Parametric Tests
Are the group variances equal enough?
Levene's test asks whether two or more groups have the same variance. That question matters because the standard one-way ANOVA â and the t-tests that follow it â assume the groups share a common variance, and when that assumption is badly violated the test's actual error rate drifts away from the one you chose. A supposedly five-per-cent test can behave like a ten-per-cent test when one group is dramatically noisier than the others.
The test's defining idea is elegant and worth internalising: rather than work with the raw values, which are not normally distributed when the means differ, it works with each value's absolute deviation from its group centre. Those deviations are much closer to normal, so the subsequent F-test on them is far more robust than the classical variance-ratio F-test it replaced.
- Check the equal-variance assumption behind ANOVA and pooled t-tests.
- More robust than the classical F-test, especially with non-normal data.
- The Brown-Forsythe variant â deviations from the median â is the default in most libraries.
Why equal variances matter
The pooled variance in a t-test or the mean square error in an ANOVA is a weighted average of the group variances, and the weighting assumes each group contributes an equally noisy estimate of the same underlying quantity. When that is true, the F and t reference distributions are correct. When one group has four times the variance of another, the pooled estimate is dominated by the noisy group, and the nominal degrees of freedom no longer describe the statistic's actual sampling behaviour.
The practical consequences are concrete. Confidence intervals for differences in means become miscalibrated â too narrow in the direction that matters. The Type I error rate of the omnibus F-test inflates when group sizes are unequal and the smaller groups are the noisier ones, which is the common real-world configuration. And effect sizes computed under the pooled assumption become hard to interpret, because there is no single variance to refer to.
The classical alternative, the variance-ratio F-test, compares the largest sample variance to the smallest. Its weakness is that it is extremely sensitive to non-normality: with heavy-tailed data it rejects equal variances that are in fact equal, which is why Levene's test displaced it in routine practice and why most software no longer offers the classical test as the default.
How the test works
Levene's construction is a transformation followed by a completely ordinary one-way ANOVA. Replace each observation with its absolute deviation from its group's centre, then run an F-test asking whether the mean deviations differ across groups. If the groups have equal spread, their mean deviations should be equal too.
Here Y_ij is observation j in group i, and tilde Y_i is that group's centre â the mean in the original formulation, the median in the Brown-Forsythe variant. Because the ANOVA on the Z values reuses machinery you already know, the test's assumptions reduce to independence of observations and the robustness of the ANOVA to non-normality, which the absolute-deviation step substantially improves.
import numpy as np
import pandas as pd
from scipy import stats
rng = np.random.default_rng(42)
# Three groups with genuinely different spreads
group_a = rng.normal(50, 5, size=30)
group_b = rng.normal(50, 8, size=30)
group_c = rng.normal(50, 14, size=30)
data = pd.DataFrame({
"value": np.concatenate([group_a, group_b, group_c]),
"group": ["A"] * 30 + ["B"] * 30 + ["C"] * 30,
})
# Levene by hand: deviations from the group mean
data["dev_from_mean"] = (
data["value"] - data.groupby("group")["value"].transform("mean")
).abs()
f_stat, p_value = stats.f_oneway(
*[g["dev_from_mean"].values for _, g in data.groupby("group")]
)
print(f"Levene (mean-centred): F = {f_stat:.3f}, p = {p_value:.4f}")
# The library call should match
lev_mean = stats.levene(
group_a, group_b, group_c, center="mean"
)
lev_med = stats.levene(
group_a, group_b, group_c, center="median"
)
print(f"scipy, center='mean': F = {lev_mean.statistic:.3f}, p = {lev_mean.pvalue:.4f}")
print(f"scipy, center='median': F = {lev_med.statistic:.3f}, p = {lev_med.pvalue:.4f}")
The hand calculation in that script is the whole algorithm: group, subtract the centre, take the absolute value, run an ANOVA. Seeing it written out demystifies the library call and makes the next section's variants obvious rather than arbitrary.
Mean, median, and trimmed centres
The only free parameter in Levene's test is which centre defines the deviations, and the choice changes the test's robustness profile in a predictable way.
| Centre | Definition | Robustness | Typical use |
|---|---|---|---|
| Mean | deviation from group mean | moderate | original Levene; good under normality |
| Median | deviation from group median | high | Brown-Forsythe; the common default |
| Trimmed mean | deviation from 10% trimmed mean | high | compromise between the two |
| Custom | any robust location | variable | specialised or heavy-tailed designs |
# Compare the three centres on skewed data
skewed = [
rng.lognormal(2.0, 0.3, size=40),
rng.lognormal(2.0, 0.6, size=40),
rng.lognormal(2.0, 0.5, size=40),
]
for center in ["mean", "median", "trimmed"]:
if center == "trimmed":
from scipy.stats import trim_mean
# scipy's levene supports 'trimmed' with proportionto=0.05
result = stats.levene(*skewed, center="trimmed", proportiontocut=0.05)
else:
result = stats.levene(*skewed, center=center)
print(f"center={center:<8} F = {result.statistic:6.3f}, p = {result.pvalue:.4f}")
# Show why: the centres differ on skewed data
for i, g in enumerate(skewed, start=1):
print(f"Group {i}: mean={g.mean():.2f}, median={np.median(g):.2f}, "
f"std={g.std(ddof=1):.2f}")
The median-centred version is the default in most software because it behaves well across the widest range of data shapes. Under perfect normality the mean-centred version has slightly more power, and that difference is rarely decisive in practice. Unless you have a specific reason, reach for center="median" and say so in the report.
Running the test in a real workflow
The test earns its place in an analysis by being run before the ANOVA, not after, and by its result actually changing what you do next.
# Simulated experiment: reaction time by drug dose
doses = {
"placebo": rng.normal(250, 30, size=25),
"low": rng.normal(240, 35, size=25),
"high": rng.normal(220, 55, size=25),
}
# 1. Descriptive check first
summary = pd.DataFrame({
"n": {k: len(v) for k, v in doses.items()},
"mean": {k: v.mean() for k, v in doses.items()},
"sd": {k: v.std(ddof=1) for k, v in doses.items()},
})
summary["var"] = summary["sd"] ** 2
summary["max/min var"] = summary["var"] / summary["var"].min()
print(summary.round(2))
# 2. Levene's test
lev = stats.levene(*doses.values(), center="median")
print(f"\nLevene: F = {lev.statistic:.3f}, df = ({len(doses)-1}, {sum(len(v) for v in doses.values())-len(doses)}), p = {lev.pvalue:.4f}")
# 3. Decide what to run next
alpha = 0.05
if lev.pvalue < alpha:
print("Variances differ: use Welch's ANOVA, not classic ANOVA.")
# Welch's one-way ANOVA
from scipy.stats import f_oneway
# scipy does not ship Welch's ANOVA; use pingouin if available
try:
import pingouin as pg
welch = pg.welch_anova(dv="value", between="group", data=long_df)
print(welch)
except ImportError:
print("Install pingouin for Welch's ANOVA, or use Games-Howell post hoc.")
else:
print("Variances look equal: classic ANOVA is appropriate.")
f_stat, p_val = stats.f_oneway(*doses.values())
print(f"Classic ANOVA: F = {f_stat:.3f}, p = {p_val:.4f}")
Note the order of operations: descriptive variances first, because a ratio of largest to smallest above roughly three warns you before any formal test does; then Levene; then the choice of ANOVA. Levene's test with small samples has modest power, so a non-significant result is weak evidence of equality, which is why the descriptive ratio stays in the report alongside the p-value.
Interpreting the result
A significant Levene's test is a signal to change analysis strategy, not a finding to report as though it were the study's result. The three standard responses are Welch's ANOVA, a rank-based alternative, or a variance-stabilising transformation, and which one you pick depends on what the unequal variances are doing to your estimand.
# How unequal variances distort the classic F-test: a simulation
def simulate_f_distortion(n_per_group=20, reps=2000, var_ratio=4.0):
"""Type I error of classic vs Welch ANOVA under unequal variances."""
false_classic = 0
false_welch = 0
for _ in range(reps):
a = rng.normal(0, 1, n_per_group)
b = rng.normal(0, np.sqrt(var_ratio), n_per_group)
c = rng.normal(0, 1, n_per_group)
# Classic: equal n keeps it fairly robust
f, p = stats.f_oneway(a, b, c)
if p < 0.05:
false_classic += 1
try:
from scipy.stats import ttest_ind
# Approximate Welch via pairwise with correction is messy;
# pingouin's welch_anova is the clean path
import pingouin as pg
long_df = pd.DataFrame({
"value": np.concatenate([a, b, c]),
"group": ["a"] * n_per_group + ["b"] * n_per_group + ["c"] * n_per_group,
})
w = pg.welch_anova(dv="value", between="group", data=long_df)
if w["p-unc"].values[0] < 0.05:
false_welch += 1
except ImportError:
pass
return false_classic / reps, false_welch / reps
classic_rate, welch_rate = simulate_f_distortion()
print(f"Type I error, classic ANOVA: {classic_rate:.3f}")
print(f"Type I error, Welch ANOVA: {welch_rate:.3f}")
print("Target rate is 0.05 for both.")
Welch's ANOVA is almost always the safe default when Levene's test is significant, because it never performs worse than classic ANOVA when variances are equal and substantially outperforms it when they are not. The cost is a slightly more complicated formula and degrees of freedom that are rarely round numbers.
# Variance-stabilising transformation as an alternative response
log_data = {k: np.log(v) for k, v in doses.items()}
lev_raw = stats.levene(*doses.values(), center="median")
lev_log = stats.levene(*log_data.values(), center="median")
print(f"Levene on raw scale: p = {lev_raw.pvalue:.4f}")
print(f"Levene on log scale: p = {lev_log.pvalue:.4f}")
# Check what the transformation did to the means as well
means = pd.DataFrame({
"raw mean": {k: v.mean() for k, v in doses.items()},
"log mean": {k: v.mean() for k, v in log_data.items()},
})
print(means.round(3))
The transformation route changes the question you are answering: on the log scale you are testing differences in geometric means, not arithmetic ones. That is often the more meaningful question for skewed measurements, but it must be stated explicitly, because the two analyses can disagree in ways that look like contradictions and are not.
Brown-Forsythe and relatives
Levene's test is itself a special case of a small family. The O'Brien and Brown-Forsythe procedures differ in how they scale the deviations before the ANOVA, and the Bartlett test takes the opposite philosophical position by working directly on the variances and paying for it with a normality requirement.
| Test | Works on | Robust to non-normality | Notes |
|---|---|---|---|
| Levene (mean) | absolute deviations from mean | moderate | original formulation |
| Brown-Forsythe | absolute deviations from median | high | recommended default |
| Bartlett | sample variances directly | low | powerful when normality holds |
| Fligner-Killeen | ranked deviations from median | very high | rank-based, distribution-free |
# Bartlett: powerful but fragile
bart = stats.bartlett(*doses.values())
lev = stats.levene(*doses.values(), center="median")
# Fligner-Killeen: rank-based, most robust
flig = stats.fligner(*doses.values(), center="median")
print(f"Bartlett: chi2 = {bart.statistic:.3f}, p = {bart.pvalue:.4f}")
print(f"Levene (median): F = {lev.statistic:.3f}, p = {lev.pvalue:.4f}")
print(f"Fligner-Killeen: chi2 = {flig.statistic:.3f}, p = {flig.pvalue:.4f}")
# Agreement across the three is itself informative
ps = [bart.pvalue, lev.pvalue, flig.pvalue]
verdicts = ["reject" if p < 0.05 else "fail to reject" for p in ps]
print(f"Verdicts: {dict(zip(['Bartlett', 'Levene', 'Fligner'], verdicts))}")
When all three agree, the conclusion is robust to the choice of test. When Bartlett alone rejects, suspect non-normality rather than a variance difference. When the rank-based tests reject and Bartlett does not, the variance difference is real but the data are far from normal â exactly the situation Levene's test was built for.
Mistakes that misuse the test
Common Mistakes
Treating a significant Levene's test as a study result
Fix: It is an assumption check; report it as a methodological step, not a finding.
Ignoring Levene's test when group sizes are unequal
Fix: Unequal n plus unequal variances is the combination that inflates Type I error most.
Using the mean-centred version on clearly non-normal data
Fix: Switch to center='median' (Brown-Forsythe) or Fligner-Killeen.
Accepting equality from a non-significant test with tiny samples
Fix: Levene has low power at small n; report the variance ratio alongside the p-value.
Running Levene's test after choosing the ANOVA variant
Fix: Decide the strategy from the test, so the analysis path is determined by evidence.
Forgetting that transforming the data changes the estimand
Fix: A log-scale analysis answers a geometric-mean question; say so explicitly.
Applying Levene's test to paired or repeated measures
Fix: The test assumes independent groups; for paired designs examine differences instead.
Practices that keep the check useful
Best Practices
- Run Levene's test before the ANOVA and let its result choose the variant.
- Use center='median' unless you have a specific reason not to.
- Report the ratio of largest to smallest variance alongside the p-value.
- Default to Welch's ANOVA when variances differ or group sizes are unequal.
- Consider Fligner-Killeen when the data are markedly non-normal.
- State whether a transformation was applied and what it changes about the estimand.
- Check independence of observations first; no variance test rescues a dependent sample.
- Pair the assumption check with an effect size for the group comparison itself.
Key takeaways
Key Takeaways
- Unequal variances distort classic ANOVA and pooled t-tests, especially with unequal group sizes.
- Levene's test converts the variance question into an ANOVA on absolute deviations, which is far more robust.
- The median-centred Brown-Forsythe variant is the recommended default.
- A significant result is a methodological signal: switch to Welch's ANOVA or a robust alternative.
- Non-significance at small samples does not establish equality; report the variance ratio too.
- Bartlett is fragile under non-normality; Fligner-Killeen is the rank-based extreme.
- Transformations stabilise variance but change the estimand, which must be stated.
Where to go next
- F-Test for Equality of Variances â the classical variance-ratio test Levene's replaced.
- One-Way ANOVA â the analysis this test supports.
- Heteroscedasticity â the same problem in the regression setting.
- Effect Size â quantifying group differences once the assumptions are settled.