InterviewTreedInterviewTreed

InterviewTreed Question Bank

Statistics & Probability Interview Questions and Answers

Understand probability, statistical concepts, distributions, hypothesis testing, regression, and the mathematical foundations of data science and machine learning.

Total Questions

100

Beginner

30

Intermediate

40

Advanced

30

Beginner Questions

Foundational concepts, terminology, and core ideas.

Q1Probability Foundations

Probability

Probability measures how likely an event is, from 0 to 1.

Answer

Probability measures how likely an event is, from 0 to 1.

Syntax

P(A)=favorable outcomes/total equally likely outcomes

Example

A fair die rolls a 4 with probability 1/6.

Code example

p=1/6
print(p)

Diagram

Ω={1,2,3,4,5,6} → A={4} → P(A)=1/6

Key Points

  • Probability measures how likely an event is, from 0 to 1.
  • Check assumptions and interpret the result in the context of the data and research question.
Q2Probability Foundations

Sample spaces and events

A sample space contains every possible outcome; an event is a subset of that space.

Answer

A sample space contains every possible outcome; an event is a subset of that space.

Syntax

A ⊆ Ω

Example

For a coin, Ω={H,T}; the event of heads is {H}.

Code example

sample_space={'H','T'}
event={'H'}
print(len(event)/len(sample_space))

Diagram

Experiment → Ω → event A⊆Ω

Key Points

  • A sample space contains every possible outcome; an event is a subset of that space.
  • Check assumptions and interpret the result in the context of the data and research question.
Q3Probability Foundations

Complement rule

The complement is the event that A does not occur.

Answer

The complement is the event that A does not occur.

Syntax

P(Aᶜ)=1−P(A)

Example

If rain probability is 0.3, no-rain probability is 0.7.

Code example

p_rain=.3
print(1-p_rain)

Diagram

Ω = A ∪ Aᶜ; A∩Aᶜ=∅

Key Points

  • The complement is the event that A does not occur.
  • Check assumptions and interpret the result in the context of the data and research question.
Q4Probability Foundations

Addition rule for disjoint events

For mutually exclusive events, add their probabilities to get the probability that either occurs.

Answer

For mutually exclusive events, add their probabilities to get the probability that either occurs.

Syntax

P(A∪B)=P(A)+P(B), if A∩B=∅

Example

Rolling 1 or 2 on a fair die has probability 1/3.

Code example

print(1/6+1/6)

Diagram

A and B disjoint → add probabilities

Key Points

  • For mutually exclusive events, add their probabilities to get the probability that either occurs.
  • Check assumptions and interpret the result in the context of the data and research question.
Q5Probability Foundations

General addition rule

For overlapping events, subtract the overlap to avoid counting it twice.

Answer

For overlapping events, subtract the overlap to avoid counting it twice.

Syntax

P(A∪B)=P(A)+P(B)−P(A∩B)

Example

If P(A)=.5, P(B)=.4, and overlap=.2, union=.7.

Code example

pa,pb,pab=.5,.4,.2
print(pa+pb-pab)

Diagram

A only + overlap + B only

Key Points

  • For overlapping events, subtract the overlap to avoid counting it twice.
  • Check assumptions and interpret the result in the context of the data and research question.
Q6Probability Foundations

Conditional probability

Conditional probability gives the probability of A when B is known to have occurred.

Answer

Conditional probability gives the probability of A when B is known to have occurred.

Syntax

P(A|B)=P(A∩B)/P(B)

Example

6 of 10 flagged records are overdue, so P(overdue|flagged)=.6.

Code example

both, flagged = 6, 10
print(both/flagged)

Diagram

Restrict sample space to B; count A∩B

Key Points

  • Conditional probability gives the probability of A when B is known to have occurred.
  • Check assumptions and interpret the result in the context of the data and research question.
Q7Probability Foundations

Independence

Events are independent if knowing one occurred does not change the probability of the other.

Answer

Events are independent if knowing one occurred does not change the probability of the other.

Syntax

P(A∩B)=P(A)P(B)

Example

Two fair coin tosses have probability 1/4 of both being heads.

Code example

p=.5
print(p*p)

Diagram

Toss 1 outcome independent of toss 2

Key Points

  • Events are independent if knowing one occurred does not change the probability of the other.
  • Check assumptions and interpret the result in the context of the data and research question.
Q8Probability Foundations

Bayes theorem

Bayes theorem updates a prior probability using observed evidence and the likelihood.

Answer

Bayes theorem updates a prior probability using observed evidence and the likelihood.

Syntax

P(A|B)=P(B|A)P(A)/P(B)

Example

A positive test must be interpreted with test accuracy and base rate.

Code example

prior=.01; sensitivity=.95; evidence=.05
print(sensitivity*prior/evidence)

Diagram

Prior + likelihood → posterior

