Inferencia y A/B testing
Hypothesis testing, p-value, potencia y MDE
Inferencia estadística es responder preguntas sobre poblaciones usando datos de muestras. Nunca sabrás con certeza absoluta si un cambio funciona — pero puedes cuantificar tu confianza. A/B testing es la forma práctica de inferencia en negocios: divides usuarios al azar en dos grupos (A=control, B=tratamiento), ejecutas el experimento, y mides si B es significativamente mejor que A.
Un test de hipótesis es una afirmación falsable. Hipótesis nula (H0) es lo que asumes 'por defecto' (ej. 'el nuevo botón no cambia conversiones'). Hipótesis alternativa (H1) es lo que esperas probar (ej. 'el nuevo botón aumenta conversiones'). Ejecutas el experimento, calculas una estadística de test (ej. t-statistic), y decides si rechazas H0 o no.
El p-value es la probabilidad de observar datos TAN EXTREMOS O MÁS si H0 fuera verdadera. Si p < 0.05, es raro ver estos datos bajo H0, así que rechazas H0. Pero p=0.05 es ARBITRARIO — es una convención que significa '5% de chance de falso positivo'. No es la 'probabilidad de que H0 sea verdadera'; eso requiere Bayes.
Errores Tipo I y Tipo II: error Tipo I (falso positivo, α) es rechazar H0 cuando es verdadera (p<0.05 no significa que realmente haya efecto). Error Tipo II (falso negativo, β) es no rechazar H0 cuando es falsa (no detectas un efecto real que existe). Potencia = 1 - β = capacidad de detectar efecto real. Quieres potencia alta (80%+ típicamente).
Minimum Detectable Effect (MDE) es el tamaño del efecto más pequeño que tu experimento puede detectar con una cierta potencia. Si esperas cambio de 1% en conversión pero tu experimento solo detecta cambios de 5%, desperdiciaste tiempo. MDE depende del tamaño de muestra, varianza, potencia deseada y α. Más muestra = MDE más pequeño = puedes detectar efectos menores.
Intervalos de confianza cuantifican incertidumbre: 'el verdadero efecto está entre X y Y con 95% confianza'. Es más útil que p-values porque te dice magnitud, no solo significancia. Un intervalo de confianza que no incluye 0 indica significancia estadística. Es importante pensar en magnitud práctica: un efecto estadísticamente significativo (p<0.05) podría ser demasiado pequeño para importar en negocio.
# Hypothesis Testing & A/B Testing with scipy.stats
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
# === SIMPLE T-TEST (compare two groups) ===
np.random.seed(42)
control = np.random.normal(loc=100, scale=15, size=100) # group A
treatment = np.random.normal(loc=105, scale=15, size=100) # group B (slightly higher mean)
t_stat, p_value = stats.ttest_ind(control, treatment)
print(f't-statistic: {t_stat:.3f}, p-value: {p_value:.4f}')
print(f'Reject H0: {p_value < 0.05}') # if p<0.05, difference is significant
# === CONFIDENCE INTERVAL (range of plausible values) ===
effect = np.mean(treatment) - np.mean(control) # observed difference
se = np.sqrt((np.var(control)/len(control)) + (np.var(treatment)/len(treatment))) # standard error
ci_lower = effect - 1.96 * se # 95% confidence interval
ci_upper = effect + 1.96 * se
print(f'Effect: {effect:.2f} [95% CI: {ci_lower:.2f}, {ci_upper:.2f}]')
print(f'Significant: {ci_lower > 0}') # if lower bound > 0, p<0.05
# === CHI-SQUARE TEST (for categorical data) ===
# A/B test: conversions in control vs treatment
conversions_A = 50 # out of 1000
conversions_B = 70 # out of 1000
n_A, n_B = 1000, 1000
# Contingency table
contingency = np.array([
[conversions_A, n_A - conversions_A], # [conversions, no-conversions] in A
[conversions_B, n_B - conversions_B] # [conversions, no-conversions] in B
])
chi2, p_value, dof, expected = stats.chi2_contingency(contingency)
print(f'Chi-square: {chi2:.3f}, p-value: {p_value:.4f}')
# === POWER ANALYSIS (sample size planning) ===
from scipy.stats import norm
# Inputs: baseline conversion, expected lift, alpha, power
baseline_cr = 0.05 # 5% conversion rate (control)
expected_lift = 0.20 # expect 20% relative lift (5% → 6%)
target_cr = baseline_cr * (1 + expected_lift) # 6%
alpha = 0.05
power = 0.80
# Effect size (Cohen's h for proportions)
h = 2 * (np.arcsin(np.sqrt(target_cr)) - np.arcsin(np.sqrt(baseline_cr)))
z_alpha = norm.ppf(1 - alpha/2) # two-sided
z_beta = norm.ppf(power)
n_per_group = ((z_alpha + z_beta) / h) ** 2 # sample size per group
print(f'Sample size needed: {n_per_group:.0f} per group ({2*n_per_group:.0f} total)')
# === MINIMUM DETECTABLE EFFECT (MDE) ===
# Given a sample size, what is the smallest effect you can detect?
n = 500 # sample size per group
h_achieved = (z_alpha + z_beta) / np.sqrt(n)
# Convert h back to conversion rate difference
print(f'MDE (as effect size h): {h_achieved:.3f}')
# === TYPE I & TYPE II ERRORS ===
print(f'Type I error (α): {alpha} (false positive rate)')
print(f'Type II error (β): {1 - power} (false negative rate)')
print(f'Power (1 - β): {power} (true positive rate)')Katas (4)
Debugging lab
Detecta y corrige el error en el código.
- 1.10.5.1
control = np.random.normal(100, 15, 100) treatment = np.random.normal(101, 15, 100) # tiny effect t_stat, p_value = stats.ttest_ind(control, treatment) if p_value < 0.05: print('Significant! The treatment works!') else: print('No effect')
- 1.10.5.2
# Peekng at results mid-experiment for day in range(1, 31): data_so_far = collect_data_for_n_days(day) t_stat, p_value = stats.ttest_ind(data_so_far['A'], data_so_far['B']) if p_value < 0.05: print(f'Stop! Significant on day {day}') # stop when p<0.05
- 1.10.5.3
# Confuse Type I and Type II print('α = 0.05 means Type I error = 5%') print('Power = 0.80 means Type II error = 80%') # WRONG
- 1.10.5.4
# Chi-square on continuous data values_A = np.random.normal(100, 15, 100) values_B = np.random.normal(105, 15, 100) contingency = np.array([[np.mean(values_A)], [np.mean(values_B)]]) chi2, p_value = stats.chi2_contingency(contingency) # wrong!
- 1.10.5.5
# Run experiment without calculating sample size print('Let\'s run an A/B test. We\'ll collect data for 1 week.') # Collect for 1 week, then analyze results = analyze_ab_test(data_1_week) if results['p_value'] < 0.05: print('Significant!') else: print('Not significant — try again next week')
- 1.10.5.6
# Misinterpret confidence interval ci_lower, ci_upper = 95, 105 # 95% CI for treatment effect print(f'There is a 95% probability that true effect is between {ci_lower} and {ci_upper}') # misinterpretation