카이제곱 독립성 검정

Python으로 배우는 가설 검정

James Chapman

Curriculum Manager, DataCamp

비율 검정 복습

age_by_hobbyist = stack_overflow.groupby("age_cat")['hobbyist'].value_counts()
age_cat      hobbyist
At least 30  Yes          812
             No           238
Under 30     Yes         1021
             No           190
Name: hobbyist, dtype: int64
from statsmodels.stats.proportion import proportions_ztest
n_hobbyists = np.array([812, 1021])
n_rows = np.array([812 + 238, 1021 + 190])
stat, p_value = proportions_ztest(count=n_hobbyists, nobs=n_rows, 
                                  alternative="two-sided")
(-4.223691463320559, 2.403330142685068e-05)
Python으로 배우는 가설 검정

변수의 독립성

이전 가설 검정 결과: hobbyistage_cat이 연관되어 있다는 증거

통계적 독립성 - 반응 변수의 성공 비율이 설명 변수의 모든 범주에 걸쳐 동일함

Python으로 배우는 가설 검정

변수 독립성 검정

import pingouin
expected, observed, stats = pingouin.chi2_independence(data=stack_overflow, x='hobbyist',
                                                       y='age_cat', correction=False)
print(stats)
                 test    lambda       chi2  dof      pval    cramer     power
0             pearson  1.000000  17.839570  1.0  0.000024  0.088826  0.988205
1        cressie-read  0.666667  17.818114  1.0  0.000024  0.088773  0.988126
2      log-likelihood  0.000000  17.802653  1.0  0.000025  0.088734  0.988069
3       freeman-tukey -0.500000  17.815060  1.0  0.000024  0.088765  0.988115
4  mod-log-likelihood -1.000000  17.848099  1.0  0.000024  0.088848  0.988236
5              neyman -2.000000  17.976656  1.0  0.000022  0.089167  0.988694

$\chi^2$ 통계량 = 17.839570 = $(-4.223691463320559)^2$ = ($z$-점수)$^2$

Python으로 배우는 가설 검정

직업 만족도와 연령 범주

stack_overflow['age_cat'].value_counts()
Under 30       1211
At least 30    1050
Name: age_cat, dtype: int64
stack_overflow['job_sat'].value_counts()
Very satisfied           879
Slightly satisfied       680
Slightly dissatisfied    342
Neither                  201
Very dissatisfied        159
Name: job_sat, dtype: int64
Python으로 배우는 가설 검정

가설 설정

$H_{0}$: 연령 범주와 직업 만족도 수준은 독립적입니다

$H_{A}$: 연령 범주와 직업 만족도 수준은 독립적이지 않습니다

alpha = 0.1
  • 검정 통계량: $\chi^{2}$
  • 독립성을 가정할 때, 관측값이 기댓값에서 얼마나 벗어나는가?
Python으로 배우는 가설 검정

탐색적 시각화: 비율 누적 막대 그래프

props = stack_overflow.groupby('job_sat')['age_cat'].value_counts(normalize=True)

wide_props = props.unstack()
wide_props.plot(kind="bar", stacked=True)
Python으로 배우는 가설 검정

탐색적 시각화: 비율 누적 막대 그래프

연령 범주별로 채워진 직업 만족도의 비율 누적 막대 그래프

Python으로 배우는 가설 검정

카이제곱 독립성 검정

import pingouin
expected, observed, stats = pingouin.chi2_independence(data=stack_overflow, x="job_sat", y="age_cat")
print(stats)    
                 test    lambda      chi2  dof      pval    cramer     power
0             pearson  1.000000  5.552373  4.0  0.235164  0.049555  0.437417
1        cressie-read  0.666667  5.554106  4.0  0.235014  0.049563  0.437545
2      log-likelihood  0.000000  5.558529  4.0  0.234632  0.049583  0.437871
3       freeman-tukey -0.500000  5.562688  4.0  0.234274  0.049601  0.438178
4  mod-log-likelihood -1.000000  5.567570  4.0  0.233854  0.049623  0.438538
5              neyman -2.000000  5.579519  4.0  0.232828  0.049676  0.439419

자유도:

$(\text{반응 변수 범주 수} - 1) \times (\text{설명 변수 범주 수} - 1)$

$(2 - 1) * (5 - 1) = 4$

Python으로 배우는 가설 검정

변수 순서를 바꾸면?

props = stack_overflow.groupby('age_cat')['job_sat'].value_counts(normalize=True)
wide_props = props.unstack()
wide_props.plot(kind="bar", stacked=True)
Python으로 배우는 가설 검정

변수 순서를 바꾸면?

직업 만족도별로 채워진 연령 범주의 비율 누적 막대 그래프

Python으로 배우는 가설 검정

카이제곱: 양방향 모두

expected, observed, stats = pingouin.chi2_independence(data=stack_overflow, x="age_cat", y="job_sat")
print(stats[stats['test'] == 'pearson'])   
      test  lambda      chi2  dof      pval    cramer     power
0  pearson     1.0  5.552373  4.0  0.235164  0.049555  0.437417

질문: 변수 X와 Y는 독립적인가?

아님: 변수 X는 변수 Y와 독립적인가?

Python으로 배우는 가설 검정

방향과 꼬리는 어떻게 되나요?

  • 관측 및 기댓값의 제곱은 음수가 될 수 없습니다
  • 카이제곱 검정은 거의 항상 오른쪽 꼬리 검정입니다 $^{1}$
1 왼쪽 꼬리 카이제곱 검정은 데이터가 조작되었을 때 적합도가 의심스러울 정도로 높은지 탐지하기 위한 통계 포렌식에서 사용됩니다. 분산에 대한 카이제곱 검정은 양측 검정일 수 있습니다. 그러나 이는 특수한 사용 사례입니다.
Python으로 배우는 가설 검정

연습해 봅시다!

Python으로 배우는 가설 검정

Preparing Video For Download...