Key Points

  • Bayes theorem updates a prior probability using observed evidence and the likelihood.
  • Check assumptions and interpret the result in the context of the data and research question.
Q9Probability Foundations

Random variable

A random variable maps outcomes to numeric values.

Answer

A random variable maps outcomes to numeric values.

Syntax

X: Ω→ℝ

Example

For two tosses, X may count the number of heads.

Code example

outcomes=['TT','HT','TH','HH']
print([s.count('H') for s in outcomes])

Diagram

Outcome → numeric value

Key Points

  • A random variable maps outcomes to numeric values.
  • Check assumptions and interpret the result in the context of the data and research question.
Q10Probability Foundations

Discrete vs continuous variables

Discrete variables have countable values; continuous variables can take any value in an interval.

Answer

Discrete variables have countable values; continuous variables can take any value in an interval.

Syntax

Discrete: P(X=x); continuous: P(a≤X≤b)=∫f(x)dx

Example

Ticket count is discrete; waiting time is often continuous.

Code example

tickets=[0,1,2,3]
waiting_minutes=2.75
print(tickets,waiting_minutes)

Diagram

Discrete points vs continuous interval

Key Points

  • Discrete variables have countable values; continuous variables can take any value in an interval.
  • Check assumptions and interpret the result in the context of the data and research question.
Q11Descriptive Statistics & Distributions

Expected value

Expected value is the probability-weighted average of possible values.

Answer

Expected value is the probability-weighted average of possible values.

Syntax

E[X]=ΣxP(X=x)

Example

A fair die has expected value 3.5.

Code example

values=[1,2,3,4,5,6]
print(sum(values)/len(values))

Diagram

Values × probabilities → weighted sum

Key Points

  • Expected value is the probability-weighted average of possible values.
  • Check assumptions and interpret the result in the context of the data and research question.
Q12Descriptive Statistics & Distributions

Variance

Variance is the expected squared distance from the mean.

Answer

Variance is the expected squared distance from the mean.

Syntax

Var(X)=E[(X−μ)²]

Example

For [2,4,6], population variance is 8/3.

Code example

x=[2,4,6]; mu=sum(x)/len(x)
print(sum((v-mu)**2 for v in x)/len(x))

Diagram

Values → deviations → squares → average

Key Points

  • Variance is the expected squared distance from the mean.
  • Check assumptions and interpret the result in the context of the data and research question.
Q13Descriptive Statistics & Distributions

Standard deviation

Standard deviation is the square root of variance and uses the original data units.

Answer

Standard deviation is the square root of variance and uses the original data units.

Syntax

σ=√Var(X)

Example

A 5-minute SD describes spread in waiting time.

Code example

import statistics
print(statistics.pstdev([2,4,6]))

Diagram

Variance in squared units → square root → SD

Key Points

  • Standard deviation is the square root of variance and uses the original data units.
  • Check assumptions and interpret the result in the context of the data and research question.
Q14Descriptive Statistics & Distributions

Covariance

Covariance indicates whether two variables tend to move together.

Answer

Covariance indicates whether two variables tend to move together.

Syntax

Cov(X,Y)=E[(X−μX)(Y−μY)]

Example

Positive covariance means above-average X tends to accompany above-average Y.

Code example

import numpy as np
print(np.cov([1,2,3],[2,4,6],ddof=0)[0,1])

Diagram

X rises as Y rises → positive covariance

Key Points

  • Covariance indicates whether two variables tend to move together.
  • Check assumptions and interpret the result in the context of the data and research question.
Q15Descriptive Statistics & Distributions

Correlation

Correlation standardizes covariance and measures linear association from −1 to +1.

Answer

Correlation standardizes covariance and measures linear association from −1 to +1.

Syntax

ρ=Cov(X,Y)/(σXσY)

Example

If y=2x exactly, Pearson correlation is +1.

Code example

import numpy as np
print(np.corrcoef([1,2,3],[2,4,6])[0,1])

Diagram

−1 negative ← 0 none linear → +1 positive

Key Points

  • Correlation standardizes covariance and measures linear association from −1 to +1.
  • Check assumptions and interpret the result in the context of the data and research question.
Q16Descriptive Statistics & Distributions

Law of large numbers

With many suitable independent trials, a sample average tends toward its expected value.

Answer

With many suitable independent trials, a sample average tends toward its expected value.

Syntax

X̄ₙ→μ as n grows

Example

The proportion of heads tends toward 0.5 over many fair tosses.

Code example

import random
random.seed(7)
x=[random.choice([0,1]) for _ in range(10000)]
print(sum(x)/len(x))

Diagram

More trials → average stabilizes near expectation

Key Points

  • With many suitable independent trials, a sample average tends toward its expected value.
  • Check assumptions and interpret the result in the context of the data and research question.
Q17Descriptive Statistics & Distributions

Central limit theorem

