독립표본 검정 (Independent)

데이터가 정규성을 가지는 경우(모수적 검정)
 두 집단의 등분산 검정을 한 후 from scipy.stats import ttest_ind

 - 등분산인 경우:  ttest_ind(data1, data2, equal_var = True)

 - 등분산이 아닌 경우:  ttest_ind(data1, data2, equal_var = False)

데이터가 정규성을 가지지 않는 경우(비모수적 검정)

 

11. 두개 학급의 시험성적에 대한 데이터이다. 두 학습의 시험 평균(비모수검정의 경우 중위값)은 동일하다 말할 수 있는지 확인하라.

# 데이터 로드
import pandas as pd 
import matplotlib.pyplot as plt
df1 = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/scipy/ind1.csv')
df2 = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/scipy/ind2.csv')

# 시각화
plt.hist(df1,label='df1',alpha=0.4)
plt.hist(df2,label="df2",alpha=0.4)
plt.xlabel('Score bins')
plt.ylabel('Counts')
plt.legend()
plt.show()

print('class1 데이터 수:', len(df1))
print('class2 데이터 수:', len(df2))

# 정규성 검정
from scipy.stats import shapiro
s1, p1 = shapiro(df1)
s2, p2 = shapiro(df2)
print(shapiro(df1))
print(shapiro(df2))
for i, p in enumerate([p1, p2]):
    if p < 0.05:
        print(f'class{i+1}: 유의수준 5%에서 귀무가설 기각 → 정규성을 만족하지 않음')
    else:
        print(f'class{i+1}: 유의수준 5%에서 귀무가설 채택 → 정규성 만족')

# 등분산 검정
from scipy.stats import levene
statistic, p_value = levene(df1['data'], df2['data'])
print(levene(df1['data'], df2['data']))
if p_value < 0.05:
    print('유의수준 5%에서 귀무가설 기각 → 두 그룹의 분산이 같다고 할 수 없음')
else:
    print('유의수준 5%에서 귀무가설 채택 → 두 그룹의 분산이 같다고 할 수 있음')
    
# t-test
from scipy.stats import ttest_ind
statistic, p_value = ttest_ind(df1, df2, equal_var = True)
print(ttest_ind(df1, df2, equal_var = True))
if p_value[0] < 0.05:
    print('유의수준 5%에서 귀무가설 기각 → 두 그룹의 평균에 차이가 있다고 할 수 있음')
else:
    print('유의수준 5%에서 귀무가설 채택 → 두 그룹의 평균에 차이가 있다고 할 수 없음')
[output]
class1 데이터 수: 100
class2 데이터 수: 100
ShapiroResult(statistic=0.9860946536064148, pvalue=0.379673033952713) ShapiroResult(statistic=0.990182638168335, pvalue=0.6793646216392517)
class1: 유의수준 5%에서 귀무가설 채택 → 정규성 만족
class2: 유의수준 5%에서 귀무가설 채택 → 정규성 만족
LeveneResult(statistic=2.5337683795339547, pvalue=0.11302904824468704)
유의수준 5%에서 귀무가설 채택 → 두 그룹의 분산이 같다고 할 수 있음 Ttest_indResult(statistic=array([2.76719074]), pvalue=array([0.00619015]))
유의수준 5%에서 귀무가설 기각 → 두 그룹의 평균에 차이가 있다고 할 수 음

 

12. 두개 학급의 시험성적에 대한 데이터이다. 두 학습의 시험 평균(비모수검정의 경우 중위값)은 동일하다 말할 수 있는지 확인하라.

# 데이터 로드
import pandas as pd 
import matplotlib.pyplot as plt
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/scipy/scipy5.csv')

# 시각화
plt.hist(df['A'], alpha = 0.5,label = 'A')
plt.hist(df['B'].dropna(),alpha = 0.5, label = 'B')
plt.xlabel('Score bins')
plt.ylabel('Counts')
plt.legend()
plt.show()

print('데이터 수: ', len(df))

