Certificate/data analytics-Google

[Hypothesis test] Python, scipy.ttest_ind(), scipy.ttest_1sample()

Olivia-BlackCherry 2023. 7. 20. 13:19

목차

    문제 상황

    서로 다른 구역에서 문맹률 차이가 나는데, 이것은 우연적인 것일까 아니면 통계적으로 유의미한 상황인 것일까?

    <데이터>

    DistName에서 구역을 알 수 있고, Overall_li에서 문맹률을 알 수 있다.

     

     

    1. 통계 라이브러리 가져오기

    import pandas as pd
    from scipy import stats

     

     

    2. 데이터 전처리

    - isna(), dropna()---> null값 처리

    - state21, state28인 행만 추출한다. 

    state21 = education_districtwise[education_districtwise['STATNAME'] == "STATE21"]
    state28 = education_districtwise[education_districtwise['STATNAME'] == "STATE28"]

     

     

    3. 샘플링 sample()

    n 개수
    replace 복원추출
    random_state 랜덤시드 설정(같은 랜덤시드를 설정하면, 미래에도 같은 랜덤 샘플이 뽑힌다)
    sampled_state21 = state21.sample(n=20, replace = True, random_state=3490)
    sampled_state28 = state28.sample(n=20, replace = True, random_state=9103)

     

     

    4. 표본 평균구하기

    sampled_state21['OVERALL_LI'].mean()
    sampled_state28['OVERALL_LI'].mean()
    70.27850000000001
    66.12199999999999​

    두 평균의 차이가 4.15인데 이것은 매 표본마다 값이 달라진다. 따라서 두 지역의 문맹률에 차이가 있는지 없는지 통계적으로 유의미한 해석을 알기 위해서는 아래의 hypothesis test를 수행해야 한다. 

     

     

    5. hypothesis test 수행하기

    1) Two sampled test

    1. State the null hypothesis and the alternative hypothesis

    귀무가설: 두 지역의 문맹률은 같다.

    대립가설: 두 지역의 문맹률은 다르다.

     

    2. choose a significance level

    유의수준: 5%=0.05

     

    3. find the p-value

    p-value<5%이면 귀무가설을 기각할 수 있다. 

    scipy.stats.ttest_ind(a, b, equal_var)
    a: 첫번째 샘플의 관측값들
    b: 두 번째 샘플의 관측값들
    equal_var: 불리언값이다. 두 개 샘플의 분산이 같다는 가정에 대해 True/False를 한다.
    stats.ttest_ind(a=sampled_state21['OVERALL_LI'], b=sampled_state28['OVERALL_LI'], equal_var=False)

     

    alternative: 양측검정을 하면 파라미터를 적을 필요가 없지만, 만약 작거나 크다를 명시하고 싶으면 less 또는 greater을 적는다. 
    a<b 라면 less라고 적는다. 
    ex) ohio< newyork

    ex) newyork < ohio

     

    결과

    p-value=0.064=6.4%

    두 샘플이 차이가 없다는 귀무가설의 전제 아래, 두 샘플의 절대적인 차이가 4.15이거나, 이것보다 작을 확률이 6.4%가 된다는 의미이다.   

    Ttest_indResult(statistic=1.9165891405315183, pvalue=0.06285805488526518)

     

     

    4. reject or fail to reject the null hypothesis

     p-value< significance level 귀무가설 기각

    ---> Statistically significant difference in literacy rates

     

    p-value> significance level 귀무가설 기각 안됨

     6.4%>5% 이므로 fail to reject the null hypothesis이다.

    ---> No Statistically significant difference in literacy rates

     

     

     

    2) One-sampled test

    귀무가설: 새로운 정책에 영향을 받지 않은 Michigan 주의 aqi 평균은 10이하일 것이다. 

    대립가설: 새로운 정책에 영향이 있는 Michigan 주의 aqi 평균이 10보다 클 것이다.

    mcg= aqi[aqi['state_name']=='Michigan']
    tstat, pvalue= stats.ttest_1samp(mcg['aqi'], 10, alternative='greater')
    -1.7395913343286131
    0.9399405193140109

    p-value 0,93 > significant level 0.5

    귀무가설 기각

     

     

    데이터분석, 데이터교육, 코딩, 코딩교육, 데이터 분석시험, 구글