Under common conditions, the standardized sample mean approaches a normal distribution as sample size grows.

Answer

Under common conditions, the standardized sample mean approaches a normal distribution as sample size grows.

Syntax

Z=(X̄−μ)/(σ/√n)

Example

Means of samples from a skewed population may look approximately normal.

Code example

import numpy as np
r=np.random.default_rng(1)
means=[r.exponential(size=40).mean() for _ in range(1000)]
print(round(float(np.mean(means)),3))

Diagram

Population → repeated samples → distribution of means

Key Points

  • Under common conditions, the standardized sample mean approaches a normal distribution as sample size grows.
  • Check assumptions and interpret the result in the context of the data and research question.
Q18Descriptive Statistics & Distributions

Probability mass function

A PMF gives each value's probability for a discrete random variable.

Answer

A PMF gives each value's probability for a discrete random variable.

Syntax

p(x)=P(X=x); Σp(x)=1

Example

Each face of a fair die has probability 1/6.

Code example

pmf={k:1/6 for k in range(1,7)}
print(sum(pmf.values()))

Diagram

Discrete x values → probabilities sum to 1

Key Points

  • A PMF gives each value's probability for a discrete random variable.
  • Check assumptions and interpret the result in the context of the data and research question.
Q19Descriptive Statistics & Distributions

Probability density function

A PDF describes density for a continuous variable; interval probability is area under the curve.

Answer

A PDF describes density for a continuous variable; interval probability is area under the curve.

Syntax

P(a≤X≤b)=∫ₐᵇf(x)dx

Example

Normal probability between −1 and 1 is area under the density.

Code example

from scipy.stats import norm
print(norm.cdf(1)-norm.cdf(-1))

Diagram

Density curve; area over interval = probability

Key Points

  • A PDF describes density for a continuous variable; interval probability is area under the curve.
  • Check assumptions and interpret the result in the context of the data and research question.
Q20Descriptive Statistics & Distributions

Cumulative distribution function

A CDF gives the probability a random variable is at most x.

Answer

A CDF gives the probability a random variable is at most x.

Syntax

F(x)=P(X≤x)

Example

For a standard normal distribution, F(0)=0.5.

Code example

from scipy.stats import norm
print(norm.cdf(0))

Diagram

x increases → CDF rises from 0 to 1

Key Points

  • A CDF gives the probability a random variable is at most x.
  • Check assumptions and interpret the result in the context of the data and research question.
Q21Descriptive Statistics & Distributions

Bernoulli distribution

Bernoulli models one binary trial with success probability p.

Answer

Bernoulli models one binary trial with success probability p.

Syntax

P(X=x)=pˣ(1−p)^(1−x), x∈{0,1}

Example

An email click is 1 for click and 0 otherwise.

Code example

from scipy.stats import bernoulli
print(bernoulli.pmf([0,1],p=.2))

Diagram

Failure 0 (1−p) | success 1 (p)

Key Points

  • Bernoulli models one binary trial with success probability p.
  • Check assumptions and interpret the result in the context of the data and research question.
Q22Descriptive Statistics & Distributions

Binomial distribution

Binomial counts successes in n independent Bernoulli trials with common p.

Answer

Binomial counts successes in n independent Bernoulli trials with common p.

Syntax

P(X=k)=C(n,k)pᵏ(1−p)ⁿ⁻ᵏ

Example

Count conversions among 10 users with conversion probability .2.

Code example

from scipy.stats import binom
print(binom.pmf(3,n=10,p=.2))

Diagram

n trials → success/failure → count

Key Points

  • Binomial counts successes in n independent Bernoulli trials with common p.
  • Check assumptions and interpret the result in the context of the data and research question.
Q23Descriptive Statistics & Distributions

Geometric distribution

Geometric models the number of Bernoulli trials until the first success.

Answer

Geometric models the number of Bernoulli trials until the first success.

Syntax

P(X=k)=(1−p)^(k−1)p

Example

At 10% click chance, it models impressions until first click.

Code example

from scipy.stats import geom
print(geom.pmf(4,p=.1))

Diagram

Failures → first success at trial k

Key Points

  • Geometric models the number of Bernoulli trials until the first success.
  • Check assumptions and interpret the result in the context of the data and research question.
Q24Descriptive Statistics & Distributions

Poisson distribution

Poisson models event counts over a fixed interval under a stable-rate independent-events model.

Answer

Poisson models event counts over a fixed interval under a stable-rate independent-events model.

Syntax

P(X=k)=e^(−λ)λᵏ/k!

Example

An average of 3 tickets per hour suggests a Poisson(3) count model.

Code example

from scipy.stats import poisson
print(poisson.pmf(2,mu=3))

Diagram

Rate λ per interval → count k

Key Points

  • Poisson models event counts over a fixed interval under a stable-rate independent-events model.
  • Check assumptions and interpret the result in the context of the data and research question.