# 정규성 검정
from scipy.stats import shapiro
s1, p1 = shapiro(df['B'].dropna())
s2, p2 = shapiro(df['A'])
print(shapiro(df['B'].dropna()))
print(shapiro(df['A']))
for i, p in enumerate([p1, p2]):
    if p < 0.05:
        print(f'class{i+1}: 유의수준 5%에서 귀무가설 기각 → 정규성을 만족하지 않음')
    else:
        print(f'class{i+1}: 유의수준 5%에서 귀무가설 채택 → 정규성 만족')

# 두 그룹 모두 정규성을 만족하지 않으므로 비모수 검정
# Mann-Whitney U Test
from scipy.stats import mannwhitneyu
statistic, p_value = mannwhitneyu(df['A'],df['B'].dropna())
print(mannwhitneyu(df['A'],df['B'].dropna()))
if p_value < 0.05:
    print('유의수준 5%에서 귀무가설 기각 → 두 그룹의 평균에 차이가 있다고 할 수 없음')
else:
    print('유의수준 5%에서 귀무가설 채택 → 두 그룹의 평균에 차이가 있다고 할 수 있음')
# 윌콕슨 순위합 검정(ranksums)
from scipy.stats import ranksums
statistic, p_value = ranksums(df['A'],df['B'].dropna())
print(ranksums(df['A'],df['B'].dropna()))
if p_value < 0.05:
    print('유의수준 5%에서 귀무가설 기각 → 두 그룹의 평균에 차이가 있다고 할 수 있음')
else:
    print('유의수준 5%에서 귀무가설 채택 → 두 그룹의 평균에 차이가 있다고 할 수 없음')
[output]
데이터 수: 300
ShapiroResult(statistic=0.9639433026313782, pvalue=0.00013568344002123922) ShapiroResult(statistic=0.93753981590271, pvalue=6.175894240456614e-10)
class1: 유의수준 5%에서 귀무가설 기각 → 정규성을 만족하지 않음
class2: 유의수준 5%에서 귀무가설 기각 → 정규성을 만족하지 않음
MannwhitneyuResult(statistic=27036.0, pvalue=0.9807458376150018)
유의수준 5%에서 귀무가설 채택 → 두 그룹의 평균에 차이가 있다고 할 수 있음 RanksumsResult(statistic=0.02446942170858557, pvalue=0.9804781743503561)
유의수준 5%에서 귀무가설 채택 → 두 그룹의 평균에 차이가 있다고 할 수 음

 

13. 두개 그룹에 대한 수치형 데이터이다. 두 그룹의 평균은 동일하다 말할 수 있는지 검정하라.

# 데이터 로드
import pandas as pd 
import matplotlib.pyplot as plt
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/scipy/ind3.csv')

# 시각화
plt.hist(df[df['group'] == 'a'].data,label = 'A', alpha = 0.5)
plt.hist(df[df['group'] == 'b'].data,label = 'B', alpha = 0.5)
plt.xlabel('Score bins')
plt.ylabel('Counts')
plt.legend()
plt.show()

a = df[df['group'] =='a'].data
b = df[df['group'] =='b'].data

print('데이터 수: ', len(df))
# 정규성 검정
from scipy.stats import shapiro
print(shapiro(a))
print(shapiro(b))
for i in [shapiro(a), shapiro(b)]:
    if i[1] < 0.05:
        print('유의수준 5%에서 귀무가설 기각 → 정규성을 만족하지 않음')
    else:
        print('유의수준 5%에서 귀무가설 채택 → 정규성 만족')

# 등분산 검정
from scipy.stats import levene
statistic, p_value = levene(a, b)
print(levene(a, b))
if p_value < 0.05:
    print('유의수준 5%에서 귀무가설 기각 → 두 그룹의 분산이 같다고 할 수 없음')
else:
    print('유의수준 5%에서 귀무가설 채택 → 두 그룹의 분산이 같다고 할 수 있음')
    
# t-test
from scipy.stats import ttest_ind
statistic, p_value = ttest_ind(a, b, equal_var = False)
print(ttest_ind(a, b, equal_var = False))
if p_value < 0.05:
    print('유의수준 5%에서 귀무가설 기각 → 두 그룹의 평균에 차이가 있다고 할 수 있음')
