3. Bi- and multivariate statistics

Situation in the previous module: univariate data, where we are looking at a single variable at a time.
…but most data analysis problems, however, deal with two or more variables.
Goal: learn to study the relationships that may or may not exist between two different variables.
Different possibilities:

One sample, two variables measured on each individual. This is an example of paired variables: \(X_i\) is paired with \(Y_i\), as they are both coming from the same individual.
Typical questions in this case: is there a correlation between \(X\) and \(Y\)? Are \(X\) and \(Y\) independent?
Different possibilities:

Two samples on the same individuals, measuring the same variable under different conditions (ex. different time). The variables are also paired in the case, but in addition to that they have the same scale and units.
Typical questions in this case: does the change in the conditions cause a change in the measure? Is \(X_{i}(t_0) \neq X_{i}(t_1)\)?
Different possibilities:

One sample with two variables, one of which is a categorical grouping variable. This is equivalent to having several samples (one per category of the grouping variable) with the same variable measured on different individuals.

Typical questions in this case: is the distribution of the variable different in the two groups? Do they have the same mean?
When looking at the relationship between variables, we often make a distinction between independent variables (the “input” of the system, what we directly control in an experimental study) and the dependent variables (the “output”, which we measure).

This distinction can be arbitrary, and deciding on which variable occupies which role doesn’t prove causality in the relationship.
Example: we are measuring the effect of the treatment group (A or B, independent variable) on the temperature (dependent variable).
Correlation between variables: the “strength” of the relationship. If two variables are correlated, knowing the value of one gives us information about the (likely) value of the other. Correlation is a type of dependence.
Correlation does not prove causality.
Dependence:
\(Y = f(X, k)\)
\(P(Y | X) \neq P(Y)\)
Independence:
\(Y = f(k), X = f(m)\)
\(P(Y | X) = P(Y)\)
Confounding variable:
\(Y = f(t, k), X = f(t, m)\)
\(P(Y | X) \neq P(Y)\)
Type of link also depends on the types of variables:
Easiest representation: a contingency table. Example:
| Anterior | Posterior | Left-lateral | Right-lateral | TOTAL | |
|---|---|---|---|---|---|
| Grade I | 4 | 6 | 5 | 12 | 27 |
| Grade II | 7 | 9 | 6 | 7 | 29 |
| Grade III | 1 | 2 | 0 | 1 | 4 |
| TOTAL | 12 | 17 | 11 | 20 | 60 |
Question: what would be the expected contingency table if there is no relationship between the variables ?
If there is no relationship, then the “total” in each group are simply a reflection of the population distribution.
| Anterior | Posterior | Left-lateral | Right-lateral | TOTAL | |
|---|---|---|---|---|---|
| Grade I | 27 | ||||
| Grade II | 29 | ||||
| Grade III | 4 | ||||
| TOTAL | 12 | 17 | 11 | 20 | 60 |
The values inside the table would then be expected to keep the ratios between groups constant in all categories (i.e.: \(P(Posterior | Grade II) = P(Posterior)\))
| Anterior | Posterior | Left-lateral | Right-lateral | TOTAL | |
|---|---|---|---|---|---|
| Grade I | 27 | ||||
| Grade II | \(=\frac{17*29}{60}=8.22\) | 29 | |||
| Grade III | 4 | ||||
| TOTAL | 12 | 17 | 11 | 20 | 60 |
| Anterior | Posterior | Left-lateral | Right-lateral | TOTAL | |
|---|---|---|---|---|---|
| Grade I | 5.4 | 7.65 | 4.95 | 9 | 27 |
| Grade II | 5.8 | 8.22 | 5.32 | 9.67 | 29 |
| Grade III | 0.8 | 1.13 | 0.73 | 1.3 | 4 |
| TOTAL | 12 | 17 | 11 | 20 | 60 |
Intuitively, we can say that there is a relationship between the two variables if the observed frequencies are sufficiently different from the expected frequencies.
\(\Rightarrow\) hypothesis test with \(H_0\): independence of the variables.
| \(Y_1\) | … | \(Y_j\) | … | \(Y_p\) | ||
|---|---|---|---|---|---|---|
| \(X_1\) | ||||||
| … | ||||||
| \(X_i\) | \(n_{ij}\) | \(n_{i.}\) | ||||
| … | ||||||
| \(X_r\) | ||||||
| \(n_{.j}\) | \(n\) |
Independent variables \(\Rightarrow n_{ij} \rightarrow \frac{n_{i.}n_{.j}}{n}\)
Graphical representation: heatmap

Choice of colormap is arbitrary. Readability is more important than esthetics.
Simplest graphical representation: scatterplot. Alternative (particularly if high density of points): bin into categories and show heatmap.


Correlation between the two variables if \(E(Y | X=x ) = f(x)\) (and \(E(X | Y=y) = g(y)\)), i.e. the expected value of one variable is a function of the value of the other.