Q25Descriptive Statistics & Distributions

Uniform distribution

A continuous uniform distribution has constant density over an interval.

Answer

A continuous uniform distribution has constant density over an interval.

Syntax

f(x)=1/(b−a), a≤x≤b

Example

A random number from 0 to 1 follows Uniform(0,1).

Code example

from scipy.stats import uniform
print(uniform.cdf(.75))

Diagram

Constant density across [a,b]

Key Points

  • A continuous uniform distribution has constant density over an interval.
  • Check assumptions and interpret the result in the context of the data and research question.
Q26Descriptive Statistics & Distributions

Normal distribution

The normal distribution is symmetric and bell-shaped, specified by mean μ and SD σ.

Answer

The normal distribution is symmetric and bell-shaped, specified by mean μ and SD σ.

Syntax

f(x)=exp(−(x−μ)²/(2σ²))/(σ√(2π))

Example

Some measurement errors are approximately normal.

Code example

from scipy.stats import norm
print(norm.cdf(1.96))

Diagram

Bell curve centered at μ

Key Points

  • The normal distribution is symmetric and bell-shaped, specified by mean μ and SD σ.
  • Check assumptions and interpret the result in the context of the data and research question.
Q27Descriptive Statistics & Distributions

Exponential distribution

Exponential models nonnegative waiting time between events in a Poisson process.

Answer

Exponential models nonnegative waiting time between events in a Poisson process.

Syntax

f(x)=λe^(−λx), x≥0

Example

It may model time between requests when assumptions fit.

Code example

from scipy.stats import expon
print(expon.cdf(2,scale=2))

Diagram

Density high near zero then decays

Key Points

  • Exponential models nonnegative waiting time between events in a Poisson process.
  • Check assumptions and interpret the result in the context of the data and research question.
Q28Descriptive Statistics & Distributions

Z-score

A z-score measures how many SDs an observation lies from its mean.

Answer

A z-score measures how many SDs an observation lies from its mean.

Syntax

z=(x−μ)/σ

Example

For x=80, mean=70, SD=5, z=2.

Code example

x,mu,sigma=80,70,5
print((x-mu)/sigma)

Diagram

x → subtract mean → divide by SD

Key Points

  • A z-score measures how many SDs an observation lies from its mean.
  • Check assumptions and interpret the result in the context of the data and research question.
Q29Descriptive Statistics & Distributions

Percentile

The pth percentile is a value at or below which approximately p% of observations fall.

Answer

The pth percentile is a value at or below which approximately p% of observations fall.

Syntax

qₚ=quantile(data,p/100)

Example

The 90th latency percentile is a high-tail service threshold.

Code example

import numpy as np
print(np.percentile([10,20,30,40,100],90))

Diagram

Sort observations → locate quantile

Key Points

  • The pth percentile is a value at or below which approximately p% of observations fall.
  • Check assumptions and interpret the result in the context of the data and research question.
Q30Descriptive Statistics & Distributions

Population vs sample

A population is the target group; a sample is the observed subset used to learn about it.

Answer

A population is the target group; a sample is the observed subset used to learn about it.

Syntax

Parameter: population value; statistic: sample estimate

Example

A poll of 1,000 voters estimates preferences among all eligible voters.

Code example

population=1_000_000; sample=1000
print(sample/population)

Diagram

Population → sampling → sample → inference

Key Points

  • A population is the target group; a sample is the observed subset used to learn about it.
  • Check assumptions and interpret the result in the context of the data and research question.

Intermediate Questions

Implementation details, practical patterns, and common workflows.

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.

Syntax

SE(mean)=s/√n

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.

Syntax

Reject H₀ if p≤α

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.

Syntax

Power=1−β

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.

Syntax

t=d̄/(s_d/√n)

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.

Syntax

χ²=Σ(O−E)²/E

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.

Syntax

ŷ=β₀+β₁x

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.

Syntax

eᵢ=yᵢ−ŷᵢ

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.

Syntax

R²=1−SS_res/SS_tot

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.

Syntax

VIFⱼ=1/(1−Rⱼ²)

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.

Syntax

H₁: −Δ<θ<Δ

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.

Advanced Questions

Architecture, optimization, and design trade-offs.

Q71Advanced Theory & Causal Inference

Confidence interval for a proportion

A proportion interval quantifies uncertainty in a binomial success probability; Wilson often beats the simple Wald interval.

Answer

A proportion interval quantifies uncertainty in a binomial success probability; Wilson often beats the simple Wald interval.

Syntax

Wald: p̂±z√(p̂(1−p̂)/n)

Example

Estimate a conversion rate from 60 successes in 100 trials.

Code example

from statsmodels.stats.proportion import proportion_confint
print(proportion_confint(60,100,method='wilson'))

Diagram

Successes / trials → estimate → interval