else:
    print('유의수준 5%에서 귀무가설 채택 → 두 그룹의 평균에 차이가 있다고 할 수 없음')
[output]

데이터 수: 190
ShapiroResult(statistic=0.9834123253822327, pvalue=0.1473984718322754) ShapiroResult(statistic=0.9831852316856384, pvalue=0.4701973497867584)
유의수준 5%에서 귀무가설 채택 → 정규성 만족
유의수준 5%에서 귀무가설 채택 → 정규성 만족
LeveneResult(statistic=6.185601018015722, pvalue=0.013750484571911642)
유의수준 5%에서 귀무가설 기각 → 두 그룹의 분산이 같다고 할 수 없음 Ttest_indResult(statistic=-2.1949470315829265, pvalue=0.029512802991767898)
유의수준 5%에서 귀무가설 기각 → 두 그룹의 평균에 차이가 있다고 할 수 있음

 

14. 두개 그룹에 대한 수치형 데이터이다. 두 그룹의 평균은 동일하다 말할 수 있는지 검정하라.

# 데이터 로드
import pandas as pd 
import matplotlib.pyplot as plt
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/scipy/ind6.csv')

# 시각화
plt.hist(df['a'], alpha = 0.5, label = 'A')
plt.hist(df['b'], alpha = 0.5, label = 'B')
plt.xlabel('Score bins')
plt.ylabel('Counts')
plt.legend()
plt.show()

a = df['a'].dropna()
b = df['b'].dropna()

print('데이터 수: ', len(df))

# 정규성 검정
from scipy.stats import shapiro
print(shapiro(a))
print(shapiro(b))
for i in [shapiro(a), shapiro(b)]:
    if i[1] < 0.05:
        print('유의수준 5%에서 귀무가설 기각 → 정규성을 만족하지 않음')
    else:
        print('유의수준 5%에서 귀무가설 채택 → 정규성 만족')

# 등분산 검정
from scipy.stats import levene
statistic, p_value = levene(a, b)
print(levene(a, b))
if p_value < 0.05:
    print('유의수준 5%에서 귀무가설 기각 → 두 그룹의 분산이 같다고 할 수 없음')
else:
    print('유의수준 5%에서 귀무가설 채택 → 두 그룹의 분산이 같다고 할 수 있음')
    
# t-test
from scipy.stats import ttest_ind
statistic, p_value = ttest_ind(a, b, equal_var = False)
print(ttest_ind(a, b, equal_var = False))
if p_value < 0.05:
    print('유의수준 5%에서 귀무가설 기각 → 두 그룹의 평균에 차이가 있다고 할 수 있음')
else:
    print('유의수준 5%에서 귀무가설 채택 → 두 그룹의 평균에 차이가 있다고 할 수 없음')
[output]
데이터 수: 120
ShapiroResult(statistic=0.9865895509719849, pvalue=0.28390026092529297) ShapiroResult(statistic=0.9854326844215393, pvalue=0.5937624573707581)
유의수준 5%에서 귀무가설 채택 → 정규성 만족
유의수준 5%에서 귀무가설 채택 → 정규성 만족
LeveneResult(statistic=3.9862856894158347, pvalue=0.047314956128686365)
유의수준 5%에서 귀무가설 기각 → 두 그룹의 분산이 같다고 할 수 없음 Ttest_indResult(statistic=0.0015963310698567184, pvalue=0.9987289046092704)
유의수준 5%에서 귀무가설 채택 → 두 그룹의 평균에 차이가 있다고 할 수 없음

 

대응표본 t 검정 (paired)

15. 특정 질병 집단의 투약 전후의 혈류량 변화를 나타낸 데이터이다. 투약 전후의 변화가 있는지 검정하라.

# 데이터 로드
import pandas as pd 
import matplotlib.pyplot as plt
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/scipy/rel2.csv')

# 시각화
fig ,ax = plt.subplots(1,2)
ax[0].boxplot(df['before'])
ax[1].boxplot(df['after'])
ax[0].set_xticklabels(['before'])
ax[1].set_xticklabels(['after'])
ax[0].set_ylim(100, 350)
ax[1].set_ylim(100, 350)
ax[1].get_yaxis().set_visible(False)
ax[0].set_ylabel('value')
plt.show()