Finding the relationship \(Y = f(x)\) is the goal of regression tasks. Typically: we define a regression model (eg linear regression: \(y = ax + b\)), then try to determine the parameters (here \(a, b\)) of the function so that it fits the data as much as possible.
Commonly used characteristics of the relationship between numerical variables: the covariance and the Pearson Correlation Coefficient (for linear correlation only).
Both are related:
\(cov_{X,Y} =
E[(X-\mu_X)(Y-\mu_Y)]\)
\(corr_{X,Y} =
\frac{E[(X-\mu_X)(Y-\mu_Y)]}{\sigma_X \sigma_Y} =
\frac{cov_{X,Y}}{\sigma_X \sigma_Y}\)
Both are descriptions of how the variations of two variables are related. Positive covariance (or correlation) means that they increase together, negative covariance (or correlation) that one decreases when the other increases.
Interpretation depends on which is considered as dependent. If X is the independent and Y the dependent variable:
Numerical Y and Categorical X \(\rightarrow\) study the variation of Y depending on the category X. This is equivalent to splitting the dataset in multiple samples (one per category). Y can then be characterized for each group, and compared between groups. Graphically, it is common to use the boxplot or the violin plot for this purpose.


Interpretation depends on which is considered as dependent. If X is the independent and Y the dependent variable:
Numerical Y and Categorical X \(\rightarrow\) study the variation of Y depending on the category X. This is equivalent to splitting the dataset in multiple samples (one per category). Y can then be characterized for each group, and compared between groups. Graphically, it is common to use the boxplot or the violin plot for this purpose.


Interpretation depends on which is considered as dependent. If X is the independent and Y the dependent variable:
Categorical Y and Numerical X \(\rightarrow\) study the category of Y depending on the value of X. This is the classic setup of a classification problem. If we have a single numerical variable, this could lead to a very simple threshold classification criterion (e.g. \(X < t_0 \Rightarrow Y = Y_0\), \(t_0 \leq X \Rightarrow Y = Y_1\)).


Interpretation depends on which is considered as dependent. If X is the independent and Y the dependent variable:
Categorical Y and Numerical X \(\rightarrow\) study the category of Y depending on the value of X.
Measures of the quality of a decision criterion: true positives (TP), false positives (FP), true negatives (TN), false negatives (FN).
\(N = TP + FP + TN + FN\)
\(Accuracy = \frac{TP+TN}{N}\)
\(Sensitivity = Recall = \frac{TP}{TP+FN}\)
\(Specificity = Precision = \frac{TP}{TP+FP}\)

We want to choose the best material to use for an implantable sensor. In an animal study, we implant ten rats with sensors of material A and ten rats with sensors of material B, and measure their accuracy in controlled conditions. Which of these statements about the variables MATERIAL and ACCURACY is most accurate:
Material is a categorical variable (categories: A or B).
Accuracy is a numerical variable (continuous measure).
We want to understand if changing the material has an impact on the accuracy, therefore the accuracy is the “outcome”, or dependent variable, and the material is the independent “input” variable.

Poster by Verstraeten et al., 2024.
What are they measuring in the study? What relationship are they trying to find, and what is the time of the variables being studied? What is the hypothesis that they are trying to validate?
Before collecting the data:
State the problem / ask the question(s)
What is the effect of treatment A on patients suffering from B
?
Frame in terms of measurable parameters, and their expected
values.
M is a marker of disease B \(\rightarrow\) if the treatment works, we
expect M to be lower after treatment.
Collect the data necessary to answer the question /
solve the problem.
Clinical study with measure of M before and after treatment in N
patients.
Check the validity of the data and perform descriptive
analysis.
Perform statistical tests to accept / reject the
hypothesis.
Test shows that the null hypothesis \(M_{after} \geq M_{before}\) can be rejected
with a p-value < 0.05, so we conclude that \(M_{after} < M_{before}\) is likely to be
true, and the treatment probably works.
Which statistical test to use depends on…

It’s complicated!
Some references:
In this course…

Univariate tests: test on the characteristics of a single variable.
Test on the central value
Test on the distribution shape


Bivariate tests on paired variables: test the relationship between two variables.
Test depend on…
Typical situation: we have a set of individuals on which we take a categorical measurements under two different conditions (example: before and after treatment).
If the “categorical measurement” is a binary outcome (example: positive / negative, correct / incorrect, sick / healthy, alive / dead…), then we can use McNemar test.
if we have more categories, extensions such as the Stuart-Maxwell “marginal homogeneity” test can be used (will not be discussed in this course).
Example: on a test dataset with 50 images, we are comparing the results of two different classification algorithms, which can either be Correct or Incorrect. Are the results of the algorithms significantly different ?
A contigency table for such a problem could look like this:
| A Correct | A Incorrect | |
|---|---|---|
| B Correct | 35 | 7 |
| B Incorrect | 3 | 5 |
\(H_0: P(A Incorrect | B Correct) = P(B Incorrect | A Correct)\)
In other words: we are testing if the two algorithms are wrong “in the same way”.
More generally, given two groups/conditions \(A\) and \(B\) and a binary dependent variable \(Y \in [0, 1]\), we have:
| \(A\) and \(Y=0\) | \(A\) and \(Y=1\) | |
|---|---|---|
| \(B\) and \(Y=0\) | a | b |
| \(B\) and \(Y=1\) | c | d |
Under \(H_0\): \(X^2 = \frac{(b-c)^2}{b+c} \sim \chi^2_1\).
| A Correct | A Incorrect | |
|---|---|---|
| B Correct | 35 | 7 |
| B Incorrect | 3 | 5 |
If we look at the algorithms individually, we can compute their accuracy: \(ACC_A = \frac{38}{50} = 76\%\), \(ACC_B = \frac{42}{50} = 84\%\). But is this difference significant ?
\(X^2 = \frac{(7-3)^2}{7+3} = 1.6\), and \(P(x \geq 1.6 | x \sim \chi^2_1) = 0.21\) \(\rightarrow\) the p-value is 0.21 and we can’t reject the hypothesis that the difference between the two algorithms is simply due to random sampling.