Key Points

  • A proportion interval quantifies uncertainty in a binomial success probability; Wilson often beats the simple Wald interval.
  • Check assumptions and interpret the result in the context of the data and research question.
Q72Advanced Theory & Causal Inference

Paired vs independent data

Paired data link measurements or matched units; independent samples contain unrelated units.

Answer

Paired data link measurements or matched units; independent samples contain unrelated units.

Syntax

Paired: analyze differences; independent: compare groups

Example

Before/after measurements on the same users are paired.

Code example

before=[10,12,11]; after=[8,10,9]
print([b-a for b,a in zip(before,after)])

Diagram

Paired unit i ↔ before and after

Key Points

  • Paired data link measurements or matched units; independent samples contain unrelated units.
  • Check assumptions and interpret the result in the context of the data and research question.
Q73Advanced Theory & Causal Inference

Heteroscedasticity

Error variance differs across predictor values or groups.

Answer

Error variance differs across predictor values or groups.

Syntax

Var(ε|X) is not constant

Example

Errors may grow with transaction volume.

Code example

x=range(1,6); residuals=[.1,-.2,.4,-1.5,2.0]
print(list(zip(x,residuals)))

Diagram

Residual spread may widen with fitted values

Key Points

  • Error variance differs across predictor values or groups.
  • Check assumptions and interpret the result in the context of the data and research question.
Q74Advanced Theory & Causal Inference

Residual Q-Q plot

A Q-Q plot compares sample residual quantiles with theoretical normal quantiles.

Answer

A Q-Q plot compares sample residual quantiles with theoretical normal quantiles.

Syntax

Compare sample quantiles to Normal quantiles

Example

Strong curvature can indicate tail or shape departures.

Code example

import matplotlib.pyplot as plt
from scipy import stats
stats.probplot([-2,-1,-.5,0,.2,.5,1,2],dist='norm',plot=plt)
plt.show()

Diagram

Theoretical quantiles ↔ observed quantiles

Key Points

  • A Q-Q plot compares sample residual quantiles with theoretical normal quantiles.
  • Check assumptions and interpret the result in the context of the data and research question.
Q75Advanced Theory & Causal Inference

Robust statistic

A robust statistic is less sensitive to certain outliers or assumption violations.

Answer

A robust statistic is less sensitive to certain outliers or assumption violations.

Syntax

Median is more robust to outliers than mean

Example

For incomes [30,32,35,38,500], median better reflects the center.

Code example

import statistics
x=[30,32,35,38,500]
print(statistics.mean(x),statistics.median(x))

Diagram

Outlier shifts mean more than median

Key Points

  • A robust statistic is less sensitive to certain outliers or assumption violations.
  • Check assumptions and interpret the result in the context of the data and research question.
Q76Advanced Theory & Causal Inference

MCAR, MAR, MNAR

MCAR missingness is unrelated to data; MAR depends on observed data; MNAR depends on missing values/unobserved factors.

Answer

MCAR missingness is unrelated to data; MAR depends on observed data; MNAR depends on missing values/unobserved factors.

Syntax

Missingness mechanism guides assumptions and methods

Example

Survey nonresponse related to unreported spending may be MNAR.

Code example

types={'MCAR':'unrelated','MAR':'observed variables','MNAR':'unobserved/missing values'}
print(types)

Diagram

Data → missingness mechanism → analysis strategy

Key Points

  • MCAR missingness is unrelated to data; MAR depends on observed data; MNAR depends on missing values/unobserved factors.
  • Check assumptions and interpret the result in the context of the data and research question.
Q77Advanced Theory & Causal Inference

Delta method

Approximates uncertainty of a smooth function of an estimator via Taylor expansion.

Answer

Approximates uncertainty of a smooth function of an estimator via Taylor expansion.

Syntax

Var[g(θ̂)]≈[g′(θ)]²Var(θ̂)

Example

Approximate SE of logit(p) from SE(p).

Code example

p,se=.4,.02
print(se/(p*(1-p)))

Diagram

Estimator → linearize transform → approximate SE

Key Points

  • Approximates uncertainty of a smooth function of an estimator via Taylor expansion.
  • Check assumptions and interpret the result in the context of the data and research question.
Q78Advanced Theory & Causal Inference

Fisher information

Fisher information measures expected curvature of log-likelihood and information about a parameter.

Answer

Fisher information measures expected curvature of log-likelihood and information about a parameter.

Syntax

I(θ)=E[(∂ log f/∂θ)²]

Example

For one Bernoulli observation, information for p is 1/[p(1−p)].

Code example

p=.5
print(1/(p*(1-p)))

Diagram

Likelihood curvature → information → precision

Key Points

  • Fisher information measures expected curvature of log-likelihood and information about a parameter.
  • Check assumptions and interpret the result in the context of the data and research question.
Q79Advanced Theory & Causal Inference

Cramér–Rao lower bound

