Codelog
[AIB] Chi-Square Test 본문
T-test +
t-test는 그룹의 평균값에 대해서 비교하는 가설검정 방법이다.
그러나 사실 t-test를 사용하기 위해서는 몇가지 조건이 가정되어야 한다.
- 독립성 : 두 그룹이 연결되어 있는(paired) 쌍인지
- 등분산성 : 두 그룹이 어느정도 유사한 수준의 분산 값을 가지는지
- 정규성 : 데이터가 정규성을 나타내는지
( 정규성을 확인하는 함수는 scipy 라이브러리에 구현되어있다. -> stats.normaltest() )
만약 정규성을 띄지 않는다면?
모집단이 특정 확률분포를(ex. normal) 따른다는 조건을 가정하지 않는 검정 방식을 채택한다.
→ Non-parametric method (비모수적 방식)
Non-Parametric Methods
모집단이 특정 확률 분포를 따른다는 전제를 하지 않는 방식으로, parameter estimation(모수 추정)을 할 필요가 없다.
- Categorical 데이터를 위한 모델링
- 혹은 극단적 outlier가 있는 경우 매우 유효한 방식
- distribution free method 라고 부르기도 함
( Chisqure, Spearman correlation, Run test, Kolmogorov Smirnov, Mann-Whitney U, Wilcoxon, Kruskal-Wallis 등 )
Kruskal-Wallis Test (비모수적 평균 비교법)
2개 이상의 그룹의 중위 랭크를 통한 차이 비교
from scipy.stats import kruskal
x1 = [1, 3, 4, 8, 9]
y1 = [1, 4, 6, 7, 7]
kruskal(x1, y1)
Output : KruskalResult(statistic=0.01111111111111548, pvalue=0.91605107228188)
약간은 다르지만 "유의한" 차이는 아님
x2 = [12, 15, 18]
y2 = [24, 25, 26]
z = [40, 40]
kruskal(x2, y2, z)
Output : KruskalResult(statistic=6.325301204819277, pvalue=0.042313436212501186)
서로 같다고 볼 수 없음, 3번째 그룹은 사이즈가 다름
Non-Parametric Method는 Categorical data를 이용하지만 Numerical data를 이용할 때도 있기 때문에
Numerical data를 Categorical data로 변환시켜서 사용한다.
1. Type casting
numerical 이지만, continuous하지 않아서 바로 category로 사용할 수 있는 경우
ex) 1, 2, 3 → 1, 2, 3
2. Binning
numerical 이지만, continuous해서 구간별로 나누어 사용해야 하는 경우
ex) 1.4, 2, 3.1, 2.8, 1.5 -> A: 1~2, B: 2~3, C: 3~4
Chisquare Test
1. One sample Chisquare test
주어진 데이터가 특정 예상되는 분포와 동일한 분포를 나타내는지에 대한 가설검정 방법
주어진 데이터가 균등한 분포를 나타내고 있는지 확인
Null Hypothesis = Distribution is similar ( or specific input )
Alternative Hypothesis = Distribution is not similar ( or speecific input )
통계치는 data의 scale에 따라서 영향을 많이 받는다.
예를 들어 x1=[10, 11, 10, 12, 10, 11] 과 x2=[1000, 1100, 1000, 1200, 1000, 1100] 의 분산은 똑같지만
데이터의 scale이 더 큰 x2의 Chisquare 값이 더 크게 나온다.
따라서 표준화된 값이 필요하다. ( Statistics → P-value )
( 이는 scipy 라이브러리에 구현되어 있다. -> stats.chi2.cdf() or stats.chi2.sf() )
chisquare value를 p-value로 표준화하기
from scipy import stats
x2 = 0.00139
pval = 1 - stats.chi2.cdf(x2, df=1) # 자유도=1
# 같은 결과
pval = stats.chi2.sf(x2, df=1)
Output :
0.9702595963009745
Chisquare 예시
import numpy as np
form scipy.stats import chisquare
s_obs = np.array([18, 22, 20, 15, 23, 22]) # Similar
chisquare(s_obs, axis=None) # One sample chi-square test
Output :
Power_divergenceResult(statistic=2.3000000000000003, pvalue=0.8062668698851285)
ns_obs = np.array([[5, 23, 26, 19, 24, 23]]) # Not Similar
chisquare(ns_obs, axis=None)
Output :
Power_divergenceResult(statistic=14.8, pvalue=0.011251979028327346)
2. Two sample Chisquare test
2개의 데이터가 연관이 있는지 확인
Null Hypothesis = Variable is independent
Alternative Hypothesis = Variable is not independent ( or specific input )
import numpy as np
from scipy.stats import chi2_contingency
obs = np.array([[9,2], [13,3]])
chi2_contingency(obs) # Two sample chi-square test
# correction 파라미터가 True로 설정 : Yates' correction 시행함
Output :
(0.0013946280991735537, 0.9702101490749658, 1, array([[ 8.96296296, 2.03703704], [13.03703704, 2.96296296]]))
"scipy.stats.chi2_contingency" return value
1 : x^2-statistic 2 : p-value 3 : degree of freedom 4 : expected value for observed
Degrees of Freedom (자유도)
해당 parameter를 결정짓기 위한 독립적으로 정해질 수 있는 값의 수
주어진 조건 아래에서 통계적 제한을 받지 않고 자유롭게 변화할 수 있는 요소의 수
- 1-sample (적합도 검정) : df = #categories - 1
- 2-sample (독립성 검정) : df = (#rows - 1) * (#columns - 1)
'Boot Camp > section1' 카테고리의 다른 글
[AIB] Confidence Intervals (0) | 2021.11.02 |
---|---|
Type of Error (TP, TN, FP, FN) (0) | 2021.10.10 |
[AIB] Hypothesis Test (0) | 2021.10.09 |
[AIB] Data Manipulation (0) | 2021.10.01 |
[AIB] Feature Engineering (0) | 2021.09.27 |