\(\rightarrow\) testing for correlations

\(\rightarrow\) testing for equality of central value.



Linear correlation for normally distributed variables: Pearson Correlation Coefficient (\(r\)).
\(r = \frac{cov(X, Y)}{s_X s_Y} = \frac{\sum_{i=1}^{n}(x_i-\bar{x})(y_i-\bar{y})}{\sqrt{\sum_{i=1}^{n}(x_i-\bar{x})^2\sum_{i=1}^{n}(y_i-\bar{y})^2}}\), with \(-1 < r < 1\).
Statistical test for the significance of the linear correlation coefficient: \(H_0: r = 0, H_1: r \neq 0\) (\(H_0\) here does not mean independence, only no linear correlation!)
If \(X\) and \(Y\) follow normal distributions and \(r = 0\), then:
\(T = \frac{r\sqrt{n-2}}{\sqrt{1-r^2}} \sim t_{n-2}\), and we can reject \(H_0\) if \(|T_{obs}| > t_{n-2, 1-\alpha/2}\).




Non-parametric equivalent: Spearman’s Rank Correlation Coefficient.
Let \(R_i\) be the rank of \(x_i\) in the sample, and \(S_i\) be the \(rank\) of \(y_i\) in the sample, for the two variables \(X, Y\).
\(r_s = \frac{\sum_{i=1}^{n}(R_i-\bar{R_i})(S_i-\bar{S_i})}{\sqrt{\sum_{i=1}^{n}(R_i-\bar{R_i})^2\sum_{i=1}^{n}(S_i-\bar{S_i})^2}}\)
If no ties in ranking, this can be reduced to: \(r_s = 1 - \frac{6\sum_{i=1}^{n}(R_i-S_i)^2}{n^3-n}\)
Spearman’s coefficient will detect any monotonic relationship between \(X\) and \(Y\).

\(\rightarrow\) testing for equality of central value.
Paired samples for numerical data: look at the difference between the two conditions for each individual \(\rightarrow\) \(X_a - X_b\) is a univariate, one-sample random variable.
Parametric: Student’s paired samples t-test = one-sample t-test on \(d_i = x_{a,i}-x_{b,i}\) with \(H_0: \bar{d} = 0\). Under \(H_0\), the test statistic \(t = \frac{\bar{d}}{s/\sqrt{n}} \sim t_{n-1}\), where \(s\) is the observed standard deviation of \(d\).
Non-parametric: if symmetrical distribution, Wilcoxon signed-rank test on \(d_i = x_{a,i}-x_{b,i}\) with \(H_0: Median[d] = 0\). If non-symmetrical, sign test.
Mix of categorical and numerical variables: categorical variable determines groups. Dataset is split along those groups, so that we treat the data as multiple samples.
Example: instead of considering one sample with variables “TREATMENT GROUP” and “BLOOD PRESSURE”, we would each treatment group can be used as a separate unpaired sample, with variable “BLOOD PRESSURE”.