Under regularity conditions, an unbiased estimator variance is bounded below by inverse Fisher information.

Answer

Under regularity conditions, an unbiased estimator variance is bounded below by inverse Fisher information.

Syntax

Var(θ̂)≥1/Iₙ(θ)

Example

For n Bernoulli observations, Iₙ(p)=n/[p(1−p)].

Code example

n,p=100,.5
print(1/(n/(p*(1-p))))

Diagram

More information → lower variance bound

Key Points

  • Under regularity conditions, an unbiased estimator variance is bounded below by inverse Fisher information.
  • Check assumptions and interpret the result in the context of the data and research question.
Q80Advanced Theory & Causal Inference

Exponential family

A family expressible in a common density form supports useful estimation and Bayesian results.

Answer

A family expressible in a common density form supports useful estimation and Bayesian results.

Syntax

f(x|η)=h(x)exp(ηᵀT(x)−A(η))

Example

Bernoulli, Poisson, and normal models can be expressed as exponential families.

Code example

families=['Bernoulli','Binomial','Poisson','Normal']
print(', '.join(families))

Diagram

Sufficient statistic + natural parameter + normalizer

Key Points

  • A family expressible in a common density form supports useful estimation and Bayesian results.
  • Check assumptions and interpret the result in the context of the data and research question.
Q81Advanced Theory & Causal Inference

Sufficient statistic

A statistic is sufficient if it retains all sample information about a parameter under the model.

Answer

A statistic is sufficient if it retains all sample information about a parameter under the model.

Syntax

Factorization: f(x|θ)=g(T(x),θ)h(x)

Example

The success count is sufficient for p in Bernoulli trials.

Code example

x=[1,0,1,1,0]
print(sum(x))

Diagram

Raw data → sufficient statistic → inference

Key Points

  • A statistic is sufficient if it retains all sample information about a parameter under the model.
  • Check assumptions and interpret the result in the context of the data and research question.
Q82Advanced Theory & Causal Inference

Method of moments

Estimates parameters by equating sample moments with theoretical moments.

Answer

Estimates parameters by equating sample moments with theoretical moments.

Syntax

Sample moment = theoretical moment

Example

For Bernoulli data, equating means estimates p by success proportion.

Code example

x=[1,0,1,1,0]
print(sum(x)/len(x))

Diagram

Sample moments = theoretical moments → solve

Key Points

  • Estimates parameters by equating sample moments with theoretical moments.
  • Check assumptions and interpret the result in the context of the data and research question.
Q83Advanced Theory & Causal Inference

Bias–variance trade-off

Prediction error often reflects squared bias, variance, and irreducible noise.

Answer

Prediction error often reflects squared bias, variance, and irreducible noise.

Syntax

E[(Y−f̂(X))²]≈Bias²+Variance+Noise

Example

A simple model may underfit; a flexible one may vary greatly across samples.

Code example

parts={'bias_squared':.12,'variance':.18,'noise':.20}
print(sum(parts.values()))

Diagram

Complexity ↑ → bias often ↓; variance often ↑

Key Points

  • Prediction error often reflects squared bias, variance, and irreducible noise.
  • Check assumptions and interpret the result in the context of the data and research question.
Q84Advanced Theory & Causal Inference

Regularization

Regularization penalizes model complexity to improve stability or generalization.

Answer

Regularization penalizes model complexity to improve stability or generalization.

Syntax

Ridge: loss+λΣβ²; Lasso: loss+λΣ|β|

Example

Ridge shrinks coefficients, often helping with correlated predictors.

Code example

from sklearn.linear_model import Ridge
m=Ridge(alpha=1).fit([[1,2],[2,1],[3,4],[4,3]],[2,3,6,7])
print(m.coef_)

Diagram

Data loss + penalty λ → fitted parameters

Key Points

  • Regularization penalizes model complexity to improve stability or generalization.
  • Check assumptions and interpret the result in the context of the data and research question.
Q85Advanced Theory & Causal Inference

Generalized linear model

A GLM combines a response distribution, linear predictor, and link function.

Answer

A GLM combines a response distribution, linear predictor, and link function.

Syntax

g(E[Y|X])=Xβ

Example

Logistic regression uses logit; Poisson regression commonly uses log link.

Code example

import statsmodels.api as sm
print('GLM = response family + link + linear predictor')

Diagram

Xβ → link → expected response

Key Points

  • A GLM combines a response distribution, linear predictor, and link function.
  • Check assumptions and interpret the result in the context of the data and research question.
Q86Advanced Theory & Causal Inference

Poisson regression and offset

Poisson regression models counts; an offset adjusts for exposure differences.

Answer

Poisson regression models counts; an offset adjusts for exposure differences.

Syntax

log(E[Y|X])=Xβ+log(exposure)

Example

Model incidents per user-month with log exposure as offset.

Code example