before = df['before']
after = df['after']
print('데이터 수: ', len(df))

# 정규성 검정
from scipy.stats import shapiro
print(shapiro(before))
print(shapiro(after))
for i in [shapiro(before), shapiro(after)]:
    if i[1] < 0.05:
        print('유의수준 5%에서 귀무가설 기각 → 정규성을 만족하지 않음')
    else:
        print('유의수준 5%에서 귀무가설 채택 → 정규성 만족')

# 등분산 검정
from scipy.stats import levene
statistic, p_value = levene(before, after)
print(levene(before, after))
if p_value < 0.05:
    print('유의수준 5%에서 귀무가설 기각 → 투약 전후의 분산이 같다고 할 수 없음')
else:
    print('유의수준 5%에서 귀무가설 채택 → 투약 전후의 분산이 같다고 할 수 있음')
    
# t-test
from scipy.stats import ttest_rel
statistic, p_value = ttest_rel(before, after)
print(ttest_rel(before, after))
if p_value < 0.05:
    print('유의수준 5%에서 귀무가설 기각 → 투약 전후의 평균에 차이가 있다고 할 수 있음')
else:
    print('유의수준 5%에서 귀무가설 채택 → 투약 전후의 평균에 차이가 있다고 할 수 없음')
[output]

데이터 수: 120
ShapiroResult(statistic=0.9907895922660828, pvalue=0.6065835952758789) ShapiroResult(statistic=0.9916961193084717, pvalue=0.6923638582229614)
유의수준 5%에서 귀무가설 채택 → 정규성 만족
유의수준 5%에서 귀무가설 채택 → 정규성 만족
LeveneResult(statistic=0.06427968690211128, pvalue=0.8000741651677916)
유의수준 5%에서 귀무가설 채택 → 투약 전후의 분산이 같다고 할 수 있음 TtestResult(statistic=-2.5535473487670677, pvalue=0.011926744724546513, df=119)
유의수준 5%에서 귀무가설 기각 → 투약 전후의 평균에 차이가 있다고 할 수 있음

 

16. 특정 질병 집단의 투약 전후의 혈류량 변화를 나타낸 데이터이다. 투약 전후의 변화가 있는지 검정하라.

# 데이터 로드
import pandas as pd 
import matplotlib.pyplot as plt
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/scipy/rel3.csv')

# 시각화
fig, ax = plt.subplots(1, 2)
ax[0].boxplot(df['before'])
ax[1].boxplot(df['after'])
ax[0].set_xticklabels(['before'])
ax[1].set_xticklabels(['after'])
ax[0].set_ylim(130, 300)
ax[1].set_ylim(130, 300)
ax[1].get_yaxis().set_visible(False)
ax[0].set_ylabel('value')
plt.show()

before = df['before']
after = df['after']
print('데이터 수: ', len(df))

# 정규성 검정
from scipy.stats import shapiro
print(shapiro(before))
print(shapiro(after))
for i in [shapiro(before), shapiro(after)]:
    if i[1] < 0.05:
        print('유의수준 5%에서 귀무가설 기각 → 정규성을 만족하지 않음')
    else:
        print('유의수준 5%에서 귀무가설 채택 → 정규성 만족')

# 등분산 검정
from scipy.stats import levene
statistic, p_value = levene(before, after)
print(levene(before, after))
if p_value < 0.05:
    print('유의수준 5%에서 귀무가설 기각 → 투약 전후의 분산이 같다고 할 수 없음')
else:
    print('유의수준 5%에서 귀무가설 채택 → 투약 전후의 분산이 같다고 할 수 있음')
    
# t-test
from scipy.stats import ttest_rel
statistic, p_value = ttest_rel(before, after)
print(ttest_rel(before, after))
if p_value < 0.05:
    print('유의수준 5%에서 귀무가설 기각 → 투약 전후의 평균에 차이가 있다고 할 수 있음')
else:
    print('유의수준 5%에서 귀무가설 채택 → 투약 전후의 평균에 차이가 있다고 할 수 없음')