Two slightly different cases are covered here. First: one categorical independent grouping variable (e.g. treatment vs control) with one dependent categorical variable (e.g. success at performing some task).
| Individual | Group | Task |
|---|---|---|
| 1 | Treatment | Success |
| … | … | … |
| N | Control | Failure |
This is equivalent to splitting the dataset into two samples (per the grouping variable), potentially of different sizes:
Treatment group:
| Individual | Task |
|---|---|
| 1 | Success |
| … | … |
| m | Success |
Control group:
| Individual | Task |
|---|---|
| 1 | Success |
| … | … |
| n | Failure |
Second: two categorical variables measured on the same individuals, without one having a particularly different status from the other (e.g. country of residence, gender).
| Individual | Country | Gender |
|---|---|---|
| 1 | FR | M |
| … | … | … |
| N | BE | F |
What would the contingency tables look like in both cases?
| Individual | Group | Task |
|---|---|---|
| 1 | Treatment | Success |
| … | … | … |
| N | Control | Failure |
\(\rightarrow\)
| Group \ Task | Success | Failure |
|---|---|---|
| Treatment | ||
| Control |
| Individual | Country | Gender |
|---|---|---|
| 1 | FR | M |
| … | … | … |
| N | BE | F |
\(\rightarrow\)
| Country \ Gender | M | F |
|---|---|---|
| BE | ||
| FR | ||
| … | ||
| US |
Note the slight difference with the setup of McNemar. If, for instance, the groups were “Pre-treatment” and “Post-treatment”, and the measure are done on the same individuals, we can’t have:
Incorrect:
| Group \ Task | Success | Failure |
|---|---|---|
| Pre-Treatment | ||
| Post-Treatment |
Correct:
| Pre \ Post | Success | Failure |
|---|---|---|
| Success | ||
| Failure |
Otherwise the same individual would appear twice in the table. It would be equivalent to looking at the “raw data” like this:
| Individual | Group | Task |
|---|---|---|
| 1 | Pre-Treatment | Success |
| 1 | Post-Treatment | Success |
| … | … | … |
| N | Pre-Treatment | Failure |
| N | Post-Treatment | Success |
| \(Y_1\) | … | \(Y_j\) | … | \(Y_p\) | ||
|---|---|---|---|---|---|---|
| \(X_1\) | ||||||
| … | ||||||
| \(X_i\) | \(n_{ij}\) | \(n_{i.}\) | ||||
| … | ||||||
| \(X_r\) | ||||||
| \(n_{.j}\) | \(n\) |
\(H_0: n_{ij} = e_{ij} := \frac{n_{i.}n_{.j}}{n}\)
Test statistic: \(X^2 = \sum_{i=1}^r \sum_{j=1}^p \frac{(n_{ij}-e_{ij})^2}{e_{ij}} \sim \chi_{(r-1)(p-1)}^2\) under \(H_0\).
\(H_0: n_{ij} = e_{ij} := \frac{n_{i.}n_{.j}}{n}\)
Test statistic: \(X^2 = \sum_{i=1}^r \sum_{j=1}^p \frac{(n_{ij}-e_{ij})^2}{e_{ij}} \sim \chi_{(r-1)(p-1)}^2\) under \(H_0\).
P-value: \(P(X^2 \geq x^2 | H_0)\), where \(x^2\) is the observed value of the statistic. Reject \(H_0\) if \(< \alpha\).
Application conditions:
| Anterior | Posterior | Left-lateral | Right-lateral | TOTAL | |
|---|---|---|---|---|---|
| Grade I | 4 | 6 | 5 | 12 | 27 |
| Grade II | 7 | 9 | 6 | 7 | 29 |
| Grade III | 1 | 2 | 0 | 1 | 4 |
| TOTAL | 12 | 17 | 11 | 20 | 60 |
| Anterior | Posterior | Left-lateral | Right-lateral | TOTAL | |
|---|---|---|---|---|---|
| Grade I | 4 | 6 | 5 | 12 | 27 |
| Grade >= II | 8 | 11 | 6 | 8 | 33 |
| TOTAL | 12 | 17 | 11 | 20 | 60 |
Expected values under \(H_0\):
| Anterior | Posterior | Left-lateral | Right-lateral | TOTAL | |
|---|---|---|---|---|---|
| Grade I | 5.4 | 7.65 | 4.95 | 9 | 27 |
| Grade >= II | 6.6 | 9.35 | 6.05 | 11 | 33 |
| TOTAL | 12 | 17 | 11 | 20 | 60 |
def chi_square_test(table: np.ndarray) -> Tuple[float, float]:
r = table.shape[0]
p = table.shape[1]
dof = (r-1)*(p-1)
distribution = chi2(dof)
expected = np.zeros(table.shape)
for i in range(table.shape[0]):
for j in range(table.shape[1]):
expected[i, j] = (table[i,:].sum()*table[:,j].sum())/table.sum()
X2 = (((table - expected)**2)/expected).sum()
p = 1-distribution.cdf(X2)
return(X2, p)Test statistic: \(X^2 = \sum_{i=1}^r \sum_{j=1}^p \frac{(n_{ij}-e_{ij})^2}{e_{ij}} = 3.13\)
\(r = 2, p = 4 \rightarrow\) under \(H_0\), \(X^2 \sim \chi_3^2\).
p-value \(= 0.37 \rightarrow\) we cannot reject \(H_0\) and the two variables are likely to be independent.
X2, pval, dof, ef = chi2_contingency(table)
Test statistic: \(X^2 = \sum_{i=1}^r \sum_{j=1}^p \frac{(n_{ij}-e_{ij})^2}{e_{ij}} = 3.13\)
\(r = 2, p = 4 \rightarrow\) under \(H_0\), \(X^2 \sim \chi_3^2\).
p-value \(= 0.37 \rightarrow\) we cannot reject \(H_0\) and the two variables are likely to be independent.

\(\chi^2\) goodness-of-fit test: one sample, univariate, test if a categorical variable follows a particular distribution.
\(H_0\): observed sample comes from assumed distribution (e.g.: equal proportions).
Test statistic: \(X^2 = \sum_{i=1}^r \frac{(n_{i}-e_{i})^2}{e_{i}}\) where \(e_{i}\) is the expected number for category \(i\) under \(H_0\).
Under \(H_0\), \(X^2 \sim \chi^2_{(r-1)}\).
P-value: \(P(\chi_{(r-1)}^2 \geq X^2)\). Reject \(H_0\) if \(< \alpha\).
\(\chi^2\) independence test: one sample, bivariate, test if two categorical variables are independent.
\(H_0\): the two variables are independent.
Test statistic: \(X^2 = \sum_{i=1}^r \sum_{j=1}^p \frac{(n_{ij}-e_{ij})^2}{e_{ij}}\)
Under \(H_0\), \(X^2 \sim \chi^2_{(r-1)(p-1)}\)
P-value: \(P(\chi_{(r-1)(p-1)}^2 \geq X^2)\). Reject \(H_0\) if \(< \alpha\).
You just developed a new VR assistance tool for heart surgery. To test the device, 40 surgeries are performed with the tool and 40 without the tool. Each surgery can either be a success or a failure. You should…
Using goodness-of-fit test assumes that the “without tool” distribution is actually known, while the independence test takes into account the fact that is is also randomly sampled. So a table like
| Failure | Success | |
|---|---|---|
| NoTool | 16 | 24 |
| Tool | 8 | 32 |
Will lead to a significant (p=0.01) goodness-of-fit test (using NoTool as the expected frequency), whereas the independence test will not be significant (p=0.09).