counts=[4,8,5]; exposure=[10,20,10]
print([c/e for c,e in zip(counts,exposure)])

Diagram

Counts + exposure → rate model

Key Points

  • Poisson regression models counts; an offset adjusts for exposure differences.
  • Check assumptions and interpret the result in the context of the data and research question.
Q87Advanced Theory & Causal Inference

Overdispersion

Overdispersion means observed variance exceeds a model's assumed variance.

Answer

Overdispersion means observed variance exceeds a model's assumed variance.

Syntax

Poisson: Var(Y|X)=E[Y|X]

Example

Ticket counts may vary more than Poisson allows.

Code example

import statistics
x=[0,0,1,2,10,12]
print(statistics.mean(x),statistics.pvariance(x))

Diagram

Observed variance > modeled variance

Key Points

  • Overdispersion means observed variance exceeds a model's assumed variance.
  • Check assumptions and interpret the result in the context of the data and research question.
Q88Advanced Theory & Causal Inference

Mixed-effects model

Mixed models include population-level fixed effects and group-specific random effects.

Answer

Mixed models include population-level fixed effects and group-specific random effects.

Syntax

yᵢⱼ=Xᵢⱼβ+Zᵢⱼbⱼ+εᵢⱼ

Example

Repeated measurements nested in patients may share group-level variation.

Code example

formula='outcome ~ treatment + (1 | group)'
print(formula)

Diagram

Group → random effect → correlated group observations

Key Points

  • Mixed models include population-level fixed effects and group-specific random effects.
  • Check assumptions and interpret the result in the context of the data and research question.
Q89Advanced Theory & Causal Inference

Survival analysis

Models time to an event while handling censored observations.

Answer

Models time to an event while handling censored observations.

Syntax

S(t)=P(T>t); hazard is instantaneous event rate conditional on survival

Example

Analyze churn time when some customers remain active at study end.

Code example

durations=[5,8,10]; event_observed=[1,0,1]
print(list(zip(durations,event_observed)))

Diagram

Follow-up → event or censoring → survival curve

Key Points

  • Models time to an event while handling censored observations.
  • Check assumptions and interpret the result in the context of the data and research question.
Q90Advanced Theory & Causal Inference

Kaplan–Meier estimator

Estimates survival as a product of conditional survival fractions at observed event times.

Answer

Estimates survival as a product of conditional survival fractions at observed event times.

Syntax

Ŝ(t)=∏(1−dᵢ/nᵢ)

Example

Estimate customer retention over time with right-censoring.

Code example

risk_set,events=100,5
print(1-events/risk_set)

Diagram

At risk nᵢ → events dᵢ → survival step

Key Points

  • Estimates survival as a product of conditional survival fractions at observed event times.
  • Check assumptions and interpret the result in the context of the data and research question.
Q91Advanced Theory & Causal Inference

Cox proportional hazards model

Relates predictors to a hazard via baseline hazard and exponentiated linear predictor.

Answer

Relates predictors to a hazard via baseline hazard and exponentiated linear predictor.

Syntax

h(t|X)=h₀(t)exp(Xβ)

Example

Estimate association between a product change and churn hazard.

Code example

hazard_ratio=1.25
print(f'{(hazard_ratio-1)*100:.0f}% higher hazard')

Diagram

Baseline hazard × exp(Xβ) → hazard

Key Points

  • Relates predictors to a hazard via baseline hazard and exponentiated linear predictor.
  • Check assumptions and interpret the result in the context of the data and research question.
Q92Advanced Theory & Causal Inference

Markov chain

A Markov chain models transitions where the next state depends on the current state conditional on the present.

Answer

A Markov chain models transitions where the next state depends on the current state conditional on the present.

Syntax

P(Xₜ₊₁=j|Xₜ=i,past)=Pᵢⱼ

Example

Customers can transition between Free, Paid, and Churned states.

Code example

import numpy as np
P=np.array([[.7,.2,.1],[.1,.8,.1],[0,0,1]])
print(P.sum(axis=1))

Diagram

States → transition matrix → next state

Key Points

  • A Markov chain models transitions where the next state depends on the current state conditional on the present.
  • Check assumptions and interpret the result in the context of the data and research question.
Q93Advanced Theory & Causal Inference

Monte Carlo simulation

Monte Carlo approximates quantities by repeated random sampling.

Answer

Monte Carlo approximates quantities by repeated random sampling.

Syntax

E[g(X)]≈(1/N)Σg(Xᵢ)

Example

Estimate π by sampling points in a square and counting those in a quarter circle.

Code example

import random
random.seed(1); N=20000
inside=sum(random.random()**2+random.random()**2<=1 for _ in range(N))
print(4*inside/N)

Diagram

Model → simulate many outcomes → summarize

Key Points

  • Monte Carlo approximates quantities by repeated random sampling.
  • Check assumptions and interpret the result in the context of the data and research question.