[output]
데이터 수: 120
ShapiroResult(statistic=0.9920631051063538, pvalue=0.7270199656486511) ShapiroResult(statistic=0.992019534111023, pvalue=0.7229290008544922)
유의수준 5%에서 귀무가설 채택 → 정규성 만족
유의수준 5%에서 귀무가설 채택 → 정규성 만족
LeveneResult(statistic=1.3463330638203617, pvalue=0.2470827904523813)
유의수준 5%에서 귀무가설 채택 → 투약 전후의 분산이 같다고 할 수 있음 TtestResult(statistic=0.188900575991026, pvalue=0.8504925317234707, df=119)
유의수준 5%에서 귀무가설 채택 → 투약 전후의 평균에 차이가 있다고 할 수 없음

 

17. 특정 집단의 학습 전후 시험 성적 변화를 나타낸 데이터이다. 시험 전과 후에 차이가 있는지 검정하라.

# 데이터 로드
import pandas as pd 
import matplotlib.pyplot as plt
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/scipy/rel1.csv')

# 시각화
fig ,ax = plt.subplots(1, 2)
ax[0].boxplot(df['before'])
ax[1].boxplot(df['after'])
ax[0].set_xticklabels(['before'])
ax[1].set_xticklabels(['after'])
ax[0].set_ylim(145, 170)
ax[1].set_ylim(145, 170)
ax[1].get_yaxis().set_visible(False)
ax[0].set_ylabel('value')
plt.show()

before = df['before']
after = df['after']
print('데이터 수: ', len(df))

# 정규성 검정
from scipy.stats import shapiro
print(shapiro(before))
print(shapiro(after))
for i in [shapiro(before), shapiro(after)]:
    if i[1] < 0.05:
        print('유의수준 5%에서 귀무가설 기각 → 정규성을 만족하지 않음')
    else:
        print('유의수준 5%에서 귀무가설 채택 → 정규성 만족')

# 등분산 검정
from scipy.stats import levene
statistic, p_value = levene(before, after)
print(levene(before, after))
if p_value < 0.05:
    print('유의수준 5%에서 귀무가설 기각 → 전후의 분산이 같다고 할 수 없음')
else:
    print('유의수준 5%에서 귀무가설 채택 → 전후의 분산이 같다고 할 수 있음')

# 정규성을 가지지 않음 → 대응 표본 검정중 비모수 검정인 윌콕슨 부호순위 검정을 진행
# 등분산성 가짐 → 대응표본의 경우 등분산성이 파라미터에 영향을 주지않음
# wilcoxon 부호순위 검정
from scipy.stats import wilcoxon
statistic, p_value = wilcoxon(before, after)
print(wilcoxon(before, after))
if p_value < 0.05:
    print('유의수준 5%에서 귀무가설 기각 → 전후의 평균에 차이가 있다고 할 수 있음')
else:
    print('유의수준 5%에서 귀무가설 채택 → 전후의 평균에 차이가 있다고 할 수 없음')
[output]
데이터 수: 50
ShapiroResult(statistic=0.9173730611801147, pvalue=0.0018974003614857793) ShapiroResult(statistic=0.9448966979980469, pvalue=0.021140215918421745)
유의수준 5%에서 귀무가설 기각 → 정규성을 만족하지 않음
유의수준 5%에서 귀무가설 기각 → 정규성을 만족하지 않음
LeveneResult(statistic=0.14329522146179022, pvalue=0.7058456563194885)
유의수준 5%에서 귀무가설 채택 → 전후의 분산이 같다고 할 수 있음
WilcoxonResult(statistic=437.0, pvalue=0.12098409484052809)
유의수준 5%에서 귀무가설 채택 → 전후의 평균에 차이가 있다고 할 수 없음

 

18. 한 기계 부품의 rpm 수치를 두가지 다른 상황에서 측정했다.(총 70세트) b 상황이 a 상황보다 rpm값이 높다고 말할 수 있는지 검정하라.

# 데이터 로드
import pandas as pd 
import matplotlib.pyplot as plt
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/scipy/rel4.csv')

