Statistical Experiments & A/B Testing Guide
Statistical Experiments & A/B Testing Guide
MODULE-3
Statistical Experiments and Significance Testing
INTRODUCTION
In statistics, our main aim is not just to describe data, but to make inferences – that is, to
draw conclusions about a larger population from a smaller sample of data.
To make such conclusions, researchers design statistical experiments. These experiments are
structured in such a way that they can test whether observed outcomes are due to real effects
(like a new drug working better) or whether they happened simply by random chance.
Once an experiment is conducted, we need tools to interpret the results. This is where
significance testing (also called hypothesis testing) comes in. It is a systematic way of deciding
whether an observed effect is likely real or could be explained by randomness.
Example 1: In a clinical trial, patients (subjects) are given two different drugs (treatments), and
their blood pressure reduction is measured (outcome).
Example 2: In e-commerce, website visitors (subjects) are shown two versions of a webpage
(treatments A and B), and the purchase decision (outcome: buy or not buy) is recorded.
To test a hypothesis: for example, "Drug A works better than Drug B".
To compare treatments: Is price A better than price B in terms of sales?
To establish causality: If differences are found, can we confidently say they are caused
by the treatment, not by other external factors?
To control variability: By randomization and design, we minimize the effect of
confounding variables (other influences).
Even when we observe differences between groups, random chance can create apparent
differences. For example:
If we flip a fair coin 10 times, we might get 7 heads and 3 tails. Does that mean the coin
is biased? Not necessarily — such results can occur by chance.
Similarly, if Group A (Drug A) shows better recovery than Group B (Drug B), is it due to
the drug or just random variability?
1. Formulate a hypothesis
o Example: "Price A is better than Price B."
2. Design the experiment
o Randomly assign subjects to treatment and control groups.
3. Collect the data
o Record observed outcomes (conversions, recovery, clicks, etc.).
4. Analyze the data
o Use appropriate statistical tests (t-test, chi-square, resampling, etc.).
5. Draw conclusions
o Decide whether the results are statistically significant and interpret them in real-
world context.
Randomization: Randomly assigning subjects ensures that the groups are comparable
and results are not biased.
Control group: Acts as a baseline. Without it, we cannot say for sure whether the
observed change is due to treatment or external factors.
📌 Example: If we only try a new drug on one group and compare it to past records, many other
factors (environment, diet, patient demographics) might differ. Randomized control avoids this
issue.
A/B TESTING
A/B testing is one of the most widely used types of statistical experiments, especially in
business, marketing, medicine, and web analytics. The basic idea is simple: we compare
two groups (A and B) to determine which of two treatments, options, or strategies works
better.
Group A (Control): This group receives the standard treatment, the existing version, or
no treatment at all.
Group B (Treatment): This group receives the new option or the experimental treatment
being tested.
The goal of A/B testing is to measure whether there is a significant difference in outcomes
between the two groups, and if so, to decide which option should be chosen going forward.
A/B tests are common in web design and marketing, since results are so readily measured. Some
examples of A/B testing include:
Testing two soil treatments to determine which produces better seed germination
Testing two therapies to determine which suppresses cancer more effectively
Testing two prices to determine which yields more net profit
Testing two web headlines to determine which produces more clicks (Figure 3-2)
Testing two web ads to determine which generates more conversions
A proper A/B test has subjects that can be assigned to one treatment or another. The subject
might be a person, a plant seed, a web visitor; the key is that the subject is exposed to the
treatment. Ideally, subjects are randomized (assigned randomly) to treatments. In this way, you
know that any difference between the treatment groups is due to one of two things:
• The effect of the different treatments
• Luck of the draw in which subjects are assigned to which treatments (i.e., the random
assignment may have resulted in the naturally better-performing subjects being concentrated in
A or B)
You also need to pay attention to the test statistic or metric you use to compare group A to group
B. Perhaps the most common metric in data science is a binary variable: click or no-click, buy or
don’t buy, fraud or no fraud, and so on. Those results would be summed up in a 2×2 table. Table
3-1 is a 2×2 table for an actual price test.
If the metric is a continuous variable (purchase amount, profit, etc.) or a count (e.g., days in
hospital, pages visited), the result might be displayed differently. If one were interested not in
conversion but in revenue per page view, the results of the price test in Table 3-1 might look like
this in typical default software output:
Department of AI & DS, NCE, Hassan Page 5
Statistical Machine Learning for Data Science (BAD702)
Randomization ensures that differences between groups are caused by the treatment itself and
not by other hidden factors.
Example:
If younger patients are placed in Group A and older patients in Group B, the observed
difference may be due to age, not treatment.
Randomization distributes such variables evenly, making the comparison fair and
unbiased.
Without a control group, you might mistakenly conclude that a treatment works when the
change is due to external conditions.
Example:
o Imagine a company launches a new website design and sees a sales increase.
o But what if the increase happened because it was holiday season, not because of
the design?
A control group exposed to the old design at the same time would account for seasonal
effects, allowing a fair comparison.
Example: If patients know they are receiving the new drug, they may feel better simply because
of expectations (placebo effect).
Example: In a website test, if the primary goal is sales, then conversion rate should be the
metric. Looking at multiple metrics after the test (like clicks, time, engagement) may lead to
biased conclusions.
Limitations:
A/B testing is a fundamental experimental design technique that helps us make decisions
based on data rather than guesswork. By comparing a control group (A) with a treatment group
(B), and using proper randomization and statistical testing, we can determine whether observed
differences are real or just due to chance. It is the foundation of modern data-driven decision
making in both scientific research and business applications.
HYPOTHESIS TESTING
Hypothesis tests, also called significance tests, are ubiquitous in the traditional statistical analysis
of published research. Their purpose is to help you learn whether random chance might be
responsible for an observed effect.
At first glance, it seems logical to just pick the treatment that performs better in the test. But
there are two major problems with this approach:
Sometimes rare, extreme events occur — events that seem impossible but are part of
natural randomness.
Example: A startup runs an A/B test on 100 customers, and one customer buys a huge
order that skews results in favor of one version.
Without hypothesis testing, one might incorrectly conclude that the new version is
superior.
Hypothesis testing was invented to protect us from these traps — it forces us to measure how
compatible our results are with pure chance.
If such results are very unlikely under chance alone → we reject the null hypothesis and
accept the alternative.
If the results are consistent with chance → we avoid making false claims.
In short:
Practical Example
Imagine two webpage designs tested on 1000 visitors each:
At first glance, Version B looks better. But is that 0.5% difference real, or just luck of the
draw?
If we run a hypothesis test and the p-value = 0.42, then such a difference (or larger)
would occur 42% of the time due to chance.
Conclusion: This difference is not statistically significant — we should not switch
designs based on this result.
Humans tend to interpret random or unusual events as meaningful patterns. Therefore, to guard
against false conclusions, statistical tests demand strong evidence before rejecting the
assumption of “no real effect.”
Any observed difference between groups (e.g., Group A vs. Group B) is initially
assumed to be caused by random variation or chance.
Only when the observed difference is too extreme to be reasonably attributed to
chance do we reject the null hypothesis.
Definition:
The null hypothesis (H₀) states that there is no significant difference between two or more
groups, conditions, or populations being compared. This involves a baseline assumption that the
treatments are equivalent, and any difference between the groups is due to chance. This baseline
assumption is termed the null hypothesis.
Formally, it can be expressed as:
Examples:
Thus, the null hypothesis assumes equivalence between treatments, interventions, or groups.
The null hypothesis provides the starting point or reference model for testing.
It assumes no real effect of treatments or variables, implying that observed differences
are due purely to random sampling error.
Researchers collect sample data and use statistical tests (e.g., t-test, ANOVA, chi-square
test) to evaluate whether the evidence is strong enough to reject this assumption.
Alternative Hypothesis
Hypothesis tests by their nature involve not just a null hypothesis but also an offsetting
alternative hypothesis. Here are some examples:
Null = “no difference between the means of group A and group B”;
alternative =“A is different from B” (could be bigger or smaller)
Null = “A ≤ B”; alternative = “A > B”
Null = “B is not X% greater than A”; alternative = “B is X% greater than A”
Taken together, the null and alternative hypotheses must account for all possibilities. The nature
of the null hypothesis determines the structure of the hypothesis test.
The alternative hypothesis (H₁ or Ha) represents what the researcher aims to prove — that
there is a real difference or effect.
A one-tailed test is used when the research question is directional, i.e., we only care about
whether B is better (or worse) than A, not both.
Key Characteristics:
Scenario: You will switch to the new design (B) only if it performs better than A.
Hypotheses:
Interpretation:
Only the upper tail (right side) of the sampling distribution is considered.
If the test statistic falls into this extreme region, H₀ is rejected, and B is accepted as
better.
Definition:
A two-tailed test is used when we are interested in any difference between A and B — whether
B is better or worse than A.
Key Characteristics:
Interpretation:
Summary
RESAMPLING
Resampling in statistics means to repeatedly sample values from observed data, with a general
goal of assessing random variability in a statistic. It can also be used to assess and improve the
accuracy of some machine-learning models.
There are two main types of resampling procedures: the bootstrap and permutation tests. The
bootstrap is used to assess the reliability of an estimate (discussed in previous Module-2).
Permutation tests are used to test hypotheses, typically involving two or more groups.
Permutation Test
A Permutation Test (also known as a Randomization Test or Exact Test) is a non-
parametric statistical method used to test hypotheses about differences between two or more
groups. It is often applied in A/B testing, experimental design, or comparative studies where
we want to determine if observed differences between groups are statistically significant or
merely due to random chance.
The term “permute” means to rearrange or change the order of data values.
In a permutation test, data from all groups (e.g., A and B) are combined and shuffled to
simulate the situation under the null hypothesis (H₀) — that there is no real difference
between the groups.
The test then measures how likely the observed difference between groups could occur
purely by random reallocation of the data.
The treatments or conditions applied to different groups (A, B, C, etc.) do not have any real
effect — any observed differences are due to random variation.
Therefore:
1. Combine the results from the different groups into a single data set.
2. Shuffle the combined data and then randomly draw (without replacement) a resample of the
same size as group A (clearly it will contain some data from the other groups).
3. From the remaining data, randomly draw (without replacement) a resample of the same size as
group B.
4. Do the same for groups C, D, and so on. You have now collected one set of resamples that
mirror the sizes of the original samples.
5. Whatever statistic or estimate was calculated for the original samples (e.g., difference in group
proportions), calculate it now for the resamples, and record; this constitutes one permutation
iteration.
6. Repeat the previous steps R times to yield a permutation distribution of the test statistic.
Compare the observed statistic (from the actual, unshuffled data) to the permutation
distribution.
The p-value is estimated as the proportion of permutation results that are as extreme
or more extreme than the observed value.
If this p-value is small (e.g., < 0.05), we reject the null hypothesis, concluding that the
observed difference is unlikely to be due to chance alone.
1. Non-parametric method: It does not rely on assumptions about the data’s underlying
distribution (e.g., normality). This makes it suitable for datasets that violate parametric
test assumptions.
2. Applicable to small samples: The test can provide exact significance levels for small
datasets because all possible rearrangements can be computed.
3. High flexibility: The permutation framework can be applied to a wide range of statistics
— such as means, medians, correlations, or regression coefficients.
4. Conceptually intuitive: The logic of reshuffling data to simulate the null hypothesis is
easy to understand and directly tied to the data itself.
5. Robustness: Because it depends only on the observed data and random rearrangements,
it remains reliable even when data contain outliers or are not normally distributed.
6. No reliance on asymptotic theory: The test works accurately even for small sample
sizes without needing large-sample approximations.
Violating this condition (e.g., in time-series or dependent data) can lead to incorrect
results.
4. Limited interpretability for complex models: When applied to regression or
multivariate models, the interpretation of permuted results can become more complicated.
5. Not ideal for extremely large data: While modern computing power helps, the method
may still be impractical for very large datasets with millions of observations.
A company selling a relatively high-value service wants to test which of two web presentations
does a better selling job. Due to the high value of the service being sold, sales are infrequent and
the sales cycle is lengthy; it would take too long to accumulate enough sales to know which
presentation is superior. So the company decides to measure the results with a proxy variable,
using the detailed interior page that describes the service.
A proxy variable is a measurable variable that substitutes for a true variable of interest when the
latter is:
Hard to measure,
Time-consuming, or
Too costly to obtain.
In this experiment:
Longer session time implies higher engagement and possibly higher conversion likelihood.
One potential proxy variable for our company is the number of clicks on the detailed landing
page. A better one is how long people spend on the page. It is reasonable to think that a web
presentation (page) that holds people’s attention longer will lead to more sales. Hence, our metric
is average session time, comparing page A to page B. Google Analytics is used to measure
session time. Instead of deleting that session from the data, though, Google Analytics records it
as a zero, so the data requires additional processing to remove those sessions. The result is a total
of 36 sessions for the two different presentations, 21 for page A and 15 for page B. Using ggplot,
we can visually compare the session times using side-by-side boxplots:
R Code:
ggplot(session_times, aes(x=Page, y=Time)) + geom_boxplot()
Python Code:
ax = session_times.boxplot(by='Page', column='Time')
ax.set_xlabel('')
ax.set_ylabel('Time (in seconds)')
[Link]('')
Page B shows a higher median and overall longer session time than Page A, suggesting that Page
B may be more engaging.
R Code:
mean_a <- mean(session_times[session_times['Page'] == 'Page A', 'Time'])
mean_b <- mean(session_times[session_times['Page'] == 'Page B', 'Time'])
mean_b - mean_a
# [1] 35.66667
Python Code:
mean_a = session_times[session_times.Page == 'Page A'].[Link]()
mean_b = session_times[session_times.Page == 'Page B'].[Link]()
mean_b - mean_a
Result:
Page B’s sessions are 35.67 seconds longer on average.
Is this observed difference (35.67 seconds) statistically significant — i.e., could it have
occurred by random chance?
Python Code:
def perm_fun(x, nA, nB):
n = nA + nB
idx_B = set([Link](range(n), nB))
idx_A = set(range(n)) - idx_B
return [Link][idx_B].mean() - [Link][idx_A].mean()
Explanation:
This function works by sampling (without replacement) nB indices and assigning them to the B
group; the remaining nA indices are assigned to group A. The difference between the two means
is returned. Calling this function R = 1,000 times and specifying nA = 21 and nB = 15 leads to a
distribution of differences in the session times that can be plotted as a histogram. In R this is
done as follows using the hist function:
R Code:
perm_diffs <- rep(0, 1000)
for (i in 1:1000) {
perm_diffs[i] = perm_fun(session_times[, 'Time'], 21, 15)
}
hist(perm_diffs, xlab='Session time differences (in seconds)')
abline(v=mean_b - mean_a)
Python Code:
perm_diffs = [perm_fun(session_times.Time, nA, nB) for _ in range(1000)]
Figure 3-4 shows that mean difference of random permutations often exceeds the observed
difference in session times (the vertical line). For our results, this happens in 12.6% of the cases:
Compute p-Value
mean(perm_diffs > (mean_b - mean_a))
---
0.126
As the simulation uses random numbers, the percentage will vary. For example, in the Python
version, we got 12.1%:
[Link](perm_diffs > mean_b - mean_a)
---
0.121
This suggests that the observed difference in session time between page A and page B is well
within the range of chance variation and thus is not statistically significant.
Result:
p-value ≈ 0.12 (12%)
These variants differ mainly in how the resampling is done and the assumptions they model.
Key Characteristics
All combinations of group assignments are enumerated.
Provides an exact test because it includes every possible permutation.
Guarantees that, under the null hypothesis, the probability of falsely declaring
significance does not exceed the pre-defined alpha level (e.g., 0.05).
Sometimes called an Exact Test due to its statistical precision.
Practicality
Only feasible for small sample sizes because the number of possible permutations grows
factorially with sample size.
For example, if 10 observations are divided into two groups of 5, the number of unique
permutations is:
Approximation
For large datasets, a random permutation test (with many random shuffles) provides results
that closely approximate those of the exhaustive version.
Key Idea
The bootstrap models two sources of randomness:
1. Assignment randomness: how observations are assigned to groups (as in the
regular permutation test).
2. Sampling randomness: how the sample itself represents the underlying
population.
Process
Randomly resample (with replacement) from the combined dataset to form new groups A
and B.
Compute the test statistic for each resampled pair.
Repeat many times to build a bootstrap permutation distribution.
Advantages
Reflects both sampling variability and assignment variability.
Especially useful when the data represent only a subset of a larger population.
Limitations
The distinction between bootstrap and random permutation can become blurred.
In practical data science, the difference between the two approaches is usually not
critical.
Comparison Summary
Statistical significance refers to the method used by statisticians to determine whether the
results of an experiment (or data study) are too extreme to be explained by random chance
alone.
The p-value (probability value) quantifies this idea by measuring the probability of obtaining a
result as extreme as the observed one, assuming the null hypothesis is true.
Consider in Table 3-2 the results of the web test shown earlier.
Interpretation:
Price A’s conversion rate is 5% higher than Price B’s, which seems meaningful in a high-
volume business, where even small improvements can affect revenue significantly.
Thus:
The effective sample size is determined by the number of conversions, not total sessions.
Random chance could still produce apparent differences of similar size.
Therefore, it is still essential to test whether the observed difference is statistically
significant.
Steps:
OR
This frequency gives an empirical p-value — the probability of observing a difference this large
under the null hypothesis.
Explanation:
Explanation:
The histogram of 1,000 resampled results in Figure 3-5: as it happens, in this case the observed
difference of 0.0368% is well within the range of chance variation.
p-Value
In other words, it quantifies the strength of evidence against the null hypothesis.
A small p-value (typically < 0.05) indicates that the observed result is unlikely to have
occurred by random chance, suggesting statistical significance.
A large p-value indicates that the observed difference could easily occur by chance,
meaning there is no strong evidence against H₀.
The p-value is the area in the tails of the distribution beyond the observed statistic.
It measures how “rare” the observed value is, given random variation.
|-------------------|-------------------|
low p-value → observed result far in tail
high p-value → observed result near center
The goal is to determine whether this observed difference is statistically significant or could
simply result from random chance.
Since we already conducted a permutation test (randomly shuffling data 1,000 times under the
null hypothesis), we can use it to calculate the empirical p-value.
R Code
mean(perm_diffs > obs_pct_diff)
# [1] 0.308
Python Code
[Link]([diff > obs_pct_diff for diff in perm_diffs])
# 0.308
Explanation
Thus,
Result
Interpretation
If there were truly no difference in conversion rates between the two prices,
we would still observe a difference as large (or larger) than 0.0368 percentage points
about 31% of the time due to random chance.
Conclusion:
Since p = 0.308 > 0.05, the result is not statistically significant. There is no strong evidence
that Price A converts better than Price B — the difference could be due to random variation.
Output:
Explanation
The resulting p-value = 0.3498, very close to the permutation test p-value (0.308).
Explanation
The result gives a p-value ≈ 0.35, again similar to the other methods.
Comparison of Results
All three methods consistently show high p-values (> 0.05), confirming that the observed
difference in conversion rates is not statistically significant.
In this example, p = 0.308 clearly falls into the “no evidence against H₀” range.
Alpha
Definition
In statistical hypothesis testing, alpha (α) — also called the significance level — is the
predefined threshold used to decide whether a result is considered statistically significant.
It represents the probability of rejecting the null hypothesis (H₀) when it is actually true — that
is, the risk of a Type I error (false positive).
These thresholds are arbitrary choices, not mathematical certainties. They simply represent how
much risk we are willing to accept in declaring a difference “significant” when it might have
occurred by chance.
Interpretation
We are willing to accept a 5% probability of incorrectly rejecting the null hypothesis — that is,
finding a statistically significant difference even if no real difference exists.
This means that, under the null hypothesis, only 5% of results would be as extreme (or more
extreme) than the observed result.
Important Clarification
A common misunderstanding arises because people assume α (and p-values) answer the
question:
“Given a chance model (the null hypothesis), what is the probability of obtaining a result this
extreme?”
Thus, we are evaluating how incompatible the data are with the null hypothesis model, not
assigning a probability that the null is true or false.
a. The Problem
Many researchers and journal editors have over-relied on p-values to determine the validity of
scientific findings.
As a result:
Studies with “significant” p-values (< 0.05) are more likely to be published.
Researchers often search through multiple hypotheses or tweak their analyses until
they find a p-value below 0.05 — a practice known as “p-hacking.”
This has contributed to false discoveries, irreproducible results, and a crisis in scientific
credibility, especially in psychology and biomedical research.
b. Misinterpretation of p-Values
They hope that a low p-value proves that the result is real and not random.
“The probability of observing results as extreme as, or more extreme than, the actual results if
the null hypothesis is true.”
This distinction is subtle but crucial. A low p-value indicates that the data are unlikely under the
null model, but it does not prove that the null hypothesis is false, nor does it indicate the
probability that the alternative hypothesis is true.
c. Real-World Reactions
In 2015, a major psychology journal banned the use of p-values, arguing that publication
decisions based solely on them were leading to poor-quality science.
This debate led to broader recognition that p-values are often overinterpreted — they give less
“proof” than people assume.
Example
A study with a huge dataset may find that Price A converts 0.02% more than Price B, and this
difference is statistically significant (p < 0.05). However, if this difference translates into
negligible business impact, it lacks practical value.
Key Distinction
Aspect Statistical Significance Practical Significance
Whether the result is unlikely under Whether the result is large or
Definition
random chance (based on p-value/α) meaningful in real-world terms
Depends On Sample size, variability, test method Context, effect size, impact
But difference = 0.02% ⇒ not
Example p < 0.05 ⇒ statistically significant
practically meaningful
Over-interpreting trivial results as Ignoring meaningful but statistically
Risk
“important” weak results
Explanation
Large sample sizes can make tiny, unimportant effects statistically significant,
because even small differences can achieve very low p-values.
Conversely, small samples might fail to reach statistical significance even if the effect is
substantial.
Hence, ruling out chance does not automatically make a result important. A truly valuable
finding must be both statistically and practically significant.
However, in the field of data science, the role of p-values is more pragmatic and contextual
rather than decisive. Data scientists use p-values as informative indicators, not as the ultimate
decision-making criterion.
A p-value helps data scientists assess whether a seemingly interesting model result — such as a
strong correlation or feature effect — might simply be due to random chance rather than a real
underlying relationship.
For example:
If a feature shows a very low p-value in a regression model, it suggests that the feature’s
relationship with the target variable is unlikely to be due to chance alone.
Thus, p-values help identify which model outputs are stable and meaningful, versus those that
could be artifacts of noise.
In experiments or A/B testing, data scientists use p-values to support decision-making, not to
control it.
Hence, a low p-value is not automatically a “go” signal, and a high p-value is not always a
“stop” signal.
Instead, it is additional evidence to weigh before making a data-driven decision.
In some modeling workflows, p-values are used as intermediate selection criteria for feature
inclusion or feature elimination.
For instance:
In statistical models such as linear regression or logistic regression, features with high
p-values (indicating weak or non-significant relationships with the target variable) are
often removed to simplify the model.
Conversely, features with low p-values may be retained, as they are more likely to have
a statistically meaningful association.
Practical Interpretation
In data science practice:
p-values are not controlling, meaning decisions are not solely based on them.
T-TESTS
Introduction
The t-test is one of the most widely used statistical significance tests. It was developed by
William Sealy Gosset under the pseudonym “Student” in the early 1900s while working at the
Guinness Brewery. The t-test is based on the Student’s t-distribution, which provides a way to
test hypotheses when the sample size is small and the population standard deviation is
unknown.
The t-test helps determine whether the difference between sample means (or between a sample
mean and a known population mean) is statistically significant, i.e., not likely due to random
chance.
Purpose of a t-Test
The t-test is used to:
1. Defining hypotheses:
o Null hypothesis (H₀): Assumes there is no effect or no difference.
o Alternative hypothesis (H₁ or Ha): Assumes there is an effect or difference.
2. Selecting a test statistic:
o A test statistic is calculated from the sample data to measure the magnitude of
difference or effect.
o For the t-test, the test statistic follows the t-distribution when the null hypothesis
is true.
3. Computing the p-value:
o The p-value indicates the probability of observing the sample data (or something
more extreme) if the null hypothesis were true.
o A small p-value (typically < 0.05) leads us to reject H₀.
4. Decision-making:
o Compare the calculated t-value with the critical value from the t-distribution
table.
o Or, equivalently, compare the p-value to the chosen significance level (α).
In the early 20th century, computational methods like resampling tests (permutation or bootstrap
tests) were not feasible because of limited computing power. In the 1920s and 1930s, when
statistical hypothesis testing was being developed, it was not feasible to randomly shuffle data
thousands of times to do a resampling test. Statisticians found that a good approximation to the
permutation (shuffled) distribution was the t-test, based on Gosset’s t-distribution. It is used for
the very common two-sample comparison—A/B test—in which the data is numeric. But in order
for the t-distribution to be used without regard to scale, a standardized form of the test statistic
must be used.
The calculated t-value is compared against a critical t-value from the t-distribution table with
(n – 1) degrees of freedom.
Types of t-Tests
The t-test can be classified into three major types:
1. One-Sample t-Test
Used to determine whether the mean of a single sample differs significantly from a known or
hypothesized population mean.
Example: Testing if the average height of a class is different from the national average.
3. Paired-Sample t-Test
Used when the same subjects are measured before and after an intervention, or when samples
are related.
Example: Testing the effect of a training program by comparing scores before and after.
Formula:
If these assumptions are violated, non-parametric tests (e.g., Mann–Whitney U test) can be
used instead.
All statistical software, as well as R and Python, includes commands that embody the formula. In
R, the function is [Link]:
R Example
[Link](Time ~ Page, data=session_times, alternative='less')
Output:
Interpretation:
Python Example
from scipy import stats
res = stats.ttest_ind(
session_times[session_times.Page == 'Page A'].Time,
session_times[session_times.Page == 'Page B'].Time,
equal_var=False
)
print(f'p-value for single sided test: {[Link] / 2:.4f}')
Result:
This p-value matches the R result, indicating the same conclusion — no significant difference.
Decision Rules
Criterion Decision
p-value < α (0.05) Reject H₀ (Significant difference)
p-value ≥ α (0.05) Fail to reject H₀ (No significant difference)
Applications
Comparing the effectiveness of two treatments (medical trials)
A/B testing in marketing (click-through rates, session times)
Comparing test scores, reaction times, or machine learning model performances
Testing differences in means under experimental designs
MULTIPLE TESTING
In statistics, multiple testing (or multiple comparisons) refers to the practice of performing
many hypothesis tests on the same dataset. While testing multiple hypotheses can reveal
interesting insights, it also increases the risk of false positives — that is, incorrectly concluding
that an effect exists when it actually does not.
This means that if you analyze your data through enough perspectives and perform enough
statistical tests, you will almost inevitably find some result that appears statistically significant,
even if it occurred purely by chance.
In hypothesis testing, we typically choose a significance level (α) — commonly 0.05, meaning
we accept a 5% chance of wrongly rejecting a true null hypothesis (Type I error).
However, when many tests are conducted simultaneously, the chance of making at least one
Type I error increases dramatically.
Example
20 predictor variables
1 outcome variable, and all are randomly generated (i.e., no real relationship exists).
Therefore, the probability that at least one test appears significant (by chance) is:
1−0.36=0.64
This means there is a 64% chance of finding at least one “significant” result purely due to
random noise.
This inflation of the overall false positive rate when performing multiple tests is called alpha
inflation.
It leads to an increased probability of Type I errors, where we mistakenly find “effects” that do
not actually exist.
Overfitting Analogy
Example
If you try 100 different models or variable combinations, some model will likely appear to fit the
data very well — but its performance may be due to random coincidence, not genuine
predictive power.
In supervised learning, the use of a holdout (test) set or cross-validation helps mitigate
overfitting.
These techniques ensure the model’s performance is evaluated on data it has not seen before,
reducing the likelihood of false discoveries due to multiple experimentation.
However, in statistical analysis without labeled data (e.g., exploratory hypothesis testing),
such protections do not exist — and multiple testing remains a serious issue.
Each additional test increases the chance of obtaining at least one spurious result.
To correct for alpha inflation, statisticians developed adjustment procedures that make the
significance threshold more stringent when multiple tests are performed.
Bonferroni Adjustment
Example:
If you conduct 10 tests at α = 0.05, the adjusted threshold for each test becomes
This ensures that the overall probability of making at least one Type I error remains
approximately 0.05.
Limitation:
Bonferroni is conservative — it reduces false positives but can increase false negatives (missed
true effects).
Used when comparing multiple group means (post-hoc test after ANOVA).
Conceptually, it’s similar to reshuffling all data values and recalculating maximum mean
differences repeatedly to find how extreme the observed differences are.
Multiplicity issues
The False Discovery Rate (FDR) is the expected proportion of false positives among all
significant results.
Originally developed for large-scale hypothesis testing, such as genomic research, where
thousands of tests are conducted simultaneously.
Example in Genomics
FDR represents the misclassification rate within the positive class (class 1).
It answers: “Given that we labeled a record as positive (1), what is the probability that
this prediction is false?”
Example:
This is especially relevant when positives are rare and negatives are abundant.
A study by Bayer (2011) attempted to replicate 67 scientific studies and succeeded in fully
replicating only 14 of them — roughly 21%. Nearly two-thirds of results could not be
replicated, largely due to false discoveries and multiple testing effects.
Be aware that repeated querying and manipulation of data increases false discovery
risk.
Use adjustment methods (Bonferroni, FDR control) when conducting many tests.
Employ resampling and simulation heuristics (e.g., permutation tests) to estimate the
expected number of false positives under random conditions.
DEGREES OF FREEDOM
Introduction
The term degrees of freedom (df) is a fundamental concept in statistics that appears in many
areas such as hypothesis testing, regression, and probability distributions.
It represents the number of independent values in a sample that can vary freely while calculating
a statistical estimate.
In simple terms, degrees of freedom tell us how many pieces of information are available to
estimate another piece of information.
Definition
Degrees of Freedom (df) refer to the number of independent observations in a dataset that
can vary when estimating a statistical parameter.
Mathematically,
It shows how many independent comparisons or quantities can be used in statistical calculations.
Concept Explanation
Suppose you have a sample of 10 numbers. If you know the mean of those numbers, then only
9 numbers are free to vary — because once you know 9 of them and the mean, the 10th number
is automatically determined.
Hence:
df=n−1=10−1=9
This single restriction (knowing the mean) reduces one degree of freedom.
Importance in Statistics
Reason:
Formula:
This ensures that the sample variance is an unbiased estimator of the population variance.
(a) t-Distribution
(b) F-Distribution
In data science, formal statistical tests (like t-test or F-test) are less frequently used, especially
with large datasets.
When sample size (n) is large, the difference between using n and n − 1 becomes
negligible because:
However, in small datasets, using n − 1 is essential for accurate and unbiased results.
Formula:
df = n - k
where:
Example:
If you have 100 data points and estimate 4 regression coefficients,
then df=100−4=96.
When a categorical variable with k categories is included in a regression model, it creates k−1
dummy (indicator) variables.
Reason:
Including all k dummies causes perfect multicollinearity, also known as the dummy variable
trap.
Example Problem
Example:
You have a sample of 5 test scores: [78, 82, 85, 90, 95]. Calculate degrees of freedom for
variance.
Solution:
n=5
df = n – 1 = 5 – 1 = 4
When you calculate variance:
You divide by 4, not 5, because one value is dependent once the mean is fixed.
ANOVA
ANOVA is used when comparing 3 or more group means to determine if differences are
statistically significant. ANOVA (Analysis of Variance) tests whether multiple groups have the
same mean or not.
Table 3-3 shows the stickiness of four web pages, defined as the number of seconds a visitor
spent on the page. The four pages are switched out so that each web visitor receives one at
random. There are a total of five visitors for each page, and in Table 3-3, each column is an
independent set of data. The first viewer for page 1 has no connection to the first viewer for page
2.
Note that in a web test like this, we cannot fully implement the classic randomized sampling
design in which each visitor is selected at random from some huge population. We must take the
visitors as they come. Visitors may systematically differ depending on time of day, time of week,
season of the year, conditions of their internet, what device they are using, and so on. These
factors should be considered as potential bias when the experiment results are reviewed.
With four means, there are six possible comparisons between groups:
• Page 1 compared to page 2
• Page 1 compared to page 3
• Page 1 compared to page 4
• Page 2 compared to page 3
• Page 2 compared to page 4
• Page 3 compared to page 4
The more such pairwise comparisons we make, the greater the potential for being fooled by
random chance. Instead of worrying about all the different comparisons between individual
pages we could possibly make, we can do a single overall test that addresses the question,
“Could all the pages have the same underlying stickiness, and the differences among them be due
to the random way in which a common set of session times got allocated among the four pages?”
The procedure used to test this is ANOVA. The basis for it can be seen in the following
resampling procedure (specified here for the A/B/C/D test of web page stickiness):
1. Combine all the data together in a single box.
2. Shuffle and draw out four resamples of five values each.
3. Record the mean of each of the four groups.
4. Record the variance among the four group means.
5. Repeat steps 2–4 many (say, 1,000) times.
The proportion of the time did the resampled variance exceed the observed variance. This is the
p-value.
Fortunately, the aovp function in the lmPerm package computes a permutation test for this case:
F-Statistic
The F-statistic is based on the ratio of the variance across group means (i.e., the treatment effect)
to the variance due to residual error. The higher this ratio, the more statistically significant the
result.
Df is “degrees of freedom,” Sum Sq is “sum of squares,” Mean Sq is “mean squares” (short for
mean-squared deviations), and F value is the F-statistic. For the grand average, sum of squares is
the departure of the grand average from 0, squared, times 20 (the number of observations). The
degrees of freedom for the grand average is 1, by definition.
For the treatment means, the degrees of freedom is 3 (once three values are set, and then the
grand average is set, the other treatment mean cannot vary). Sum of squares for the treatment
means is the sum of squared departures between the treatment means and the grand average.
Mean squares (MS) is the sum of squares divided by the degrees of freedom. The F-statistic is
MS(treatment)/MS(error). The F value thus depends only on this ratio and can be compared to a
standard F-distribution to determine whether the differences among treatment means are greater
than would be expected in random chance variation.
Chi-Square Test
The chi-square test was originally developed by Karl Pearson in 1900. The term chi comes from
the Greek letter Χ used by Pearson in the article.
Chi-Square Test: A Resampling Approach Suppose you are testing three different headlines—A,
B, and C—and you run them each on 1,000 visitors, with the results shown in Table 3-4.
P-values measure the strength of evidence against the null hypothesis by quantifying how likely it is to observe an effect at least as extreme as the observed one, assuming the null hypothesis is true. A small p-value suggests statistical significance, but it does not prove the null hypothesis false. Common misinterpretations include equating a low p-value with the probability of the null hypothesis being false, leading to practices like 'p-hacking.' Furthermore, a p-value does not account for the size of an effect or its real-world relevance .
The p-value threshold of 0.05 is an arbitrary convention used to determine statistical significance, representing a willingness to accept a 5% risk of a Type I error (false positive). While this threshold is widely adopted, it has led to the over-reliance on p-values for determining validity, contributing to issues like 'p-hacking' and the publication bias towards studies reporting 'significant' findings. Over-emphasis on this threshold without considering effect size or practical significance can lead to misleading conclusions about research findings .
The purpose of statistical experiments is to test hypotheses, compare treatments, establish causality, and control variability. Researchers use these experiments to determine whether observed outcomes are likely the result of the treatments applied to the experimental units or merely due to random chance . This is done by formulating hypotheses, designing and conducting the experiment, collecting and analyzing the data, and then interpreting the results to draw conclusions about statistical significance in a real-world context .
A control group in A/B testing serves as a baseline that helps to isolate the effect of the treatment being tested. By comparing the treatment group to the control group, researchers can attribute any observed differences in outcomes to the treatment rather than external factors. This parallel testing condition ensures that differences are not due to seasonal effects or other variables, thereby enhancing the validity and reliability of findings .
Misuse of p-values has led to a crisis in scientific credibility because it encourages practices like 'p-hacking,' where researchers manipulate data or test multiple hypotheses until a p-value below 0.05 is achieved. This focus on statistical significance over replicability or practical significance has led to false discoveries and irreproducible results, undermining trust in scientific findings, particularly in fields like psychology and biomedical research where complex data and effects are common .
The permutation test is computationally intensive due to the need for generating a large number of permutations, which can be time-consuming and demanding, especially for large datasets or when multiple groups are involved. Additionally, the test assumes data points are exchangeable under the null hypothesis, which can be violated in cases like time-series data. These challenges make the permutation test less practical for extremely large datasets despite modern computing advances .
Randomization is critical because it ensures that differences between treatment groups are likely due to the treatment itself and not to other confounding variables. By randomly assigning subjects to control and treatment groups, researchers can mitigate the effects of biases and systemic differences, ensuring a fair comparison and reducing the risk of false conclusions about the efficacy of a treatment .
The permutation test is a non-parametric method that does not rely on assumptions about the underlying distribution of the data, making it suitable for datasets that violate parametric test assumptions such as normality. It provides exact significance levels for small samples and is highly flexible, applicable to a wide range of statistics including means, medians, and correlations. Its robustness comes from depending solely on observed data and random permutations, making it reliable even with outliers or non-normally distributed data .
A/B testing contributes to decision-making by providing empirical evidence about which option or strategy performs better. In business, it informs marketing strategies, webpage designs, and pricing models by testing how changes affect outcomes like conversion rates or revenue. In medicine, it helps compare the effectiveness of treatments or interventions by establishing which leads to better health outcomes. This structured experimentation ensures data-driven decisions that can optimize results and minimize risks .
Blinding in experiments, especially in medical trials, is significant because it prevents bias by ensuring that neither the subjects (single-blind) nor the subjects and investigators (double-blind) know which treatment is being administered. This eliminates placebo effects and observer bias, promoting unbiased assessment of a treatment's efficacy. In A/B testing, blinding removes psychological influences and provides more reliable data by mitigating the influence of expectations on outcomes .