Q31Inference & Hypothesis Testing
Sampling bias
Sampling bias arises when the selection process systematically underrepresents some target-population members.
Answer
Sampling bias arises when the selection process systematically underrepresents some target-population members.
Syntax
Bias=E[estimator]−true parameter
Example
Surveying only app users may misrepresent all customers.
Code example
responses=['app_user']*90+['non_user']*10
print(responses.count('app_user')/len(responses))
Diagram
Target → biased selection → unrepresentative sample
Key Points
- Sampling bias arises when the selection process systematically underrepresents some target-population members.
- Check assumptions and interpret the result in the context of the data and research question.
Q32Inference & Hypothesis Testing
Standard error vs standard deviation
SD describes spread among observations; SE describes sampling uncertainty in an estimator.
Answer
SD describes spread among observations; SE describes sampling uncertainty in an estimator.
Example
Larger n reduces mean SE even if individual observations remain equally variable.
Code example
import statistics,math
x=[2,4,6,8,10]
print(statistics.stdev(x),statistics.stdev(x)/math.sqrt(len(x)))
Diagram
SD of data ÷ √n → SE of mean
Key Points
- SD describes spread among observations; SE describes sampling uncertainty in an estimator.
- Check assumptions and interpret the result in the context of the data and research question.
Q33Inference & Hypothesis Testing
Confidence interval
A confidence interval is produced by a procedure that covers the fixed true parameter at the stated rate over repeated sample…
Answer
A confidence interval is produced by a procedure that covers the fixed true parameter at the stated rate over repeated samples.
Syntax
Estimate ± critical value × SE
Example
A t interval estimates a mean when population SD is unknown.
Code example
from scipy import stats
x=[12,14,13,16,15,11,14]
print(stats.t.interval(.95,df=len(x)-1,loc=sum(x)/len(x),scale=stats.sem(x)))
Diagram
Sample → estimate ± margin → interval
Key Points
- A confidence interval is produced by a procedure that covers the fixed true parameter at the stated rate over repeated samples.
- Check assumptions and interpret the result in the context of the data and research question.
Q34Inference & Hypothesis Testing
Null hypothesis
The null hypothesis is the default claim tested, often no effect or no difference.
Answer
The null hypothesis is the default claim tested, often no effect or no difference.
Syntax
H₀: parameter = reference value
Example
A null may state mean response time equals 200 ms.
Code example
observed_mean=194; null_mean=200
print(observed_mean-null_mean)
Diagram
H₀ + data → statistic → p-value
Key Points
- The null hypothesis is the default claim tested, often no effect or no difference.
- Check assumptions and interpret the result in the context of the data and research question.
Q35Inference & Hypothesis Testing
Alternative hypothesis
The alternative hypothesis states a difference or effect inconsistent with the null.
Answer
The alternative hypothesis states a difference or effect inconsistent with the null.
Syntax
H₁: θ≠θ₀, θ>θ₀, or θ<θ₀
Example
A redesign test may ask whether conversion changed in either direction.
Code example
alpha=.05; alternative='two-sided'
print(alpha,alternative)
Diagram
H₀: no effect vs H₁: effect
Key Points
- The alternative hypothesis states a difference or effect inconsistent with the null.
- Check assumptions and interpret the result in the context of the data and research question.
Q36Inference & Hypothesis Testing
P-value
A p-value is the probability, assuming H₀ and its model, of data at least as extreme as observed.
Answer
A p-value is the probability, assuming H₀ and its model, of data at least as extreme as observed.
Syntax
p=P(statistic as/extremer | H₀)
Example
p=.03 means 3% tail probability under H₀ and the model.
Code example
from scipy import stats
print(2*stats.norm.sf(abs(2.17)))
Diagram
Assume H₀ → reference distribution → tail area
Key Points
- A p-value is the probability, assuming H₀ and its model, of data at least as extreme as observed.
- Check assumptions and interpret the result in the context of the data and research question.
Q37Inference & Hypothesis Testing
Significance level
Alpha is the chosen long-run Type I error rate for a test.
Answer
Alpha is the chosen long-run Type I error rate for a test.
Example
At alpha .05, the test procedure has a 5% Type I error rate under H₀.
Code example
alpha=.05; p_value=.03
print(p_value<=alpha)
Diagram
p≤α → reject; otherwise fail to reject
Key Points
- Alpha is the chosen long-run Type I error rate for a test.
- Check assumptions and interpret the result in the context of the data and research question.
Q38Inference & Hypothesis Testing
Type I and Type II errors
Type I rejects a true null; Type II fails to reject a false null.
Answer
Type I rejects a true null; Type II fails to reject a false null.
Syntax
Type I rate=α; Type II rate=β; power=1−β
Example
A false alarm is Type I; missing a real effect is Type II.
Code example
alpha,beta=.05,.20
print(1-beta)
Diagram
Reality × decision → correct decision or error
Key Points
- Type I rejects a true null; Type II fails to reject a false null.
- Check assumptions and interpret the result in the context of the data and research question.
Q39Inference & Hypothesis Testing
Statistical power
Power is the probability of rejecting H₀ for a specified alternative effect.
Answer
Power is the probability of rejecting H₀ for a specified alternative effect.
Example
Larger samples often improve power for a fixed effect and noise level.
Code example
from statsmodels.stats.power import TTestIndPower
print(TTestIndPower().power(effect_size=.5,nobs1=64,alpha=.05))
Diagram
Effect + noise + sample size + alpha → power
Key Points
- Power is the probability of rejecting H₀ for a specified alternative effect.
- Check assumptions and interpret the result in the context of the data and research question.
Q40Inference & Hypothesis Testing
One-sample t-test
Tests whether a population mean differs from a reference when population SD is unknown and assumptions are suitable.
Answer
Tests whether a population mean differs from a reference when population SD is unknown and assumptions are suitable.
Syntax
t=(x̄−μ₀)/(s/√n), df=n−1
Example
Test if average delivery time differs from 30 minutes.
Code example
from scipy import stats
print(stats.ttest_1samp([28,31,29,35,30,27,32],popmean=30))
Diagram
Sample mean vs reference → t statistic
Key Points
- Tests whether a population mean differs from a reference when population SD is unknown and assumptions are suitable.
- Check assumptions and interpret the result in the context of the data and research question.
Q41Inference & Hypothesis Testing
Independent two-sample t-test
Compares means of independent groups; Welch's test does not assume equal variances.
Answer
Compares means of independent groups; Welch's test does not assume equal variances.
Syntax
t=(x̄₁−x̄₂)/√(s₁²/n₁+s₂²/n₂)
Example
Compare average task time in control and treatment groups.
Code example
from scipy import stats
print(stats.ttest_ind([12,14,13,15,11],[10,12,11,13,9],equal_var=False))
Diagram
Group A mean vs Group B mean → test
Key Points
- Compares means of independent groups; Welch's test does not assume equal variances.
- Check assumptions and interpret the result in the context of the data and research question.
Q42Inference & Hypothesis Testing
Paired t-test
Tests whether the mean of within-pair differences is zero.
Answer
Tests whether the mean of within-pair differences is zero.
Example
Compare task time before and after redesign for the same users.
Code example
from scipy import stats
print(stats.ttest_rel([40,42,38,45,41],[35,40,34,39,37]))
Diagram
Same unit: before → difference ← after
Key Points
- Tests whether the mean of within-pair differences is zero.
- Check assumptions and interpret the result in the context of the data and research question.
Q43Inference & Hypothesis Testing
Chi-square independence test
Tests association between categorical variables using observed and expected contingency-table counts.
Answer
Tests association between categorical variables using observed and expected contingency-table counts.
Example
Test whether device type relates to subscription status.
Code example
from scipy.stats import chi2_contingency
print(chi2_contingency([[30,20],[15,35]]))
Diagram
Contingency table → expected counts → χ²
Key Points
- Tests association between categorical variables using observed and expected contingency-table counts.
- Check assumptions and interpret the result in the context of the data and research question.
Q44Inference & Hypothesis Testing
Fisher exact test
An exact conditional association test useful for small 2×2 tables.
Answer
An exact conditional association test useful for small 2×2 tables.
Syntax
Exact probability conditional on margins
Example
Compare two conversion rates when cell counts are small.
Code example
from scipy.stats import fisher_exact
print(fisher_exact([[2,8],[1,9]]))
Diagram
2×2 table → fixed margins → exact test
Key Points
- An exact conditional association test useful for small 2×2 tables.
- Check assumptions and interpret the result in the context of the data and research question.
Q45Inference & Hypothesis Testing
ANOVA
ANOVA tests whether three or more population means are all equal.
Answer
ANOVA tests whether three or more population means are all equal.
Syntax
F=MS_between/MS_within
Example
Compare latency across three server configurations.
Code example
from scipy.stats import f_oneway
print(f_oneway([10,12,11],[14,15,13],[9,10,8]))
Diagram
Between-group variation ÷ within-group variation
Key Points
- ANOVA tests whether three or more population means are all equal.
- Check assumptions and interpret the result in the context of the data and research question.
Q46Inference & Hypothesis Testing
Nonparametric tests
These tests often use ranks or fewer distributional assumptions than common parametric tests.
Answer
These tests often use ranks or fewer distributional assumptions than common parametric tests.
Syntax
Example: rank-based Mann–Whitney U
Example
Use rank methods when a mean-based model is unsuitable for the question and data.
Code example
from scipy.stats import mannwhitneyu
print(mannwhitneyu([1,2,3,8],[4,5,6,7]))
Diagram
Raw values → ranks → statistic
Key Points
- These tests often use ranks or fewer distributional assumptions than common parametric tests.
- Check assumptions and interpret the result in the context of the data and research question.
Q47Inference & Hypothesis Testing
Mann–Whitney U
Compares rank distributions for two independent samples; a median interpretation needs additional shape assumptions.
Answer
Compares rank distributions for two independent samples; a median interpretation needs additional shape assumptions.
Syntax
U statistic from pooled ranks
Example
Compare skewed purchase amounts across independent groups.
Code example
from scipy.stats import mannwhitneyu
print(mannwhitneyu([12,15,18,80],[20,22,25,30]))
Diagram
Pool groups → rank → compare rank sums
Key Points
- Compares rank distributions for two independent samples; a median interpretation needs additional shape assumptions.
- Check assumptions and interpret the result in the context of the data and research question.
Q48Inference & Hypothesis Testing
Wilcoxon signed-rank test
A rank-based test for paired differences, often used when normality of differences is doubtful.
Answer
A rank-based test for paired differences, often used when normality of differences is doubtful.
Syntax
Rank absolute nonzero differences and use signs
Example
Compare paired ratings before and after a feature change.
Code example
from scipy.stats import wilcoxon
print(wilcoxon([2,-1,3,0,1]))
Diagram
Paired differences → absolute ranks + signs
Key Points
- A rank-based test for paired differences, often used when normality of differences is doubtful.
- Check assumptions and interpret the result in the context of the data and research question.
Q49Inference & Hypothesis Testing
Correlation vs causation
Association does not establish that one variable causes another; confounding can explain both.
Answer
Association does not establish that one variable causes another; confounding can explain both.
Syntax
Association ≠ causal effect
Example
Hot weather can raise both ice-cream sales and swimming incidents.
Code example
dag='Temperature → Ice cream sales\nTemperature → Swimming incidents'
print(dag)
Diagram
Confounder → X and Y
Key Points
- Association does not establish that one variable causes another; confounding can explain both.
- Check assumptions and interpret the result in the context of the data and research question.
Q50Inference & Hypothesis Testing
Linear regression
Models the conditional mean of a response as a linear combination of predictors.
Answer
Models the conditional mean of a response as a linear combination of predictors.
Example
Predict delivery duration from distance.
Code example
import numpy as np
from sklearn.linear_model import LinearRegression
m=LinearRegression().fit(np.array([[1],[2],[3],[4]]),[3,5,7,8])
print(m.intercept_,m.coef_[0])
Diagram
Points → least-squares line → prediction
Key Points
- Models the conditional mean of a response as a linear combination of predictors.
- Check assumptions and interpret the result in the context of the data and research question.
Q51Regression & Resampling
Regression residuals
A residual is observed response minus fitted response.
Answer
A residual is observed response minus fitted response.
Example
Actual time 12 and predicted time 10 gives residual +2.
Code example
actual,predicted=12,10
print(actual-predicted)
Diagram
Observed y − fitted ŷ = residual
Key Points
- A residual is observed response minus fitted response.
- Check assumptions and interpret the result in the context of the data and research question.
Q52Regression & Resampling
R-squared
R² describes sample response variation accounted for by the fitted model relative to a mean baseline in standard settings.
Answer
R² describes sample response variation accounted for by the fitted model relative to a mean baseline in standard settings.
Example
R²=.8 indicates 80% of sample response variation accounted for under the usual definition.
Code example
from sklearn.metrics import r2_score
print(r2_score([1,2,3,4],[1.1,1.9,3.2,3.8]))
Diagram
Total variation → explained + residual variation
Key Points
- R² describes sample response variation accounted for by the fitted model relative to a mean baseline in standard settings.
- Check assumptions and interpret the result in the context of the data and research question.
Q53Regression & Resampling
Multicollinearity
Predictors are multicollinear when they strongly relate linearly, destabilizing individual coefficient estimates.
Answer
Predictors are multicollinear when they strongly relate linearly, destabilizing individual coefficient estimates.
Example
House size and number of rooms may overlap as predictors.
Code example
import numpy as np
print(np.corrcoef([50,70,90,110],[2,3,4,5])[0,1])
Diagram
Predictor X₁ ↔ Predictor X₂
Key Points
- Predictors are multicollinear when they strongly relate linearly, destabilizing individual coefficient estimates.
- Check assumptions and interpret the result in the context of the data and research question.
Q54Regression & Resampling
Logistic regression
Models a binary outcome probability using the logit link.
Answer
Models a binary outcome probability using the logit link.
Syntax
log(p/(1−p))=β₀+β₁x
Example
Estimate conversion probability from number of visits.
Code example
from sklearn.linear_model import LogisticRegression
m=LogisticRegression().fit([[1],[2],[3],[4],[5],[6]],[0,0,0,1,1,1])
print(m.predict_proba([[3.5]])[0,1])
Diagram
Features → linear score → sigmoid → probability
Key Points
- Models a binary outcome probability using the logit link.
- Check assumptions and interpret the result in the context of the data and research question.
Q55Regression & Resampling
Odds ratio
An odds ratio compares odds across groups or predictor values.
Answer
An odds ratio compares odds across groups or predictor values.
Syntax
OR=odds₁/odds₀; model OR=e^β
Example
OR=1.5 means 50% higher odds, not 50% higher probability.
Code example
import math
print(math.exp(math.log(1.5)))
Diagram
Odds in group 1 ÷ odds in group 0
Key Points
- An odds ratio compares odds across groups or predictor values.
- Check assumptions and interpret the result in the context of the data and research question.
Q56Regression & Resampling
Simpson's paradox
An aggregate association can reverse after stratifying because groups have different compositions.
Answer
An aggregate association can reverse after stratifying because groups have different compositions.
Syntax
Pooled association may differ from within-group associations
Example
A treatment may look better overall because more low-risk cases received it.
Code example
rates={'low_risk':90/100,'high_risk':10/100}
print(rates)
Diagram
Stratum trends + unequal weights → pooled reversal
Key Points
- An aggregate association can reverse after stratifying because groups have different compositions.
- Check assumptions and interpret the result in the context of the data and research question.
Q57Regression & Resampling
Bootstrap resampling
Bootstrap estimates uncertainty by repeatedly sampling observed records with replacement.
Answer
Bootstrap estimates uncertainty by repeatedly sampling observed records with replacement.
Syntax
Resample B times → compute statistic each time
Example
Bootstrap a median interval when a simple formula is inconvenient.
Code example
import numpy as np
r=np.random.default_rng(4); x=np.array([2,3,5,7,11])
b=[np.median(r.choice(x,size=len(x),replace=True)) for _ in range(2000)]
print(np.percentile(b,[2.5,97.5]))
Diagram
Sample → resample with replacement → statistic distribution
Key Points
- Bootstrap estimates uncertainty by repeatedly sampling observed records with replacement.
- Check assumptions and interpret the result in the context of the data and research question.
Q58Regression & Resampling
Permutation test
A permutation test creates a null reference distribution by rearranging labels under a valid exchangeability assumption.
Answer
A permutation test creates a null reference distribution by rearranging labels under a valid exchangeability assumption.
Syntax
Observed statistic vs permuted-statistic distribution
Example
Shuffle treatment labels to test a group difference under a sharp null.
Code example
import numpy as np
r=np.random.default_rng(3); labels=np.array([0,0,1,1])
print(r.permutation(labels))
Diagram
Shuffle labels under H₀ → recompute statistic
Key Points
- A permutation test creates a null reference distribution by rearranging labels under a valid exchangeability assumption.
- Check assumptions and interpret the result in the context of the data and research question.
Q59Regression & Resampling
Multiple testing
Testing many hypotheses raises the chance of at least one false positive.
Answer
Testing many hypotheses raises the chance of at least one false positive.
Syntax
FWER=1−(1−α)^m for m independent true nulls
Example
Twenty independent tests at .05 produce about .64 family-wise error probability.
Code example
alpha,m=.05,20
print(1-(1-alpha)**m)
Diagram
Many tests → accumulated false-positive risk
Key Points
- Testing many hypotheses raises the chance of at least one false positive.
- Check assumptions and interpret the result in the context of the data and research question.
Q60Regression & Resampling
Bonferroni correction
Bonferroni controls family-wise error by dividing alpha by the number of tests.
Answer
Bonferroni controls family-wise error by dividing alpha by the number of tests.
Syntax
Per-test α=family α/m
Example
For 10 tests and family alpha .05, per-test threshold is .005.
Code example
alpha,m=.05,10
print(alpha/m)
Diagram
Family alpha → divide by number of tests
Key Points
- Bonferroni controls family-wise error by dividing alpha by the number of tests.
- Check assumptions and interpret the result in the context of the data and research question.
Q61Bayesian Methods & Experiments
Benjamini–Hochberg
BH controls false discovery rate by ranking p-values and comparing them to rank-dependent thresholds.
Answer
BH controls false discovery rate by ranking p-values and comparing them to rank-dependent thresholds.
Syntax
Find largest i with p(i)≤(i/m)q
Example
Useful for many exploratory comparisons.
Code example
from statsmodels.stats.multitest import multipletests
print(multipletests([.001,.01,.03,.2],method='fdr_bh')[0])
Diagram
Sort p-values → rank → compare to (i/m)q
Key Points
- BH controls false discovery rate by ranking p-values and comparing them to rank-dependent thresholds.
- Check assumptions and interpret the result in the context of the data and research question.
Q62Bayesian Methods & Experiments
Effect size
Effect size describes magnitude, complementing statistical significance.
Answer
Effect size describes magnitude, complementing statistical significance.
Syntax
Cohen's d=(x̄₁−x̄₂)/s_pooled
Example
A tiny lift can be significant with a huge sample but practically unimportant.
Code example
import numpy as np
a=np.array([10,11,12]); b=np.array([12,13,14])
sp=np.sqrt(((len(a)-1)*a.var(ddof=1)+(len(b)-1)*b.var(ddof=1))/(len(a)+len(b)-2))
print((a.mean()-b.mean())/sp)
Diagram
Difference → standardized or natural-unit effect
Key Points
- Effect size describes magnitude, complementing statistical significance.
- Check assumptions and interpret the result in the context of the data and research question.
Q63Bayesian Methods & Experiments
Bayesian prior and posterior
A prior encodes pre-data uncertainty; posterior combines prior and likelihood.
Answer
A prior encodes pre-data uncertainty; posterior combines prior and likelihood.
Syntax
Posterior ∝ likelihood × prior
Example
Beta prior plus binomial data gives a Beta posterior for conversion probability.
Code example
from scipy.stats import beta
print(beta.mean(a=2+5,b=8+15))
Diagram
Prior + data likelihood → posterior
Key Points
- A prior encodes pre-data uncertainty; posterior combines prior and likelihood.
- Check assumptions and interpret the result in the context of the data and research question.
Q64Bayesian Methods & Experiments
Beta distribution
Beta is a distribution on [0,1], often used for uncertainty about probabilities.
Answer
Beta is a distribution on [0,1], often used for uncertainty about probabilities.
Syntax
f(p)∝p^(α−1)(1−p)^(β−1)
Example
Beta(2,8) has mean .2.
Code example
from scipy.stats import beta
print(beta.mean(a=2,b=8))
Diagram
p in [0,1]; α and β shape the distribution
Key Points
- Beta is a distribution on [0,1], often used for uncertainty about probabilities.
- Check assumptions and interpret the result in the context of the data and research question.
Q65Bayesian Methods & Experiments
Likelihood function
Likelihood measures how compatible observed data are with candidate parameter values.
Answer
Likelihood measures how compatible observed data are with candidate parameter values.
Syntax
L(θ|data)=P(data|θ)
Example
For Bernoulli data, likelihood is proportional to p^k(1−p)^(n−k).
Code example
import numpy as np
p=np.linspace(.01,.99,99); k,n=7,10
L=p**k*(1-p)**(n-k)
print(p[int(np.argmax(L))])
Diagram
Candidate θ → likelihood of observed data
Key Points
- Likelihood measures how compatible observed data are with candidate parameter values.
- Check assumptions and interpret the result in the context of the data and research question.
Q66Bayesian Methods & Experiments
Maximum likelihood estimation
MLE selects the parameter maximizing the observed-data likelihood.
Answer
MLE selects the parameter maximizing the observed-data likelihood.
Syntax
θ̂=argmaxθ L(θ|data)
Example
For Bernoulli observations, p̂ is the sample success proportion.
Code example
x=[1,0,1,1,0,1]
print(sum(x)/len(x))
Diagram
Data → likelihood → maximizing estimate
Key Points
- MLE selects the parameter maximizing the observed-data likelihood.
- Check assumptions and interpret the result in the context of the data and research question.
Q67Bayesian Methods & Experiments
Likelihood ratio test
Compares a constrained null model fit with a broader alternative model fit.
Answer
Compares a constrained null model fit with a broader alternative model fit.
Syntax
−2 log(L₀/L₁) approximately χ² under conditions
Example
Test whether adding a predictor improves a nested model.
Code example
from scipy.stats import chi2
print(chi2.sf(5.2,1))
Diagram
Null fit vs full fit → likelihood-ratio statistic
Key Points
- Compares a constrained null model fit with a broader alternative model fit.
- Check assumptions and interpret the result in the context of the data and research question.
Q68Bayesian Methods & Experiments
Non-inferiority test
Tests whether a new option is not worse than a comparator beyond a prespecified margin.
Answer
Tests whether a new option is not worse than a comparator beyond a prespecified margin.
Syntax
H₀: effect≤−Δ; H₁: effect>−Δ
Example
A cheaper service may be acceptable if quality loss stays within a justified margin.
Code example
margin=.05; effect=-.01
print(effect > -margin)
Diagram
Define margin → estimate + CI → compare boundary
Key Points
- Tests whether a new option is not worse than a comparator beyond a prespecified margin.
- Check assumptions and interpret the result in the context of the data and research question.
Q69Bayesian Methods & Experiments
Equivalence testing
Tests whether an effect is fully inside prespecified practical equivalence bounds.
Answer
Tests whether an effect is fully inside prespecified practical equivalence bounds.
Example
Show two implementations differ by less than ±5 ms.
Code example
lower,upper=-5,5; ci=(-2,3)
print(ci[0]>lower and ci[1]<upper)
Diagram
Equivalence bounds contain confidence interval
Key Points
- Tests whether an effect is fully inside prespecified practical equivalence bounds.
- Check assumptions and interpret the result in the context of the data and research question.
Q70Bayesian Methods & Experiments
A/B testing
Random assignment compares variants to estimate a causal effect when execution is valid.
Answer
Random assignment compares variants to estimate a causal effect when execution is valid.
Syntax
Effect=metric(B)−metric(A)
Example
Randomly show two checkout buttons and compare conversions.
Code example
from statsmodels.stats.proportion import proportions_ztest
print(proportions_ztest([120,138],[2000,2000]))
Diagram
Eligible users → random assignment → compare outcomes
Key Points
- Random assignment compares variants to estimate a causal effect when execution is valid.
- Check assumptions and interpret the result in the context of the data and research question.