# 시각화
fig ,ax = plt.subplots(1, 2)
ax[0].boxplot(df[df['group'] == 'a'].rpm)
ax[1].boxplot(df[df['group'] == 'b'].rpm)
ax[0].set_xticklabels(['a'])
ax[1].set_xticklabels(['b'])
ax[0].set_ylim(430, 600)
ax[1].set_ylim(430, 600)
ax[1].get_yaxis().set_visible(False)
ax[0].set_ylabel('rpm')
plt.show()

a = df[df['group'] == 'a'].rpm
b = df[df['group'] == 'b'].rpm
print('데이터 수:', len(df))

# 정규성 검정
from scipy.stats import shapiro
print(shapiro(a))
print(shapiro(b))
for i in [shapiro(a), shapiro(b)]:
    if i[1] < 0.05:
        print('유의수준 5%에서 귀무가설 기각 → 정규성을 만족하지 않음')
    else:
        print('유의수준 5%에서 귀무가설 채택 → 정규성 만족')

# 등분산 검정
from scipy.stats import levene
statistic, p_value = levene(a, b)
print(levene(a, b))
if p_value < 0.05:
    print('유의수준 5%에서 귀무가설 기각 → 상황 a와 b의 분산이 같다고 할 수 없음')
else:
    print('유의수준 5%에서 귀무가설 채택 → 상황 a와 b의 분산이 같다고 할 수 있음')

# t-test
from scipy.stats import ttest_rel
statistic, p_value = ttest_rel(a, b, alternative = 'greater')
print(ttest_rel(a, b, alternative = 'greater')) # H1 : a > b
if p_value < 0.05:
    print('유의수준 5%에서 귀무가설 기각 → b 상황이 a 상황보다 rpm 값이 크다고 할 수 없음')
else:
    print('유의수준 5%에서 귀무가설 채택 → b 상황이 a 상황보다 rpm 값이 크다고 할 수 있음')
[output]
데이터 수: 140
ShapiroResult(statistic=0.9907217025756836, pvalue=0.8884284496307373) ShapiroResult(statistic=0.984674870967865, pvalue=0.5505106449127197)
유의수준 5%에서 귀무가설 채택 → 정규성 만족
유의수준 5%에서 귀무가설 채택 → 정규성 만족
LeveneResult(statistic=0.06716114122680159, pvalue=0.795902086492326)
유의수준 5%에서 귀무가설 채택 → 상황 a와 b의 분산이 같다고 할 수 있음 TtestResult(statistic=-1.9018108294460812, pvalue=0.9693143365355352, df=69)
유의수준 5%에서 귀무가설 채택 → b 상황이 a 상황보다 rpm 값이 크다고 할 수 있음

 

카이제곱 검정 (교차분석)

일원 카이제곱검정 (chisquare , 카이제곱 적합도 검정)
 한 개의 요인에 의해 k개의 범주를 가질때 이론적 분포를 따르는지 검정
이원 카이제곱검정 (chi2_contingency ,fisher_exact(빈도수 5개 이하 셀이 20% 이상일때) , 카이제곱독립검정)
 모집단이 두개의 변수에 의해 범주화 되었을 때, 두 변수들 사이의 관계가 독립인지 아닌지 검정

 

19. 144회 주사위를 던졌을때, 각 눈금별로 나온 횟수를 나타낸다. 이 데이터는 주사위의 분포에서 나올 가능성이 있는지 검정하라.

# 데이터 로드
import pandas as pd 
import matplotlib.pyplot as plt
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/scipy/dice.csv')

# 시각화
plt.bar(df.dice_number, df.counts)
plt.xlabel('dice value')
plt.ylabel('counts')
plt.show()

# 주사위 눈금의 발생확률은 1/6으로 모두 동일
from scipy.stats import chisquare
df['expected'] = df['counts'].sum()/6
statistic, p_value = chisquare(df.counts, df.expected)
print(chisquare(df.counts, df.expected))
if p_value < 0.05:
    print('유의수준 5%에서 귀무가설 기각 → 각 주사위 눈금의 발생 비율은 동일하다고 할 수 없음')
else:
    print('유의수준 5%에서 귀무가설 채택 → 각 주사위 눈금의 발생 비율은 동일하다고 할 수 있음')
