[Datacamp] Hypothesis tests and z-scores (1)
Introduction
A/B testing
2013년, 게임사 EA에서는 출시된 게임의 사전예약 건수를 높이기 위해서 두 가지 광고 전략을 세웁니다. contrl group/treament group으로 케이스를 나누어 유저들에게 어떤 광고가 더 잘 먹히는지 관찰하는 것을 A/B testing이라고 합니다.
하지만, A/B testing을 통해 얻은 결론이 단순히 우연의 일치일지 혹은 통계적으로 유의미한 값인지 검증하는 과정도 필요합니다. 이번 챕터에서는 이런 검증 과정에 대해 배워봤습니다.
#generating a bootstrap distribution
import numpy as np
boot_dist = []
for i in range(5000): #the number of samplings
boot_dist.append(
np.mean( df.sample(frac=1, replace=True)['col_name'])
)
#add the mean of sampled dataset
mean_of_sample을 df.['col_name']의 평균이라고 할 때, Z-score를 구하는 공식은 아래와 같습니다.
#Calculating standard error and Z-score
std_error = np.std(boot_dist, ddof=1)
z_score = (mean_of_sample - mean_hypothesis) / std_error
P-values
- 단어 정의
- hypothesis : 특정 파라미터에 대한 서술
- null hypothesis($H_0$) : existing idea, 기존에 존재하던 가설, 귀무 가설
- alternative hypothesis($H_A$) : the new challenger idea of the reseracher, 새로운 가설, 대립 가설
- p-value : 귀무 가설이 참임을 전제로 결과를 얻을 확률 - 1에 가까울수록 (검정색에 속할 수록) 귀무가설을 지지
- two-tailed, right-tailed, left- tailed test로 구분 가능
Statistical significance
대립 가설을 채택할 임계점, threshold point for beyond a reasonable doubt, $ \alpha $로 표기합니다.
$ 1- \alpha $가 우리에게 익숙한 개념인 confidence interval, 즉 신뢰도입니다.
Performing T-tests
T-test
Two-sample problems, 즉 한 변수 안의 그룹 간의 통계량을 비교하는 방법입니다. 수업 내용에서는 코딩을 14세 이전에 시작한 그룹과 이후에 시작한 그룹을 나누어, 그룹 간 연봉 비교를 통해 코딩을 일찍 배운 것이 높은 연봉에 영향을 미쳤는지 확인했습니다.
Workflow of hypothesis testing
- Identify population parameter that is hypothesized about. 가설을 세울 파라미터 정하기.
- Specify the null and altenative hypotheses. 귀무 가설과 대립 가설 구체화하기.
- Determine standardized test statistic and corresponding null distribution. 실험할 통계적 지표 결정하기.
- Conduct hypothesis test in Python. 실험 진행하기.
- Measure evidence against the null hypothesis. 귀무 가설을 기각할 지표 측정하기.
- Make a decision comparing evidence to significance level. 신뢰 구간과 비교하여 결정하기.
- Interpret the results in the context of the original problem. 실제 문제의 맥락에서 결과 해석하기.
t-distributions
t statistic은 t 분포를 따릅니다. t-statistic은 모집단을 추측하기 위해서 여러 개의 sample statistic이 필요한 경우입니다. (e.g mean, std. 한 개만 사용하는 경우 z-statistic) 표본표준편차를 사용해 standard error를 추측할 때 t-distribution이 사용됩니다.
위에서 언급된 코딩을 유년기에 시작한 그룹/아닌 그룹 두 개의 표본평균을 사용하는 경우 t-statistic을 위한 수식은 아래와 같습니다.
$ \frac {\overline{X_{group1}} - \overline{X_{group2}}} {\sqrt{ \frac{std_{group1} ^ 2} {n_{group1}} + \frac{std_{group2} ^2} {n_{group2}}} }$
*분모는 근사치입니다.
Paried t-test
'data is paired'의 의미는 데이터가 독립적이지 않다, 즉 사건이 서로에게 영향을 미친다는 뜻입니다.
우리는 pingouin 패키지를 통해 hypothesis testing을 간단하게 수행하고, 결과를 데이터프레임으로 받아올 수 있습니다. 앞에 수업시간에 표본통계량을 구하고, z-score 공식에 맞춰 계산하고, cdf 함수에 넣어 값을 계산했었거든요. 파이썬을 배우면서 느낀 한 가지는 '이걸 한 번에 하는 툴은 없나'라고 생각이 든다면 보통 이미 있다는 점입니다. 제가 모를 뿐..
#how to perform hypothesis testing with pingouin package
import pingouin
pingouin.ttest(x=sample_data['diff'], #values for test
y=0, #hypothesized value from null hypothesis
alternative='less', #two-sided, less, greater due to the problem
#paired=False, #default, but if datasets are paired, change to True
)
paired data set에 unpaired t-test를 적용하면 FN error가 발생할 확률이 높아집니다.
ANOVA test
그런데, 두 개 이상의 카테고리로 이루어진 데이터셋은 어떻게 다뤄야 할까요? ANOVA 테스트는 그룹 간 비교를 위한 테스트입니다.
#set significance level
alpha=0.2
#set a test easily
anova_result = pingouin.anova(data=data,
dv=dependent_variable, #종속 변수
between=column_of_multiple_groups #그룹화하여 결과를 볼 컬럼
)
실습 예제에서 anova_results를 출력했을 때, 아래와 같은 결과를 얻을 수 있습니다. 대립 가설을 선택하기 위해 확인하는 지표인 p 값은 p-unc에서 확인할 수 있습니다.
이렇게 결과를 확인했을 때 적어도 두 개의 그룹은 유의미한 차이가 있다는 점을 알 수 있습니다. 하지만 어떤 두 그룹인지 알지는 못하므로, 모든 카테고리를 한 쌍씩 짝지어 실험해봐야할까요?
아닙니다. 패키지가 준비되어 있습니다.
#perform
pingouin.pairwise_tests(data=data,
dv=dv,
between=, #same as ANOVA tests
padjust='none' #option for false-positive
#bonf, sidak, holm, fdr_bh, fdr_by
)
수업 내용 중 핵심 코드만 타이핑하고 그에 대한 설명을 붙이는 게 생각보다 시간이 많이 걸리네요.. 여기까지가 ch2의 내용입니다. 통계 관련 개념이 많아서 구글링이 많이 필요했던 챕터였습니다. 올해 목표에 통계 강의 한 바퀴 보기를 추가해야겠어요.