Q94Advanced Theory & Causal Inference

Randomization test

Uses the assignment mechanism to construct a reference distribution under a sharp null.

Answer

Uses the assignment mechanism to construct a reference distribution under a sharp null.

Syntax

Reassign treatment as design permits → recompute statistic

Example

Permute treatment labels in a randomized trial.

Code example

import numpy as np
r=np.random.default_rng(9)
print(r.permutation([1,1,0,0]))

Diagram

Observed assignment → allowable assignments → null distribution

Key Points

  • Uses the assignment mechanism to construct a reference distribution under a sharp null.
  • Check assumptions and interpret the result in the context of the data and research question.
Q95Advanced Theory & Causal Inference

Instrumental variable

An instrument can identify a causal effect under relevance, exclusion, and independence assumptions.

Answer

An instrument can identify a causal effect under relevance, exclusion, and independence assumptions.

Syntax

Two-stage least squares: treatment~instrument; outcome~predicted treatment

Example

Policy eligibility may influence treatment uptake without directly affecting the outcome, if assumptions hold.

Code example

steps=['1st: treatment ~ instrument + covariates','2nd: outcome ~ predicted treatment + covariates']
print('\n'.join(steps))

Diagram

Instrument Z → treatment D → outcome Y

Key Points

  • An instrument can identify a causal effect under relevance, exclusion, and independence assumptions.
  • Check assumptions and interpret the result in the context of the data and research question.
Q96Evaluation & Reporting

Difference-in-differences

Compares before-after change in treated group with change in comparison group.

Answer

Compares before-after change in treated group with change in comparison group.

Syntax

DiD=(T_after−T_before)−(C_after−C_before)

Example

Evaluate a policy using treated and comparison regions.

Code example

tb,ta,cb,ca=10,15,8,10
print((ta-tb)-(ca-cb))

Diagram

Treated change − control change → DiD

Key Points

  • Compares before-after change in treated group with change in comparison group.
  • Check assumptions and interpret the result in the context of the data and research question.
Q97Evaluation & Reporting

Causal DAG

A directed acyclic graph represents assumed causal relationships without directed cycles.

Answer

A directed acyclic graph represents assumed causal relationships without directed cycles.

Syntax

Arrows encode hypothesized causal directions

Example

Age may affect both treatment choice and outcome.

Code example

print('Age → Treatment\nAge → Outcome\nTreatment → Outcome')

Diagram

Age → Treatment → Outcome; Age → Outcome

Key Points

  • A directed acyclic graph represents assumed causal relationships without directed cycles.
  • Check assumptions and interpret the result in the context of the data and research question.
Q98Evaluation & Reporting

Collider bias

Conditioning on a common effect of two variables can induce a spurious association between those causes.

Answer

Conditioning on a common effect of two variables can induce a spurious association between those causes.

Syntax

A→C←B; conditioning on C may associate A and B

Example

Among hospitalized patients, unrelated causes of admission can appear associated.

Code example

print('A → C ← B; conditioning on C can induce association')

Diagram

A → C ← B; C is collider

Key Points

  • Conditioning on a common effect of two variables can induce a spurious association between those causes.
  • Check assumptions and interpret the result in the context of the data and research question.
Q99Evaluation & Reporting

Prediction vs inference

Prediction targets performance on new cases; inference targets relationships, effects, and uncertainty.

Answer

Prediction targets performance on new cases; inference targets relationships, effects, and uncertainty.

Syntax

Prediction: held-out loss; inference: estimates and intervals

Example

A boosted tree may predict churn well but offer less direct coefficient interpretation.

Code example

goals={'prediction':'held-out error','inference':'estimates and uncertainty'}
print(goals)

Diagram

Data → model → predictions or parameter interpretation

Key Points

  • Prediction targets performance on new cases; inference targets relationships, effects, and uncertainty.
  • Check assumptions and interpret the result in the context of the data and research question.
Q100Evaluation & Reporting

Cross-validation

Cross-validation estimates generalization by training and validating across folds.

Answer

Cross-validation estimates generalization by training and validating across folds.

Syntax

K-fold CV = average held-out metric over K folds

Example

Use five-fold CV to compare predictive models.

Code example

from sklearn.model_selection import cross_val_score,KFold
from sklearn.linear_model import LinearRegression
import numpy as np
X=np.arange(20).reshape(-1,1); y=2*X.ravel()+np.sin(X.ravel())
cv=KFold(n_splits=5,shuffle=True,random_state=1)
print(cross_val_score(LinearRegression(),X,y,cv=cv).mean())

Diagram

Split folds → fit K times → aggregate scores

Key Points

  • Cross-validation estimates generalization by training and validating across folds.
  • Check assumptions and interpret the result in the context of the data and research question.

Share this question bank

Send this page to someone preparing for an interview.