[output]
Power_divergenceResult(statistic=2.333333333333333, pvalue=0.8013589222076911)
유의수준 5%에서 귀무가설 채택 → 각 주사위 눈금의 발생 비율은 동일하다고 할 수 있음

 

20. 다음 데이터는 어떤 집단의 왼손잡이, 오른손 잡이의 숫자를 나타낸다. 인간의 왼손잡이와 오른손잡이의 비율은 0.2:0.8로 알려져있다. 이 집단에서 왼손과 오른손 잡이의 비율이 적합한지 검정하라.

# 데이터 로드
import pandas as pd 
import matplotlib.pyplot as plt
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/scipy/hands2.csv')
display(df.head())

target = df.hands.value_counts().to_frame()
target['expected'] = [target.hands.sum()*0.8, target.hands.sum()*0.2]
display(target)

from scipy.stats import chisquare
statistic, p_value = chisquare(target.hands, target.expected)
print(chisquare(target.hands, target.expected))
if p_value < 0.05:
    print('유의수준 5%에서 귀무가설 기각 → 주어진 집단의 왼손과 오른손잡이의 비율이 0.2 : 0.8이라고 할 수 없음')
else:
    print('유의수준 5%에서 귀무가설 채택 → 주어진 집단의 왼손과 오른손잡이의 비율이 0.2 : 0.8이라고 할 수 있음')
[output]

Power_divergenceResult(statistic=5.0, pvalue=0.025347318677468325)
유의수준 5%에서 귀무가설 기각 → 주어진 집단의 왼손과 오른손잡이의 비율이 0.2 : 0.8이라고 할 수 없음

 

21. 다음 데이터는 국민 기초체력을 조사한 데이터이다. 성별과 등급이 독립적인지 검정하라.

# 데이터 로드
import pandas as pd 
import matplotlib.pyplot as plt
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/body/body.csv')
display(df.head())

cdf = df.groupby('측정회원성별')['등급'].value_counts().unstack()
display(cdf)

from scipy.stats import chi2_contingency
p_value = chi2_contingency(cdf)[1]
print(chi2_contingency(cdf))
if p_value < 0.05:
    print('유의수준 5%에서 귀무가설 기각 → 측정회원 성별과 등급은 연관이 있다고 할 수 있음')
else:
    print('유의수준 5%에서 귀무가설 채택 → 측정회원 성별과 등급은 연관이 있다고 할 수 없음')
[output]
Chi2ContingencyResult(statistic=120.06233631119409, pvalue=7.481892813401677e-26, dof=3, expected_freq=array([[1220.25, 1220.25, 1220.25, 1220.25], [2128.75, 2128.75, 2128.75, 2128.75]]))
유의수준 5%에서 귀무가설 기각 → 측정회원 성별과 등급은 연관이 있다고 할 수 있음

 

22. 성별에 따른 동아리 활동 참석 비율을 나타낸 데이터이다. 성별과 참석간에 관련이 있는지 검정하라.

# 데이터 로드
import pandas as pd 
import matplotlib.pyplot as plt
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/scipy/fe2.csv',index_col=0)
display(df)

cdf = df.iloc[:-1, :-1]
display(cdf)

from scipy.stats import chi2_contingency,fisher_exact
print(chi2_contingency(cdf))
print('p_value가 0.05보다 크므로 귀무가설 채택, 성별과 참석여부는 연관이 있다고 할 수 없다.')

# 5보다 작은 셀이 20%가 넘어가므로(75%) 피셔의 정확검정
p_value = fisher_exact(cdf)[1]
print(fisher_exact(cdf))
if p_value < 0.05:
    print('유의수준 5%에서 귀무가설 기각 → 성별과 참석여부는 연관이 있다고 할 수 있음')
else:
    print('유의수준 5%에서 귀무가설 채택 → 성별과 참석여부는 연관이 있다고 할 수 없음')
[output]
SignificanceResult(statistic=18.0, pvalue=0.03571428571428571)
유의수준 5%에서 귀무가설 기각 → 성별과 참석여부는 연관이 있다고 할 수 있음

출처 : https://www.datamanim.com/dataset/97_scipy/scipy.html

+ Recent posts