Paired samples
Example: mean of the differences \(\rightarrow H_0: Mean[X_{a}-X_{b}] = 0\).

Independent samples
Example: difference between means \(\rightarrow H_0: m_1 = m_2\).

Previously:
One-sample Student’s t-test: tests if the mean of the sample differs from an assumed value (\(H_0: Mean[X] = \mu_0\), \(t = \frac{\bar{x}-\mu_0}{s/\sqrt{n}} \sim t_{n-1}\))
Paired Student’s t-test: tests if the mean of the differences between paired samples differs from 0 (\(H_0: Mean[X_1-X_0] = 0\), \(t = \frac{\bar{x_1-x_0}{s/\sqrt{n}}} \sim t_{n-1}\))
How do we extend to unpaired data ?
Unpaired Student’s t-test:
Example: we measure the maximum flexion angle of the knee for 10 patients with prosthesis A, and for 10 other patients with prosthesis B. Is there a significant difference between the two samples ?
A = [150, 116, 118, 109, 138, 91, 152, 114, 130, 122]
B = [108, 140, 152, 131, 149, 142, 138, 118, 132, 138]
Example: we measure the maximum flexion angle of the knee for 10 patients with prosthesis A, and for 10 other patients with prosthesis B. Is there a significant difference between the two samples ?
\(T_{obs} = \frac{\bar{x_a}-\bar{x_b}}{s\sqrt{\frac{1}{n_a}+\frac{1}{n_b}}} = -1.55\)
\(pval = 0.138 \rightarrow\) we can’t reject \(H_0\), so there is no statistically significant difference between the two samples.

Comparison of two independent empirical distributions.
Principle:

We are exploring the question: do patients with a background in high-level sports react differently to a surgical procedure than patients without such background ?
We measure for each patient, before and after surgery, a numerical fitness parameter (eg range of motion). We have a table of data that looks like this:
| Patient | Sport | Before | After |
|---|---|---|---|
| 1 | YES | 128.3 | 141.2 |
| … | … | … | … |
| 35 | NO | 124.5 | 137.5 |
How can we answer the question using statistical tests ?
Interesting questions:
We have 2 independent samples with a numerical variable. What do we need to check to determine the test ?
We could start by checking if there is an effect for the treatment in each group separately: in that case, we are looking at paired samples (same patients Before and After), and we can use either the paired Student’s t test (if normality) or the Wilcoxon signed rank test (if symmetrical distributions) or the sign test (non-symmetrical, non-normal).
If in both groups we have an effect, we can compare the effects by treating “After - Before” as a new variable: we then fall back to the independent numerical variable case.
(Note: in all cases, we should set in advance a desired significance level for our tests.)
Let’s do it on fake data (see sport.csv on the Virtual
University). We will use \(\alpha =
0.05\) as a desired significance level in all tests. First, some
descriptive statistics:
| SPORT-Before | SPORT-After | NOSPORT-Before | NOSPORT-After | |
|---|---|---|---|---|
| n | 16 | 16 | 19 | 19 |
| mean | 126.5 | 131.4 | 115.6 | 135.9 |
| std | 3.2 | 9.6 | 5.6 | 13.4 |

Normal distributions ? Shapiro-Wilk \(\rightarrow H_0: X \sim N\)
| SPORT | NOSPORT | |
|---|---|---|
| BEFORE | 0.001 | 0.117 |
| AFTER | 0.080 | 0.031 |

\(\rightarrow\) some of the samples are unlikely to come from a normal distribution (using a typical 0.05 significance level threshold).
\(\rightarrow\) we will need to use nonparametric tests.
Comparison between the groups
Before surgery: are the two groups significantly different ? \(\rightarrow\) nonparametric test for difference between independent numerical variables \(\rightarrow\) Mann-Whitney U test (\(H_0\): equal medians, two-sided \(\rightarrow H_1\): unequal variance).
Mann-Whitney p-value = 0.000 \(\rightarrow\) significant difference
between the sport and no-sport groups before the surgery.
After surgery: idem.
Mann-Whitney p-value = 0.882 \(\rightarrow\) no significant difference
between the sport and no-sport groups after the surgery.
Effects of surgery

Symmetrical distributions ? Not really \(\rightarrow\) sign test for the effect of surgery (i.e. difference between “after” and “before” in each group separately).
We can use a one-sided test, as we want to see if the parameters after surgery are better than before.
Sports group: Sign test p-value = 0.011
No-sports group: Sign test p-value = 0.000
\(\rightarrow\) there is a significant (positive) effect of surgery in both groups.
Effects of surgery: different between the groups ?
New variables: sports-effect = sports-after - sports-before, nosports-effect = nosports-after - nosports-before.
Normality check ? \(\rightarrow H_0\) cannot be rejected. Assume normality.


Comparing 2 independent samples, numerical variables, with parametric tests: variance test necessary !
Levene test of variance p-value: 0.425 \(\rightarrow\) assume equal variances \(\rightarrow\) independent
t-test.

t-test p-value = 0.001
\(\rightarrow\) there is a significant difference in the effect of the surgery depending on the group.
What can we conclude from the study ?

