06 · Array statistics¶
You will learn the statistics engine that synaptome's questions and tests are built on: two-sample tests (including "better by a margin"), estimates with confidence intervals, the bootstrap, multiple-comparison correction, and the cluster permutation test for curves. Everything here works on plain NumPy arrays, without a study.
You need NumPy. No earlier tutorial is required: this one stands on its own. Later tutorials run the same functions for you, straight from a study.
import numpy as np
from synaptome import engine
Two matched samples¶
Twenty participants were measured before and after a training programme. Each participant gives one pair of values, so the samples are paired.
rng = np.random.default_rng(0)
before = rng.normal(50, 8, size=20)
after = before + rng.normal(4, 5, size=20)
paired_test runs a Wilcoxon signed-rank test by default, which assumes no normal distribution. The
result also carries an effect size, here the rank-biserial correlation (positive means after is larger).
res = engine.paired_test(after, before)
res
StatResult(test='wilcoxon', statistic=7.0, p_value=3.62396240234375e-05, n=20, effect_size=0.9333333333333333, effect_size_type='rank_biserial', group_sizes=None, df=None, n_eff=None, alternative='two-sided', offset=0.0, zero_method='wilcox')
The question can also be "did scores improve by more than 2 points?". offset sets the difference
tested against, and alternative makes the test one-sided. The effect size still describes the raw
difference: only the p-value answers the new question.
margin = engine.paired_test(after, before, test="ttest", offset=2.0, alternative="greater")
margin.p_value, margin.effect_size
(0.004655898552707137, 1.2068112018742212)
For a yes/no outcome coded 0/1 (passed the exam or not), the McNemar test uses only the participants whose answer changed.
passed_before = np.array([0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0])
passed_after = np.array([1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1])
engine.paired_test(passed_after, passed_before, test="mcnemar").p_value
0.0625
How large? Estimates and intervals¶
A p-value says whether there is a difference, not how large it is. Estimators give the size, and an analytic interval gives its precision. The Hodges-Lehmann estimate is the median-like shift that goes with the Wilcoxon test; the mean difference goes with the t-test.
diff = after - before
print("mean difference:", round(engine.mean_diff(after, before, paired=True), 2), engine.t_interval(diff))
print("Hodges-Lehmann: ", round(engine.hodges_lehmann(diff), 2), engine.signed_rank_interval(diff))
mean difference: 4.31 (2.639422305698352, 5.983474882248325) Hodges-Lehmann: 4.21 (2.5316513515997308, 5.88876176798037)
Proportions get intervals that stay within [0, 1]: Wilson for one proportion, Newcombe for the change in a proportion between two matched samples.
print("pass rate after:", engine.wilson_interval(passed_after))
print(
"change in pass rate:",
engine.prop_diff(passed_after, passed_before),
engine.newcombe_interval(passed_after, passed_before),
)
pass rate after: (0.46769466506643426, 0.9110583316059453) change in pass rate: 0.4166666666666667 (0.06441308128094764, 0.6429681830152245)
The bootstrap¶
Standardized effect sizes such as Hedges' g have no simple interval. The bootstrap recomputes the
estimator on resampled data; the spread of these draws gives the interval. Resampling is random, so pass
a seed for reproducible numbers.
treated = rng.normal(1.0, 1.0, size=25)
control = rng.normal(0.0, 1.0, size=30)
estimate = engine.hedges_g(treated, control)
draws = engine.bootstrap_draws(engine.hedges_g, treated, control, n_boot=2000, seed=1)
estimate, draws[:5]
(1.011891757894214, array([0.58010368, 1.09202522, 0.65970417, 0.85981474, 1.18244544]))
The same draws give an interval and a p-value that always agree: the p-value is below 0.05 exactly
when the 95% interval excludes 0. "bca" corrects the interval for bias and skew; bootstrap_bias shows
how much there was to correct.
accel = engine.jackknife_acceleration(*engine.jackknife_values(engine.hedges_g, treated, control))
low, high = engine.bootstrap_interval(draws, estimate, interval="bca", acceleration=accel)
p = engine.bootstrap_pvalue(draws, null=0.0, interval="bca", estimate=estimate, acceleration=accel)
print(f"g = {estimate:.2f}, 95% CI [{low:.2f}, {high:.2f}], p = {p:.4f}")
engine.bootstrap_bias(draws, estimate)
g = 1.01, 95% CI [0.49, 1.57], p = 0.0038
{'bias': 0.024156325666554235,
'se': 0.27929642842914104,
'bias_se_ratio': 0.08648991969721095,
'z0': -0.03008407662018911}
bootstrap_ci does all of this in one call.
engine.bootstrap_ci(engine.hedges_g, treated, control, seed=1)
(0.49366790269761557, 1.5719535671908302)
Several comparisons¶
Testing many outcomes inflates the chance of a false positive. correct_pvalues adjusts one family of
p-values, here with Holm's method, and says which stay significant.
p_values = [0.004, 0.03, 0.02, 0.4]
engine.correct_pvalues(p_values, method="holm")
(array([0.016, 0.06 , 0.06 , 0.4 ]), array([ True, False, False, False]))
Comparing two curves¶
When each participant gives a whole curve (a response over 40 time points), testing every time point multiplies the comparisons. The cluster permutation test groups neighbouring time points where the difference is strong into clusters, and judges each cluster against curves whose labels were randomly flipped. Here a real difference sits between time points 15 and 25.
n_subjects, n_times = 20, 40
noise = rng.normal(size=(2, n_subjects, n_times + 4))
condition_a, condition_b = (np.stack([np.convolve(r, np.ones(5) / 5, "valid") for r in m]) for m in noise)
condition_a[:, 15:25] += 0.8
res = engine.cluster_permutation(condition_a, condition_b, n_permutations=500, seed=0)
for (start, stop), p in zip(res.clusters, res.p_values, strict=True):
print(f"time points {start}-{stop - 1}: p = {p:.3f}")
time points 15-24: p = 0.002 time points 31-34: p = 0.090
Only the planted cluster is significant. The other one is noise: random relabellings produce clusters
that large easily, so its p-value is high. cluster_alpha sets how strong a time point must be to join a
cluster; it is not the significance level of the clusters.
Next: 07 · Toy studies introduces ready-made studies with known effects, which the following tutorials use to ask questions of a whole study.