Very often, we have more than two groups or conditions.
Examples:
Obvious option: do one-to-one comparisons, using the 2 samples test !
Obvious option: do one-to-one comparisons, using the 2 samples test !
Why can’t we do that ? Let’s remember the meaning of the p-value.
P-value = under \(H_0\), probability that sampled results are as “extreme” as the observed results.
If we have \(k\) groups, we have \(k(k-1)/2\) different one-to-one comparisons. If \(H_0\) is true, then the probability that at least one result is “extreme” is much higher !
If each one-to-one comparison is assumed independent, then P(at least one p-value < \(\alpha\)) = \(1-(1-\alpha)^{k(k-1)/2}\)
def one_to_one_comparisons(n_groups: int, alpha: float, sample_size: int = 50, n_repetitions: int = 10_000):
has_significant_result = 0
for _ in range(n_repetitions):
groups = [norm.rvs(0, 1, size=sample_size) for _ in range(n_groups)]
pvals = []
for a, b in combinations(groups, 2):
res = ttest_ind_from_stats(np.mean(a), np.std(a), len(a),
np.mean(b), np.std(b), len(b))
pvals.append(res.pvalue)
if min(pvals) < alpha:
has_significant_result += 1
return has_significant_result/n_repetitionsp = one_to_one_comparisons(5, 0.05)
\(\rightarrow\)
P(at least one significant result) = 0.29 (theory: 0.4)
p = one_to_one_comparisons(10, 0.05)
\(\rightarrow\)
P(at least one significant result) = 0.65 (theory: 0.9)
(\(\neq 1-(1-\alpha)^{k(k-1)/2}\) because comparisons are not independent)
Two main possibilities:
Simplest: Bonferroni correction
\(\rightarrow\) if testing \(m\) hypotheses at significance level \(\alpha=0.05\), test each individual hypothesis at significance level \(\alpha' = 0.05/m\).
This is a very conservative method, with a high likelihood of not rejecting \(H_0\) in cases where it is actually false (Type II error).
def one_to_one_comparisons(n_groups: int, alpha: float, sample_size: int = 50, n_repetitions: int = 10_000):
has_significant_result = 0
for _ in range(n_repetitions):
groups = [norm.rvs(0, 1, size=sample_size) for _ in range(n_groups)]
pvals = []
for a, b in combinations(groups, 2):
res = ttest_ind_from_stats(np.mean(a), np.std(a), len(a),
np.mean(b), np.std(b), len(b))
pvals.append(res.pvalue)
if min(pvals) < alpha:
has_significant_result += 1
return has_significant_result/n_repetitionsp = one_to_one_comparisons(5, 0.05/(5*4*0.5))
\(\rightarrow\)
P(at least one significant result) = 0.04 (theory: 0.05)
p = one_to_one_comparisons(10, 0.05/(10*9*0.5))
\(\rightarrow\)
P(at least one significant result) = 0.03 (theory: 0.05)
Simplest: Bonferroni correction
\(\rightarrow\) if testing \(m\) hypotheses at significance level \(\alpha=0.05\), test each individual hypothesis at significance level \(\alpha' = 0.05/m\).
Example: in ten hospitals, we measure the level of satisfaction (measured on a 10 point scale) of the patients, and we want to test if some hospitals are more highly rated than others, using \(\alpha = 0.05\) as our significance level threshold.
Example: in ten hospitals, we measure the level of satisfaction (measured on a 10 point scale) of the patients, and we want to test if some hospitals are more highly rated than others, using \(\alpha = 0.05\) as our significance level threshold.
Independent (unpaired) samples, ordinal variable \(\rightarrow\) Mann-Whitney U test.
10 hospitals \(\rightarrow\) \(\frac{10 \times 9}{2} = 45\) tests.
\(\Rightarrow\) use \(\alpha' = \frac{\alpha}{45} = 0.00111...\) for each individual test.
N-sample versions of 2-sample tests for Categorical variables
| N=2 | N>2 | |
|---|---|---|
| Independent | \(\chi^2\) independence | \(\chi^2\) independence |
| Paired | ||
| Ordinal | Sign test, Wilcoxon signed-rank | Friedman |
| Binary | McNemar | Cochran’s Q test |
N-sample versions of 2-sample tests for Numerical variables
| N=2 | N>2 | |
|---|---|---|
| Independent | ||
| Parametric | Independent t-test, Welch test | ANOVA |
| Non-parametric | Mann-Whitney | Kruskal-Wallis |
| Paired | ||
| Parametric | Paired t-test | ANOVA |
| Non-Parametric | Sign test, Wilcoxon signed-rank | Friedman |
ANOVA = “Analysis of variance”: generalisation of the t-test to N samples.
Application conditions:
Versions for…
Given \(k\) samples of sizes \(n_1\), …, \(n_i\), …, \(n_k\).
Let \(x_{ij}\) be the \(j^{th}\) value of the numerical variable \(X\) in the \(i^{th}\) group.
We have:
\(H_0\): all groups have the same mean. \(H_1\): at least 2 groups have different means.
\(H_0\): all groups have the same mean. \(H_1\): at least 2 groups have different means.
General intuition: if there is no difference between the means, then the total variance of \(X\) will only come from the within-group variance, not from the between-groups variance.


\(H_0\): all groups have the same mean. \(H_1\): at least 2 groups have different means.
Step 1: compute the variance within each group.
\(s_i^2 = \frac{1}{n_i-1}\sum_{j=1}^{n_i}(x_{ij}-\bar{x_i})^2\)
Step 2: sum for all groups \(\rightarrow\) “Mean Square” within (\(MS_w\))
\(MS_w = \frac{1}{k}\sum_{i=1}^{k}s_i^2 = \sum_{i=1}^{k}\sum_{j=1}^{n_i}\frac{(x_{ij}-\bar{x_i})^2}{k(n_i-1)}\)
Step 1: compute the variance within each group.
\(s_i^2 = \frac{1}{n_i-1}\sum_{j=1}^{n_i}(x_{ij}-\bar{x_i})^2\)
Step 2: sum for all groups \(\rightarrow\) “Mean Square” within (\(MS_w\))
\(MS_w = \frac{1}{k}\sum_{i=1}^{k}s_i^2 = \sum_{i=1}^{k}\sum_{j=1}^{n_i}\frac{(x_{ij}-\bar{x_i})^2}{k(n_i-1)}\)
Step 3: compute the variance between groups \(\rightarrow\) “Mean Square” between (\(MS_b\))
\(MS_b = \frac{1}{k-1}\sum_{i=1}^{k}n_i(\bar{x_i}-\bar{\bar{x}})^2\)
Step 4: compute F-statistic
\(F = \frac{MS_b}{MS_w}\)
Step 4: compute F-statistic
\(F = \frac{MS_b}{MS_w}\)
Under \(H_0\), \(F \sim F_{(k-1), (N-k)}\) where \(F\) is Snedecor-Fisher’s distribution (cf Module 2).
We can therefore reject \(H_0\) with confidence level \(1-\alpha\) if \(F_{obs} > F_{k-1,N-k,1-\alpha}\).

F values for 10 000 simulations (5 groups), with theoretical Snedecor distribution.
If a multi-samples test (ANOVA, Friedman, Kruskal-Wallis) is significant, it means that at least one sample is different from the others…
…but we would still like to know which one !
\(\rightarrow\) post hoc analysis refers to procedures done after the main test, to provide the one-by-one comparisons that we generally want.
The post hoc cannot be used as a substitute for the multi-sample test. A significant one-by-one comparison in the post hoc is only significant if the multi-group test was.
(see Thematic notes for more details)

Alternative to the distribution-based CI and Hypothesis tests: bootstrapping.
General idea: from a sample \(x\) of size \(n\), generate \(m\) samples \(x^*_{(i)}\) of size \(n\) by resampling with replacements. Compute the estimator that you’re interested in on each bootstrap sample to get its distribution. Use this distribution to estimate the confidence interval.
Let \(\hat{\theta}\) be the estimator for a parameter of interest. \(\hat{\theta}_s = \hat{\theta}(x)\) is the estimated value on the sample, for which we want to find a confidence interval, and \(\hat{\theta}^*_{(i)} = \hat{\theta}(x^*_{(i)})\) is the estimated value on the \(i\)-th bootstrapped sample.
Example with \(\hat{\theta} = Mean\), \(n=6\):
| Sample | Estimator |
|---|---|
| \(x = [0, -10, 20, 20, 15, 10]\) | \(\hat{\theta}_s = 9.17\) |
| \(x^*_{(1)} = [0, 0, 15, 20, 20, 0]\) | \(\hat{\theta}^*_{(1)} = 9.17\) |
| \(x^*_{(2)} = [10, 0, 20, 20, 10, 0]\) | \(\hat{\theta}^*_{(2)} = 10.0\) |
| \(x^*_{(3)} = [-10, 0, 20, 15, 20, 20]\) | \(\hat{\theta}^*_{(3)} = 10.83\) |
| … | … |
With a large amount of bootstrapped samples, we can then look at the distribution of \(\hat{\theta}^*_{(i)}\). More specifically, if we want a confidence interval at level \(1-\alpha\), we want to look at the \(\alpha/2\) and \(1-\alpha/2\) percentiles of this distribution. We will call them \(L = \hat{\theta}^*_{\alpha/2}\) and \(U = \hat{\theta}^*_{1-\alpha/2}\)
Percentile bootstrap
Easiest way to estimate the confidence interval: just take \(CI = [L, U]\).
Reverse Percentile Interval
\(CI = [2\hat{\theta}_s-U, 2\hat{\theta}_s-L]\)

\(x = [0, -10, 20, 20, 15, 10] \rightarrow \bar{x} = 9.17\)
CI (Student): \(CI = [\bar{x} \pm t_{5,
0.025} \frac{s}{\sqrt{5}}] = [-2.3, 20.7]\)
CI (Percentile): \(CI = [0,
17.5]\)
CI (RPI): \(CI = [0.8, 18.3]\)
def bootstrap_ci_estimator(sample: np.ndarray,
estimator: Callable[[np.ndarray], float],
alpha: float = 0.05,
n_bootstraps: int = 10_000,
method: BOOTSTRAP_METHOD = BOOTSTRAP_METHOD.RPI) -> Tuple[float, float]:
es = []
k = len(sample)
for _ in range(n_bootstraps):
es.append(estimator(np.random.choice(sample, k)))
es.sort()
cmin = n_bootstraps*(alpha/2)
cmax = n_bootstraps*(1-alpha/2)
if method == BOOTSTRAP_METHOD.RPI:
e_sample = estimator(sample)
return (2*e_sample-es[int(cmax)], 2*e_sample-es[int(cmin)])
else:
return (es[int(cmin)], es[int(cmax)])Let’s try it by comparing, for different sample sizes, the theoretical CI (computed based on the \(\chi^2\) distribution for the variance and on the Student t distribution for the mean) with the bootstrapped CI.
Methodology: take one random sample of size 200 from a \(N(65, 7^2)\) distribution. Then, for increasing sample sizes \(n\), take the \(n\) first items from the random sample. Compute CI using theory, percentile & RPI methods.


Big advantages of bootstrapping:
Main disadvantages:
\(\rightarrow\) if the assumptions of the theoretical approaches are reasonable, they are safer to use.
Bootstrap approach recommended when the distribution of the target statistic is complicated or unknown. Can also be used as a quick way of getting a rough estimation if precise values are not needed.
What if we want to look at more than two variables at the same time ? \(\rightarrow\) multivariate data analysis.
Table of data with \(n\) individuals and \(p\) numerical variables.
| Individual | \(X_1\) | … | \(X_j\) | … | \(X_p\) |
|---|---|---|---|---|---|
| 1 | \(x_{11}\) | … | \(x_{1j}\) | … | \(x_{1p}\) |
| … | … | … | … | … | … |
| i | \(x_{i1}\) | … | \(x_{ij}\) | … | \(x_{ip}\) |
| … | … | … | … | … | … |
| n | \(x_{n1}\) | … | \(x_{nj}\) | … | \(x_{np}\) |
| Individual | \(X_1\) | … | \(X_j\) | … | \(X_p\) |
|---|---|---|---|---|---|
| … | … | … | … | … | … |
| i | \(x_{i1}\) | … | \(x_{ij}\) | … | \(x_{ip}\) |
| … | … | … | … | … | … |
Line vector \(x_{i.}\) represents one individual in a p-dimensional space \(\rightarrow\) “variable space” or “feature space”.
All rows together form a point cloud showing the distribution of individuals in feature space.

| Individual | … | \(X_j\) | … |
|---|---|---|---|
| 1 | … | \(x_{1j}\) | … |
| … | … | … | … |
| i | … | \(x_{ij}\) | … |
| … | … | … | … |
| n | … | \(x_{nj}\) | … |
Column vector \(x_{.j}\) represents one feature in a n-dimensional space \(\rightarrow\) “individual space”.
All columns together form a point cloud showing the distribution of features in individual space.


Points that are very close together are individuals that share common features.

Points that are very close together are features that tend to have similar values across all individuals.
Quick quizz: what would be an example case where feature space is high-dimensional and individual space is low-dimensional ?
\(\mathbf{g} = \bar{\mathbf{x}} = \begin{bmatrix} \bar{x_1} \\ ... \\ \bar{x_j} \\ ... \\ \bar{x_p} \end{bmatrix}\)

Variance-Covariance matrix
\(S_{p \times p} = \begin{bmatrix} s_{11} & ... & s_{1j} & ... & s_{1p} \\ ... & ... & ... & ... & ... \\ s_{j1} & ... & s_{jj} & ... & s_{jp} \\ ... & ... & ... & ... & ... \\ s_{p1} & ... & s_{pj} & ... & s_{pp} \end{bmatrix}\)
With \(s_{jj} = s_j^2, s_{jk} = s_{kj} = cov(X_j, X_k)\)
Correlation matrix
\(R_{p \times p} = \begin{bmatrix} 1 & ... & r_{1j} & ... & r_{1p} \\ ... & ... & ... & ... & ... \\ r_{j1} & ... & 1 & ... & r_{jp} \\ ... & ... & ... & ... & ... \\ r_{p1} & ... & r_{pj} & ... & 1 \end{bmatrix}\)
With \(r_{jk} = r_{kj} = \frac{s_{jk}}{s_js_k}\)
\(\rightarrow\) Correlation and Covariance matrices are symmetrical.
They give us a quick overview of which variable have a relationship. In high-dimensional spaces, may be better represented as a heatmap to make the relationships more visible.
6 numerical variables (= blood sample measures)
Variable s1 and s2


6 numerical variables (= blood sample measures)
Variable s1 and s3


Measure of distance in feature space = how similar are two individuals (according to their features).
Problem: assumes equal contributions from all dimensions. But different variables may have different scales.
Example: in diabetes dataset, we have for variable \(s_1 \rightarrow \bar{s_1} = 189.1\) and \(Var[s_1] = 1195.0\), and for variable \(s_5 \rightarrow \bar{s_5} = 4.64\) and \(Var[s_5] = 0.27\). The contribution of \(s_5\) to the euclidean distance between two individuals will be negligible.
Possible solutions:
More general: rotation and normalisation of the point cloud to also take correlations into account. Goal: transform the point cloud into a spherical shape, so that the euclidean distance can be used.
\(\rightarrow\) see PCA in next module.
Multivariate data analysis \(\rightarrow\) find the underlying structure of the data in feature space.
Looking only at numerical “input” (i.e. not dependent) variables \(\rightarrow\) unsupervised methods (module 4), e.g. clustering. Goal is to identify natural groups, i.e. individuals that are strongly associated, or outliers, i.e. individuals that are very different from all others.
What if we have a dependent (“output”) variable ?

If categorical (or treated as such through thresholding / binning), we can use it to split the dataset into different groups.
We can…
If the dependent variable is numerical \(\rightarrow\) regression task.
\(\rightarrow\) supervised methods (module 5).