AI SEOUL 2025에 다녀왔다.
먹고 자는 백수의 삶이 반복되던 중 바깥 세상을 경험하기 위해 집 근처 코엑스에서 열리는 행사를 알아보다가 바로 사전등록하게 만든 이 행사.

입장시간 전부터 대기줄이 엄청났다.
직업 선택하라고 해서 정직하게 무직 적어낸 사람ㅋㅋㅋㅋ

키오스크가 이름표를 뱉어내자마자 당황해서 재빨리 집어들었다.. (부끄러울 것 없어..!!) 나중에 일반인이라고 되어있는 분을 마주하고 괜히 안도감이 들었다.

AI SEOUL 2025의 프로그램 목록

이번 행사는 크게 컨퍼런스, 트랙1, 트랙2, 전시로 나뉘어 진행 되었는데 나는 처음부터 끝까지 컨퍼런스만 참여했다. 각 프로그램 진행 장소마다 제공하는 스티커를 모아 등록하면 응모권을 주는 경품 이벤트가 있었는데 많이들 참여하는 것 같았다.

시장님의 2025 서울시 AI 7대 혁신 과제 발표를 시작으로 세계적으로 저명하신 분들의 강연이 이어졌는데 개인적으로는 세션3:AI 일상을 다룬 주제가 가장 몰입도가 높았다.
주제 자체가 와닿아서 그런가, 연사님들의 뛰어난 언변 덕분인가, 아니면 유일하게 한국인 강연자들로만 구성되어 있어서 일지도..?
(AI 컨퍼런스 답게 ai 기술을 사용하여 한글과 영어를 동시에 번역해서 제공하였는데 아무래도 딜레이가 좀 있고 의역 및 오역 때문에 집중이 흐려졌던 것 같다.)

아무튼 와닿았던 부분들을 기록으로 남겨두려 한다.
강연자들의 발언은 메모한 내용을 바탕으로 재구성한 것이기 때문에 실제 의도와 벗어날 수 있는 점을 미리 알립니다.


기조세션 | 2025년 AI의 미래

서울시 AI 7대 전략 과제 - 오세훈 서울시장
1. 인재양성
2. 인프라 조성
3. 투자 확대
4. 산업 간 융복합
5. 글로벌화
6. 시민 확산
7. 행정 혁신
  • AI는 과학이 아니다. 사람의 노력으로 해결했던 문제들을 해결하려는 공학이다. - Jerry Kaplan 스탠퍼드대학교 교수
  • 국내 AI는 국부를 창출하는 방향으로 도입 및 발전되어야 한다. 가치를 창출해야 공학으로서 의미를 갖는다 . - 김영오 서울대학교 공과대학 학장

세션1 | AI 윤리: 발전의 대가

  • 생성형 AI가 성공하기 위해서는 인간의 감독과 실용적 가이드라인이 필수적이다. - Ben Shneiderman 메릴랜드대학교 교수
  • 많은 이들이 말하는 AI의 주요 위험과 문제들은 악위적 행위자들에 의한 것이다. - Ben Shneiderman 메릴랜드대학교 교수
  • AI에 대한 신뢰도와 평가는 AI 휴리스틱 수준에 따라 달라진다. - 이은주 서울대학교 인공지능신뢰성센터장
  • AI 위험은 다양한 분야에서 다양한 방식으로 나타나기 때문에 무조건적인 규제 또는 도입은 위험하다. - 최민석 한국전자통신연구원 AI안전연구소 실장
  • 최근 많이 강조 되고있는 리터러시 교육에서 기술적인 부분은 모두에게 필요하지 않을 수 있다. 그러나 작동원리를 이해하는 것은 매우 중요하다. - 이은주 서울대학교 인공지능신뢰성센터장

세션1도 개인적으로 매우 흥미롭게 들었다. 특히 이은주 센터장님이 실제 실험 사례를 들어 설명해주신 부분과 질의응답 시간에 국제적으로 이루어지고 있는 AI 위험 대응에 대한 논의에 대해 소신있게 발언해주신 내용이 인상 깊었다. 기회가 된다면 센터장님의 논문이나 강연을 추가로 들어봤으면 좋겠다!


세션2 | AI 혁신: 혁신의 힘, AI가 여는 새로운 기회

  • AI의 도입 및 활용은 그 자체가 목적이 아닌 수단이 되어야 한다. - 유경범 네이버 클라우드 상무
  • 혁신적 AI 생태계를 만들기 위해서는 인재들이 우연히 접근하여 상호 협력할 수 있는 매우 창의적이고 자유로운 환경이 조성 되어야 한다. - Alex Diehl 사이버밸리 시니어 어드바이저
  • 혁신적 AI 생태계를 만들기 위해서는 성과 위주의 드라이빙에서 벗어나 실패에 대한 인정이 필요하다. 프로젝트 진행 중 영업이익이나 단기적인 결과로 인해 지원이 중단되지 않도록 충분한 시간 역시 주어져야 한다. - 유경범 네이버 클라우드 상무

세션3 | AI 일상: AI 기술이 만드는 일상의 변화

  • AI와 경쟁하려고 하지 마라. 파트너로서, 좋은 툴로서 그것을 활용하라. 항상 호기심을 가지고 새로운 기술이 나오면 사용해봐라. - 이지혜 카카오엔터프라이즈 부사장
  • 철학•창조•인간의 경험 등은 AI가 범접할 수 없는 인간의 영역이다. - 이지혜 카카오엔터프라이즈 부사장
  • 정확한 숫자 전달보다 중요한 것은 알아들을 수 있게 전달하는 것이다. - 장원철 서울대학교 교수
  • 전세계 시장이 AI시대를 인정하고 있다. 기존의 시스템이 익숙하다고 현실을 외면한다면 나만 도태된다. 인간의 진화 역사상 분명한 것은 같은 일을 더 적은 시간을 들여 할 수 있다면 인간은 무조건 선택한다는 것이다.- 최재붕 성균관대학교 교수
  • AI 혁신에 대한 은근한 두려움이 규제를 낳는다. 이러한 규제는 그 옛날의 쇄국정책과 다름 없는 결과를 낳을 것이다. - 최재붕 성균관대학교 교수

세션3에서도 얻어갈 점이 참 많았다. 이지혜 부사장님은 AI 시대 기업의 리더로서의 모범적인 자세를 보여주셨고(이런 임원이 계신 곳에서 일하면 참 좋을 것 같다는 생각을 했다), 개인적으로 사용자의 해석과 의도에 따라 무분별하게 사용될 수 있는 통계의 위험성과 변화무쌍함에 매력에 느꼈던 공학도로서 장원철 교수님의 유쾌한 강연도 인상 깊게 들었다.(서울대 통계학과를 붙었다면 교수님 강의를 들었을수도..?ㅋㅋ)
최재붕 교수님은 베스트셀러 작가 답게 AI의 주요 현황과 우리가 지녀야 할 마인드셋에 대해 호소력 있게 전달해주셨다.


마치며

오전부터 시작해 저녁이 되어서야 끝난 오늘의 컨퍼런스는 생각보다 훨씬 유익하고 흥미로웠다. 역시 하나라도 더 주워 듣고, 무엇이든 경험하는 것이 나를 이롭게 한다. 평생 배우며 살아가겠다는 나의 인생 모토를 되새기며..!

본 포스팅은 고려대학교 산업경영공학부 김성범 교수님의 유튜브 강의를 정리한 내용입니다.

유튜브 - 김성범[ 교수 / 산업경영공학부 ]

 

Least Square Estimation Algorithm (최소제곱법)

  • Cost function is convex → globally optimal solution exists(전역 최적해 존재)
  • Cost function을 최소화하는 파라미터 찾기
  • 기울기가 0인 지점 찾기
  • 비용함수를 각 베타값으로 편미분한 값이 0이 되는 두 식을 연립방적식으로 풀기
  •  

 

잔차와 확률오차

  • 잔차e는 확률오차 ε이 실제로 구현된 값
  • 확률오차 값을 직접적으로 사용하기 곤란한 경우 잔차를 많이 활용함.

 

 

자주쓰는 모듈 구성

statsmodels
│
├── 01 사후분석
│   │
│   └──stats
│       └── multicomp
│           ├── MultiComparison
│           │   └── allpairtest
│           └── pairwise_tukeyhsd
│
├── 02 시계열분석
│   │
│   ├── graphics.tsaplots
│   │   ├── plot_acf
│   │   └── plot_pacf
│   └── tsa
│       ├── arima_model
│       │   └── ARIMA
│       └── statesplace.sarimax
│           └── SARIMAX
│
├── 03 ANOVA (scipy모듈과 함께써야 모두 커버가능, 이분산 anova의 경우 pingouin모듈의 welch_anova를 사용)
│   │
│   ├── 다원분산분석 or 이원분산분석
│   └── 일원분산분석
│       └── stats.anova
│           └── anova_lm
│
└── 04 회귀분석
    │
    └── formula.api
        └── ols

 

세 집단 이상 검정 (independent)

정규성 만족, 등분산 만족 : one-way anova
정규성 만족, 등분산 불만족 : welch’s anova
정규성 불만족 : kruskal-wallis H test

 

 1. x1,x2,x3의 변수들의 평균의 차이가 존재하는지 검정하라. 차이가 존재한다면 사후 분석까지 진행하라.

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

data = df.x1
data2 = df.x2
data3 = df.x3

# 시각화
fig,ax = plt.subplots(1, 2, figsize = (12, 4))
ax[0].hist(data,alpha = 0.3, bins = 30, label = 'x1')
ax[0].hist(data2,alpha = 0.3, bins = 30, label = 'x2')
ax[0].hist(data3,alpha = 0.3, bins = 30, label = 'x3')
ax[0].legend()
labels = ['x1', 'x2', 'x3']
lst = [data,data2,data3]
ax[1].boxplot(lst, labels = labels) 
plt.show()

# 정규성 검정
from scipy.stats import shapiro
print(shapiro(data))
print(shapiro(data2))
print(shapiro(data3))
if (shapiro(data)[1] >= 0.05) & (shapiro(data2)[1] >= 0.05) & (shapiro(data3)[1] >= 0.05):
    print('모든 변수가 정규성을 만족')
else:
    print('정규성을 만족하지 않음')
    
# 등분산 검정
from scipy.stats import levene
statistic, p_value = levene(data, data2, data3)
print(levene(data, data2, data3))
if p_value < 0.05:
    print('귀무가설 기각 → 변수들의 분산이 동일하다고 할 수 없음')
else:
    print('귀무가설 기각 → 변수들의 분산이 동일하다고 할 수 있음')

# ANOVA
from scipy.stats import f_oneway
statistic, p_value = f_oneway(data, data2, data3)
print(f_oneway(data, data2, data3))
if p_value < 0.05:
    print('귀무가설 기각 → 변수들의 평균에 차이가 있다고 할 수 있음')
else:
    print('귀무가설 기각 → 변수들의 평균에 차이가 있다고 할 수 없음')
    
# 사후검정
# 방법1) tukey's HSD
from statsmodels.stats.multicomp import pairwise_tukeyhsd
posthoc = pairwise_tukeyhsd(dfm.value, dfm.variable, alpha = 0.05)
print(posthoc)
# 시각화
fig = posthoc.plot_simultaneous()
plt.show()
# 방법2) 봉페로니 교정
from statsmodels.sandbox.stats.multicomp import MultiComparison
import scipy.stats

comp = MultiComparison(dfm.value, dfm.variable)
result = comp.allpairtest(scipy.stats.ttest_ind, method = 'bonf')
print(result[0])
[output]
ShapiroResult(statistic=0.9979789853096008, pvalue=0.27395427227020264) ShapiroResult(statistic=0.9979418516159058, pvalue=0.2591271996498108) ShapiroResult(statistic=0.9987621307373047, pvalue=0.7300694584846497)
모든 변수가 정규성을 만족
LeveneResult(statistic=2.71270174202054, pvalue=0.06652021922816238)
귀무가설 기각 → 변수들의 분산이 동일하다고 할 수 있음
F_onewayResult(statistic=209.88499932318638, pvalue=4.919152988455592e-86)
귀무가설 기각 → 변수들의 평균에 차이가 있다고 할 수 있음

 

 2. x1,x2,x3의 변수들의 평균의 차이가 존재하는지 검정하라.

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

data = df.x1
data2 = df.x2
data3 = df.x3

# 시각화
fig,ax = plt.subplots(1, 2, figsize = (12, 4))
ax[0].hist(data,alpha = 0.3, bins = 30, label = 'x1')
ax[0].hist(data2,alpha = 0.3, bins = 30, label = 'x2')
ax[0].hist(data3,alpha = 0.3, bins = 30, label = 'x3')
ax[0].legend()
labels = ['x1', 'x2', 'x3']
lst = [data,data2,data3]
ax[1].boxplot(lst, labels = labels) 
plt.show()

# 정규성 검정
from scipy.stats import shapiro
print(shapiro(data))
print(shapiro(data2))
print(shapiro(data3))
if (shapiro(data)[1] > 0.05) & (shapiro(data2)[1] > 0.05) & (shapiro(data3)[1] > 0.05):
    print('모든 변수가 정규성을 만족')
else:
    print('정규성을 만족하지 않음')
    
# 등분산 검정
from scipy.stats import levene
statistic, p_value = levene(data, data2, data3)
print(levene(data, data2, data3))
if p_value <= 0.05:
    print('귀무가설 기각 → 변수들의 분산이 동일하다고 할 수 없음')
else:
    print('귀무가설 기각 → 변수들의 분산이 동일하다고 할 수 있음')

# ANOVA
from scipy.stats import f_oneway
statistic, p_value = f_oneway(data, data2, data3)
print(f_oneway(data, data2, data3))
if p_value < 0.05:
    print('귀무가설 기각 → 변수들의 평균에 차이가 있다고 할 수 있음')
else:
    print('귀무가설 기각 → 변수들의 평균에 차이가 있다고 할 수 없음')
[output]
ShapiroResult(statistic=0.9886645078659058, pvalue=0.5584133863449097) ShapiroResult(statistic=0.9924368858337402, pvalue=0.8519019484519958) ShapiroResult(statistic=0.9848724007606506, pvalue=0.31092315912246704)
모든 변수가 정규성을 만족
LeveneResult(statistic=1.845797549925243, pvalue=0.15970603203147626)
귀무가설 기각 → 변수들의 분산이 동일하다고 할 수 있음
F_onewayResult(statistic=2.386152612702158, pvalue=0.09374426938585023)
귀무가설 기각 → 변수들의 평균에 차이가 있다고 할 수 없음

 

3. target 변수들에 의해 value값들의 평균의 차이가 존재하는지 검정하라.

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

data = df[df.target == 'a'].value
data2 = df[df.target == 'b'].value
data3 = df[df.target == 'c'].value

# 시각화
fig,ax = plt.subplots(1, 2, figsize = (12, 4))
ax[0].hist(data, alpha = 0.3, bins = 30, label = 'a')
ax[0].hist(data2, alpha = 0.3, bins = 30, label = 'b')
ax[0].hist(data3, alpha = 0.3, bins = 30, label = 'c')
ax[0].legend()
labels = ['a', 'b', 'c']
lst = [data, data2, data3]
ax[1].boxplot(lst, labels = labels) 
plt.show()

# 정규성 검정
from scipy.stats import shapiro
print(shapiro(data))
print(shapiro(data2))
print(shapiro(data3))
if (shapiro(data)[1] > 0.05) & (shapiro(data2)[1] > 0.05) & (shapiro(data3)[1] > 0.05):
    print('모든 변수가 정규성을 만족')
else:
    print('정규성을 만족하지 않음')
    
# 정규성을 만족하지 않으므로 비모수 검정인 kruskal 검정
from scipy.stats import kruskal
statistic, p_value = kruskal(data, data2, data3)
print(kruskal(data, data2, data3))

if p_value < 0.05:
    print('귀무가설 기각 → 변수들의 평균에 차이가 있다고 할 수 있음')
else:
    print('귀무가설 기각 → 변수들의 평균에 차이가 있다고 할 수 없음')
[output]
ShapiroResult(statistic=0.9666392207145691, pvalue=0.012299093417823315) ShapiroResult(statistic=0.9713972210884094, pvalue=0.10934212058782578) ShapiroResult(statistic=0.9651247262954712, pvalue=0.41566193103790283)
정규성을 만족하지 않음
KruskalResult(statistic=6.9277037668798584, pvalue=0.03130893110123)
귀무가설 기각 → 변수들의 평균에 차이가 있다고 할 수 있음

 

4. target 변수들에 의해 value값들의 평균의 차이가 존재하는지 검정하라.

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

data = df[df.target == 'a'].value
data2 = df[df.target == 'b'].value
data3 = df[df.target == 'c'].value

# 시각화
fig,ax = plt.subplots(1, 2, figsize = (12, 4))
ax[0].hist(data, alpha = 0.3, bins = 30, label = 'a')
ax[0].hist(data2, alpha = 0.3, bins = 30, label = 'b')
ax[0].hist(data3, alpha = 0.3, bins = 30, label = 'c')
ax[0].legend()
labels = ['a', 'b', 'c']
lst = [data,data2,data3]
ax[1].boxplot(lst, labels = labels) 
plt.show()

# 정규성 검정
from scipy.stats import shapiro
print(shapiro(data))
print(shapiro(data2))
print(shapiro(data3))
if (shapiro(data)[1] > 0.05) & (shapiro(data2)[1] > 0.05) & (shapiro(data3)[1] > 0.05):
    print('모든 변수가 정규성을 만족')
else:
    print('정규성을 만족하지 않음')
    
# 등분산 검정
from scipy.stats import levene
statistic, p_value = levene(data, data2, data3)
print(levene(data, data2, data3))
if p_value <= 0.05:
    print('귀무가설 기각 → 변수들의 분산이 동일하다고 할 수 없음')
else:
    print('귀무가설 기각 → 변수들의 분산이 동일하다고 할 수 있음')

# 정규성은 만족하나 등분산성은 만족하지 않으므로 welch test로 검정
import pingouin as pg
test_result = pg.welch_anova(dv = 'value', between = 'target', data = df)
display(test_result)
if test_result['p-unc'].values[0] < 0.05:
    print('귀무가설 기각 → 변수들의 평균에 차이가 있다고 할 수 있음')
else:
    print('귀무가설 기각 → 변수들의 평균에 차이가 있다고 할 수 없음')
[output]
ShapiroResult(statistic=0.9835560917854309, pvalue=0.2487850785255432) ShapiroResult(statistic=0.9923046231269836, pvalue=0.9479172825813293) ShapiroResult(statistic=0.9523518681526184, pvalue=0.19537365436553955)
모든 변수가 정규성을 만족
LeveneResult(statistic=4.530341210288782, pvalue=0.011923468290294024)
귀무가설 기각 → 변수들의 분산이 동일하다고 할 수 없음

귀무가설 기각 → 변수들의 평균에 차이가 있다고 할 수 없음

 


출처: https://www.datamanim.com/dataset/96_statsmodels/statsmodels.html

독립표본 검정 (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

Scipy-stats 주요 모듈

scipy.stats
│
├── 01 T-test
│   │
│   ├── ttest_1samp         (단일표본 t검정)
│   ├── ttest_ind           (독립표본 t검정)
│   └── ttest_rel           (대응표본 t검정) 
│ 
├── 02 비모수 검정
│   │
│   ├── mannwhitneyu        (맨-휘트니 U 검정 - 중위수 , 윌콕슨 순위합 검정과 동일하다 볼 수 있음)
│   ├── ranksums            (윌콕슨 순위합 검정 - 중위수)
│   └── wilcoxon            (윌콕슨 부호 순위합 검정)
│ 
├── 03 정규정 검정
│   │
│   ├── anderson            (Anderson-Darling , 데이터수가 상대적으로 많을 때)
│   ├── kstest              (Kolmogorov-Smirnov , 데이터수가 상대적으로 많을 때)
│   ├── mstats.normaltest
│   └── shapiro             (shapiro, 노말분포 가장 엄격하게 검정, 데이터수가 상대적으로 적을때)
│   
├── 04 등분산 검정
│   │
│   ├── bartlett
│   ├── fligner
│   └── levene
│
├── 05 카이제곱검정
│   │
│   ├── chi2_contingency     (카이제곱독립검정, 독립성 검정)
│   ├── chisquare            (카이제곱검정 , 적합도 검정)
│   └── fisher_exact         (피셔 정확 검정 - 빈도수가 5개 이하 셀의 수가 전체 셀의 20% 이상일 경우 사용 )
│
└── 06 ANOVA (일원분산분석)
    │
    └── f_oneway (분산 분석은  statmodels 모듈 사용 추천 )

 

정규성 검정

01. 다음 데이터의 정규성을 검증하라.

import pandas as pd 
import matplotlib.pyplot as plt
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/scipy/normal1.csv')
plt.hist(df)
plt.show()

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

from scipy.stats import shapiro
statistic, p_value = shapiro(df)
print(shapiro(df))
if p_value < 0.05:
    print('유의수준 5%에서 귀무가설 기각 → 정규성을 만족하지 않음')
else:
    print('유의수준 5%에서 귀무가설 채택 → 정규성 만족')

[output]


데이터 수: 1000
ShapiroResult(statistic=0.9981444478034973, pvalue=0.34849318861961365) 
유의수준 5%에서 귀무가설 채택 → 정규성 만족

 

02. 다음 데이터의 정규성을 검증하라.

df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/scipy/normal3.csv')
plt.hist(df)
plt.show()

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

from scipy.stats import shapiro
statistic, p_value = shapiro(df)
print(shapiro(df))
if p_value < 0.05:
    print('유의수준 5%에서 귀무가설 기각 → 정규성을 만족하지 않음')
else:
    print('유의수준 5%에서 귀무가설 채택 → 정규성 만족')
[output]

데이터 수: 1000
ShapiroResult(statistic=0.9578885436058044, pvalue=2.309641794969743e-16)
유의수준 5%에서 귀무가설 기각 → 정규성을 만족하지 않음

 

3. 위의 데이터를 로그변환 한 후에 정규성을 검증하라.

import numpy as np
log_df = np.log1p(df)
plt.hist(log_df)
plt.show()

statistic, p_value = shapiro(log_df)
print(shapiro(df))
if p_value < 0.05:
    print('유의수준 5%에서 귀무가설 기각 → 정규성 만족')
else:
    print('유의수준 5%에서 귀무가설 채택 → 정규성을 만족하지 않음.')
[output]
ShapiroResult(statistic=0.9578885436058044, pvalue=2.309641794969743e-16)
유의수준 5%에서 귀무가설 채택 → 정규성을 만족하지 않음.

 

04. 다음 데이터의 정규성을 검증하라.

df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/scipy/normal6.csv')
plt.hist(df)
plt.show()

print('데이터 수: ', len(df))
# 데이터의 수가 5000개 이상이므로 shapiro 검정은 부적절

from scipy.stats import anderson
print(anderson(df['data'].values))
statistic, critical_values, significance_level = anderson(df['data'].values)
if statistic > critical_values[2]:
    print('유의수준 5%에서 귀무가설 기각 → 정규성을 만족하지 않음')
else:
    print('유의수준 5%에서 귀무가설 채택 → 정규성 만족')
[output]

데이터 수: 6000

AndersonResult(statistic=0.8266993530414766, critical_values=array([0.576, 0.656, 0.786, 0.917, 1.091]), significance_level=array([15. , 10. ,  5. ,  2.5,  1. ]), fit_result=  params: FitParams(loc=299.95980319533163, scale=5.031806887885131)
 success: True
 message: '`anderson` successfully fit the distribution to the data.')

유의수준 5%에서 귀무가설 기각 → 정규성을 만족하지 않음


단일 표본 t검정(One-Sample t-test)

05. 100명의 키 정보가 들어 있는 데이터가 있다.데이터가 정규성을 만족하는지 확인하라.
그리고 평균키는 165라 판단할수 있는지 귀무가설과 대립가설을 설정한 후 유의수준 5%로 검정하라.

# 데이터 로드
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/scipy/height1.csv')
print('데이터 수: ', len(df))

# 정규성 검정
from scipy.stats import shapiro
statistic, p_value = shapiro(df)
print(shapiro(df))
if p_value < 0.05:
    print('유의수준 5%에서 귀무가설 기각 → 정규성을 만족하지 않음')
else:
    print('유의수준 5%에서 귀무가설 채택 → 정규성 만족')

# 가설 검정 → 정규성을 만족하므로 단일 표본 t-test로 검정
# H0 : 평균키는 165이다. vs H1 : 평균키는 165가 아니다.
from scipy.stats import ttest_1samp
statistic, p_value = ttest_1samp(df['height'].values, 165)
print(ttest_1samp(df['height'].values, 165))
if p_value < 0.05:
    print('유의수준 5%에서 귀무가설 기각 → 평균키는 165라고 할 수 없음')
else:
    print('유의수준 5%에서 귀무가설 채택 → 평균키는 165라고 할 수 있음')
[output]
데이터 수: 100
ShapiroResult(statistic=0.9872668981552124, pvalue=0.4558176100254059)
유의수준 5%에서 귀무가설 채택 → 정규성 만족
TtestResult(statistic=3.2017884987150644, pvalue=0.0018367171548080209, df=99)
유의수준 5%에서 귀무가설 기각 → 평균키는 165라고 할 수 없음

 

06. 100명의 키 정보가 들어 있는 데이터가 있다.데이터가 정규성을 만족하는지 확인하라.
그리고 평균키는 165라 판단할수 있는지 귀무가설과 대립가설을 설정한 후 유의수준 5%로 검정하라.

# 데이터 로드
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/scipy/height2.csv')

# 정규성 검정
print('데이터 수: ', len(df))

from scipy.stats import shapiro
statistic, p_value = shapiro(df)
print(shapiro(df))
if p_value < 0.05:
    print('유의수준 5%에서 귀무가설 기각 → 정규성을 만족하지 않음')
else:
    print('유의수준 5%에서 귀무가설 채택 → 정규성 만족')
    
# 가설 검정 → 정규성을 만족하지 않으므로 비모수 검정 중 윌콕슨 순위 부호 검정
# H0 : 평균키는 165이다. vs H1 : 평균키는 165가 아니다.
from scipy.stats import wilcoxon
statistic, p_value = wilcoxon(df['height']-165)
print(wilcoxon(df['height']-165))
if p_value < 0.05:
    print('유의수준 5%에서 귀무가설 기각 → 평균키는 165라고 할 수 없음')
else:
    print('유의수준 5%에서 귀무가설 채택 → 평균키는 165라고 할 수 있음')
[output]
데이터 수: 100
ShapiroResult(statistic=0.9672006368637085, pvalue=0.013552471995353699)
유의수준 5%에서 귀무가설 기각 → 정규성을 만족하지 않음
WilcoxonResult(statistic=1952.0, pvalue=0.04880534424649582)
유의수준 5%에서 귀무가설 기각 → 평균키는 165라고 할 수 없음

 

등분산 검정

7. 두개 학급의 시험성적에 대한 데이터이다. 그룹간 등분산 검정을 시행하라.

# 데이터 로드
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/scipy/scipy2.csv')
display(df.head())

score_a = df[df['class'] == 'A']['score']
score_b = df[df['class'] == 'B']['score']

# 등분산 검정
from scipy.stats import bartlett
from scipy.stats import fligner
from scipy.stats import levene

# bartlett 검정
s1, p1 = bartlett(score_a, score_b)
# fligner 검정(default는 median 기준)
s2, p2 = fligner(score_a, score_b)
# fligner 검정(mean 기준)
s3, p3 = fligner(score_a, score_b, center = 'mean')
# levene 검정(default는 median 기준)
s4, p4 = levene(score_a, score_b)
# levene 검정(mean 기준)
s5, p5 = levene(score_a, score_b, center = 'mean')

result = pd.DataFrame({'bartlett': [s1, p1], 'fligner_median': [s2, p2], 'fligner_mean': [s3, p3], 'levene_median': [s4, p4], 'levene_mean': [s5, p5]})
display(result.T.rename({0:'statistic', 1:'p_value'}, axis = 1))
for col in result.columns:
    if result[col][1] < 0.05:
        print(f'{col}: 유의수준 5%에서 귀무가설 기각 → 두 그룹의 분산이 같다고 할 수 없음')
    else:
        print(f'{col}: 유의수준 5%에서 귀무가설 채택 → 두 그룹의 분산이 같다고 할 수 있음')
[output]
bartlett: 유의수준 5%에서 귀무가설 채택 → 두 그룹의 분산이 같다고 할 수 있음
fligner_median: 유의수준 5%에서 귀무가설 채택 → 두 그룹의 분산이 같다고 할 수 있음
fligner_mean: 유의수준 5%에서 귀무가설 채택 → 두 그룹의 분산이 같다고 할 수 있음
levene_median: 유의수준 5%에서 귀무가설 채택 → 두 그룹의 분산이 같다고 할 수 있음
levene_mean: 유의수준 5%에서 귀무가설 채택 → 두 그룹의 분산이 같다고 할 수 있음

 

8. 두개 학급의 시험성적에 대한 데이터이다. 그룹간 등분산 검정을 시행하라.

# 데이터 로드
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/scipy/scipy3.csv')
display(df.head())

score_a = df[df['class'] == 'A']['score']
score_b = df[df['class'] == 'B']['score']

# 등분산 검정
from scipy.stats import bartlett
from scipy.stats import fligner
from scipy.stats import levene

# bartlett 검정
s1, p1 = bartlett(score_a, score_b)
# fligner 검정(default는 median 기준)
s2, p2 = fligner(score_a, score_b)
# fligner 검정(mean 기준)
s3, p3 = fligner(score_a, score_b, center = 'mean')
# levene 검정(default는 median 기준)
s4, p4 = levene(score_a, score_b)
# levene 검정(mean 기준)
s5, p5 = levene(score_a, score_b, center = 'mean')

result = pd.DataFrame({'bartlett': [s1, p1], 'fligner_median': [s2, p2], 'fligner_mean': [s3, p3], 'levene_median': [s4, p4], 'levene_mean': [s5, p5]})
display(result.T.rename({0:'statistic', 1:'p_value'}, axis = 1))
for col in result.columns:
    if result[col][1] < 0.05:
        print(f'{col}: 유의수준 5%에서 귀무가설 기각 → 두 그룹의 분산이 같다고 할 수 없음')
    else:
        print(f'{col}: 유의수준 5%에서 귀무가설 채택 → 두 그룹의 분산이 같다고 할 수 있음')
[output]

bartlett: 유의수준 5%에서 귀무가설 채택 → 두 그룹의 분산이 같다고 할 수 있음
fligner_median: 유의수준 5%에서 귀무가설 기각 → 두 그룹의 분산이 같다고 할 수 없음
fligner_mean: 유의수준 5%에서 귀무가설 기각 → 두 그룹의 분산이 같다고 할 수 없음
levene_median: 유의수준 5%에서 귀무가설 기각 → 두 그룹의 분산이 같다고 할 수 없음
levene_mean: 유의수준 5%에서 귀무가설 기각 → 두 그룹의 분산이 같다고 할 수 없음

 

9. 두개 학급의 시험성적에 대한 데이터이다. 그룹간 등분산 검정을 시행하라.

# 데이터 로드
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/scipy/scipy6.csv')
display(df.head())

# 등분산 검정
from scipy.stats import bartlett
from scipy.stats import fligner
from scipy.stats import levene

# bartlett 검정
s1, p1 = bartlett(df.A, df.B)
# fligner 검정(default는 median 기준)
s2, p2 = fligner(df.A, df.B)
# fligner 검정(mean 기준)
s3, p3 = fligner(df.A, df.B, center = 'mean')
# levene 검정(default는 median 기준)
s4, p4 = levene(df.A, df.B)
# levene 검정(mean 기준)
s5, p5 = levene(df.A, df.B, center = 'mean')

result = pd.DataFrame({'bartlett': [s1, p1], 'fligner_median': [s2, p2], 'fligner_mean': [s3, p3], 'levene_median': [s4, p4], 'levene_mean': [s5, p5]})
display(result.T.rename({0:'statistic', 1:'p_value'}, axis = 1))
for col in result.columns:
    if result[col][1] < 0.05:
        print(f'{col}: 유의수준 5%에서 귀무가설 기각 → 두 그룹의 분산이 같다고 할 수 없음')
    else:
        print(f'{col}: 유의수준 5%에서 귀무가설 채택 → 두 그룹의 분산이 같다고 할 수 있음')
[output]

bartlett: 유의수준 5%에서 귀무가설 채택 → 두 그룹의 분산이 같다고 할 수 있음
fligner_median: 유의수준 5%에서 귀무가설 기각 → 두 그룹의 분산이 같다고 할 수 없음
fligner_mean: 유의수준 5%에서 귀무가설 기각 → 두 그룹의 분산이 같다고 할 수 없음
levene_median: 유의수준 5%에서 귀무가설 기각 → 두 그룹의 분산이 같다고 할 수 없음
levene_mean: 유의수준 5%에서 귀무가설 기각 → 두 그룹의 분산이 같다고 할 수 없음

 

10. 두개 학급의 시험성적에 대한 데이터이다. 그룹간 등분산 검정을 시행하라.

# 데이터 로드
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/scipy/scipy5.csv')
display(df.head())

# 등분산 검정
from scipy.stats import bartlett
from scipy.stats import fligner
from scipy.stats import levene

# bartlett, fligner 두 검정은 nan값을 지우고 사용해야 함.
# LeveneResult의 경우 nan값이 포함된다면 연산이 제대로 수행되지 않음.

# bartlett 검정
s1, p1 = bartlett(df.A, df.B.dropna())
# fligner 검정(default는 median 기준)
s2, p2 = fligner(df.A, df.B.dropna())
# fligner 검정(mean 기준)
s3, p3 = fligner(df.A, df.B.dropna(), center = 'mean')
# levene 검정(default는 median 기준)
s4, p4 = levene(df.A, df.B.dropna())
# levene 검정(mean 기준)
s5, p5 = levene(df.A, df.B.dropna(), center = 'mean')

result = pd.DataFrame({'bartlett': [s1, p1], 'fligner_median': [s2, p2], 'fligner_mean': [s3, p3], 'levene_median': [s4, p4], 'levene_mean': [s5, p5]})
display(result.T.rename({0:'statistic', 1:'p_value'}, axis = 1))
for col in result.columns:
    if result[col][1] < 0.05:
        print(f'{col}: 유의수준 5%에서 귀무가설 기각 → 두 그룹의 분산이 같다고 할 수 없음')
    else:
        print(f'{col}: 유의수준 5%에서 귀무가설 채택 → 두 그룹의 분산이 같다고 할 수 있음')
[output]

bartlett: 유의수준 5%에서 귀무가설 채택 → 두 그룹의 분산이 같다고 할 수 있음
fligner_median: 유의수준 5%에서 귀무가설 기각 → 두 그룹의 분산이 같다고 할 수 없음
fligner_mean: 유의수준 5%에서 귀무가설 기각 → 두 그룹의 분산이 같다고 할 수 없음
levene_median: 유의수준 5%에서 귀무가설 기각 → 두 그룹의 분산이 같다고 할 수 없음
levene_mean: 유의수준 5%에서 귀무가설 기각 → 두 그룹의 분산이 같다고 할 수 없음

 


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

모듈리스트

sklearn
│
├── 01 preprocessing (전처리)
│   │
│   ├── 스케일러
│   │   ├── MinMaxScaler
│   │   ├── RobustScaler
│   │   └── StandardScaler
│   │
│   └── 인코더
│       ├── LabelEncoder
│       └── OneHotEncoder
│  
├── 02 model_selection (모델링 전처리)
│   │
│   ├── 데이터셋 분리
│   │   ├── KFold
│   │   ├── StratifiedKFold
│   │   └── train_test_split
│   │
│   └── 하이퍼파라미터 튜닝
│       └── GridSearchCV
│
├── 03 모델학습
│   │
│   ├── ensemble
│   │   ├── AdaBoostClassifier
│   │   ├── GradientBoostingClassifier
│   │   ├── RandomForestClassifier
│   │   └── RandomForestRegressor
│   │
│   ├── linear_model
│   │   ├── LogisticRegression
│   │   └── RidgeClassifier
│   │
│   ├── neighbors
│   │   └── KNeighborsClassifier
│   │
│   ├── svm
│   │   ├── SVC
│   │   └── SVR
│   │
│   └── tree
│       ├── DecisionTreeClassifier
│       ├── DecisionTreeRegressor
│       ├── ExtraTreeClassifier
│       └── ExtraTreeRegressor
│
├── 04 모델평가
│   │
│   ├── metrics
│   │   ├── accuracy_score
│   │   ├── classification_report
│   │   ├── confusion_matrix
│   │   ├── f1_score
│   │   ├── log_loss
│   │   ├── mean_absolute_error
│   │   ├── mean_squared_error
│   │   └── roc_auc_score
│   │
│   └── model (정의된 모델에서 추출)
│       ├── predict
│       └── predict_proba
│
└── 05 최종앙상블
    │
    └── ensemble
        ├── StackingClassifier
        ├── StackingRegressor
        ├── VotingClassifier
        └── VotingRegressor

 

01 데이터 전처리

MinMaxScaler

# 데이터 로드
import pandas as pd
train = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/airline/x_train.csv')
test = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/airline/x_test.csv')
display(train.head(5))
[output]

 

1. train 데이터의 Flight Distance 컬럼을 사이킷런 모듈을 이용하여 최솟값을 0 최댓값을 1값로 하는 데이터로 변환하고 scaling을 이름으로 하는 컬럼으로 데이터프레임에 추가하라.

from sklearn.preprocessing import MinMaxScaler

mm = MinMaxScaler()
train['scaling'] = mm.fit_transform(train['Flight Distance'].values.reshape(-1, 1))

# 시각화
import matplotlib.pyplot as plt
fig , ax = plt.subplots(1, 2)
ax[0].boxplot(train['Flight Distance'])
ax[0].set_xticklabels(['Raw'])
ax[1].boxplot(train['scaling'])
ax[1].set_xticklabels(['Scaling data'])
plt.show()
[output]

 

2. train 데이터의 Flight Distance 컬럼을 pandas의 내장함수만을 이용하여 최솟값을 0 최댓값을 1값로 하는 데이터로 변환하고 scaling을 이름으로 하는 컬럼으로 데이터프레임에 추가하라.

nom = train['Flight Distance'] - train['Flight Distance'].min()
denom = train['Flight Distance'].max() - train['Flight Distance'].min()
train['scaling'] = nom / denom


# 시각화
import matplotlib.pyplot as plt
fig , ax = plt.subplots(1, 2)
ax[0].boxplot(train['Flight Distance'])
ax[0].set_xticklabels(['Raw'])
ax[1].boxplot(train['scaling'])
ax[1].set_xticklabels(['Scaling data'])
plt.show()
[output]

 

3. train 데이터의 Age컬럼을 MinMax 스케일링 진행 하고 age_scaling컬럼에 추가하고 train셋과 같은 기준으로 test데이터의 Age를 스케일링하여 age_scaling에 추가하라.

from sklearn.preprocessing import MinMaxScaler

mm = MinMaxScaler()
mm.fit(train['Age'].values.reshape(-1,1))

train['age_scaling'] = mm.transform(train['Age'].values.reshape(-1, 1))
test['age_scaling'] = mm.transform(test['Age'].values.reshape(-1, 1))

display(test[['ID', 'age_scaling']].head(5))
[output]

 

StandardScaler

4. train 데이터의 Age컬럼을 pandas 기본 내장 모듈을 이용하여 정규화 스케일링을 진행 하고 age_scaling컬럼에 추가하라.

train['scaling'] = (train['Age'] - train['Age'].mean())/(train['Age'].std())

# 시각화
import matplotlib.pyplot as plt
fig , ax = plt.subplots(1, 2)
ax[0].boxplot(train['Age'])
ax[0].set_xticklabels(['Raw'])
ax[1].boxplot(train['scaling'])
ax[1].set_xticklabels(['Scaling data'])
plt.show()
[output]

 

5. train 데이터의 Age컬럼을 sklearn 모듈을 이용하여 정규화 스케일링을 진행 하고 age_scaling컬럼에 추가하고 train셋과 같은 기준으로 test데이터의 Age를 스케일링하여 age_scaling에 추가하라.

from sklearn.preprocessing import StandardScaler

sc = StandardScaler()
sc.fit(train['Age'].values.reshape(-1, 1))

train['age_scaling'] = sc.transform(train['Age'].values.reshape(-1, 1))
test['age_scaling'] = sc.transform(test['Age'].values.reshape(-1, 1))

display(test[['ID','age_scaling']].head(5))

# 시각화
import matplotlib.pyplot as plt
fig , ax = plt.subplots(1, 2)
ax[0].boxplot(train['Age'])
ax[0].set_xticklabels(['Raw'])
ax[1].boxplot(train['age_scaling'])
ax[1].set_xticklabels(['age_scaling'])
plt.show()
[output]

 

02 모델링 전처리

train_test_split

# 데이터 로드
import pandas as pd
x = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/drug/x_train.csv')
y = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/drug/y_train.csv')[['Drug']]
display(x.head(5))
display(y.head(5))
[output]

 

6. x,y데이터에서 train,test세트를 구분하고 train셋의 y값과 test셋의 y값의 unique한 value 값의 숫자를 출력하라. train:test는 7:3비율 , random_state =42로 고정

from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.3, random_state = 42)

t = pd.concat([y_train.value_counts(), y_test.value_counts()], axis = 1).rename(columns = {0:'train', 1:'test'}).reset_index()
display(t)
[output]

 

7. x,y데이터에서 train,test세트를 구분하고 train셋의 y값과 test셋의 y값의 unique한 value 값의 비율을 동일하게 추출하라. 7:3비율 , random_state =42로 고정

from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.3,random_state = 42, stratify = y)

t = pd.concat([y_train.value_counts(), y_test.value_counts()], axis = 1).rename(columns = {0:'train', 1:'test'}).reset_index()
display(t)
[output]

 

03 모델링

모델링의 기본 골격

  1. model import
  2. model 선언, 초기 하이퍼 파라미터 지정
  3. model.fit(x_train,y_train)을 통한 모델 학습
  4. 회귀, 분류 문제 모두 model.predict(x_validation) 을 통한 예측
  5. auc값을 구해야하는 경우 model.predict_proba(x_validation)을 통한 확률 추출 (svm모델의 경우 학습시 probability=True옵션 추가)
  6. 원하는 metric으로 모델 평가 eg) accuracy_score(y_validation, model.predict(x_validation))

sklearn 학습 모듈 모음

분류문제의 경우 -Classifier , 회귀문제의 경우 -Regressor 형식

#ensemble
from sklearn.ensemble import AdaBoostClassifier
from sklearn.ensemble import AdaBoostRegressor
from sklearn.ensemble import BaggingClassifier
from sklearn.ensemble import BaggingRegressor
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.ensemble import ExtraTreesRegressor
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import RandomForestRegressor



#linear_model
from sklearn.linear_model import BayesianRidge
from sklearn.linear_model import ElasticNet
from sklearn.linear_model import GammaRegressor
from sklearn.linear_model import HuberRegressor
from sklearn.linear_model import Lasso
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import LogisticRegression    # 분류
from sklearn.linear_model import Ridge
from sklearn.linear_model import SGDRegressor
from sklearn.linear_model import SGDClassifier # 분류


#neighbors
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neighbors import KNeighborsRegressor
from sklearn.neighbors import KNeighborsTransformer
from sklearn.neighbors import NearestNeighbors


#svm
from sklearn.svm import LinearSVC
from sklearn.svm import LinearSVR
from sklearn.svm import OneClassSVM
from sklearn.svm import SVR   # regression
from sklearn.svm import SVC   # classfier


#tree
from sklearn.tree import BaseDecisionTree
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import DecisionTreeRegressor
from sklearn.tree import ExtraTreeClassifier
from sklearn.tree import ExtraTreeRegressor

 

04 모델 평가

import sklearn.metrics
dir(sklearn.metrics)
[output]
['ConfusionMatrixDisplay',
'DetCurveDisplay',
'PrecisionRecallDisplay',
'RocCurveDisplay',
'SCORERS',
'__all__',
'__builtins__',
'__cached__',
'__doc__',
'__file__',
'__loader__',
'__name__',
'__package__',
'__path__',
'__spec__',
'_base',
'_classification',
'_pairwise_fast',
'_plot',
'_ranking',
'_regression',
'_scorer',
'accuracy_score',
'adjusted_mutual_info_score',
'adjusted_rand_score',
'auc',
'average_precision_score',
'balanced_accuracy_score',
'brier_score_loss',
'calinski_harabasz_score',
'check_scoring',
'classification_report',
'cluster',
'cohen_kappa_score',
'completeness_score',
'confusion_matrix',
'consensus_score',
'coverage_error',
'davies_bouldin_score',
'dcg_score',
'det_curve',
'euclidean_distances',
'explained_variance_score',
'f1_score',
'fbeta_score',
'fowlkes_mallows_score',
'get_scorer',
'hamming_loss',
'hinge_loss',
'homogeneity_completeness_v_measure',
'homogeneity_score',
'jaccard_score',
'label_ranking_average_precision_score',
'label_ranking_loss',
'log_loss',
'make_scorer',
'matthews_corrcoef',
'max_error',
'mean_absolute_error',
'mean_absolute_percentage_error',
'mean_gamma_deviance',
'mean_poisson_deviance',
'mean_squared_error',
'mean_squared_log_error',
'mean_tweedie_deviance',
'median_absolute_error',
'multilabel_confusion_matrix',
'mutual_info_score',
'nan_euclidean_distances',
'ndcg_score',
'normalized_mutual_info_score',
'pair_confusion_matrix',
'pairwise',
'pairwise_distances',
'pairwise_distances_argmin',
'pairwise_distances_argmin_min',
'pairwise_distances_chunked',
'pairwise_kernels',
'plot_confusion_matrix',
'plot_det_curve',
'plot_precision_recall_curve',
'plot_roc_curve',
'precision_recall_curve',
'precision_recall_fscore_support',
'precision_score',
'r2_score', 'rand_score', '
recall_score',
'roc_auc_score',
'roc_curve',
'silhouette_samples',
'silhouette_score',
'top_k_accuracy_score',
'v_measure_score',
'zero_one_loss']

 


출처 : https://www.datamanim.com/dataset/98_sklearn/sklearn.html#minmaxscaler

Merge, Concat

# 데이터 로드
DataUrl = 'https://raw.githubusercontent.com/Datamanim/pandas/main/mergeTEst.csv'
df = pd.read_csv(DataUrl)
df1 = df.iloc[:4,:]
df2 = df.iloc[4:,:]

display(df1)
display(df2)
[output]

 

091. df1과 df2 데이터를 하나의 데이터 프레임으로 합쳐라.

pd.concat([df1, df2])
[output]

# 데이터 로드
df.set_index('Location', inplace = True)
df3 = df.iloc[:2,:4]
df4 = df.iloc[5:,3:]

display(df3)
display(df4)
[output]

 

092. df3과 df4 데이터를 하나의 데이터 프레임으로 합쳐라. 둘다 포함하고 있는 년도에 대해서만 고려한다.

pd.concat([df3, df4], join = 'inner')
[output]

 

093. df3과 df4 데이터를 하나의 데이터 프레임으로 합쳐라. 모든 컬럼을 포함하고, 결측치는 0으로 대체한다.

pd.concat([df3, df4], join = 'outer').fillna(0)
[output]

# 데이터 로드
df5 = df.T.iloc[:7,:3]
df6 = df.T.iloc[6:,2:5]

display(df5)
display(df6)
[output]

 

094. df5과 df6 데이터를 하나의 데이터 프레임으로 merge함수를 이용하여 합쳐라. Algeria컬럼을 key로 하고 두 데이터 모두 포함하는 데이터만 출력하라.

pd.merge(df5, df6, on = 'Algeria', how = 'inner')
[output]

 

095. df5과 df6 데이터를 하나의 데이터 프레임으로 merge함수를 이용하여 합쳐라. Algeria컬럼을 key로 하고 합집합으로 합쳐라.

pd.merge(df5, df6, on = 'Algeria', how = 'outer')
[output]

 


출처 : https://www.datamanim.com/dataset/99_pandas/pandasMain.html

 Pivot

# 데이터 로드
DataUrl = 'https://raw.githubusercontent.com/Datamanim/pandas/main/under5MortalityRate.csv'
df = pd.read_csv(DataUrl)
df.head()
[output]

 

083. Indicator을 삭제하고 First Tooltip 컬럼에서 신뢰구간에 해당하는 표현을 지워라.

df.drop('Indicator', axis = 1, inplace = True)
import re
df['First Tooltip'] = df['First Tooltip'].apply(lambda x: re.findall(r'\d+[\.\d+]*', x)[0])
df.head()
[output]

 

084. 년도가 2015년 이상, Dim1이 Both sexes인 케이스만 추출하라.

df[(df.Period >= 2015) & (df.Dim1 == 'Both sexes')]
[output]

 

085. 84번 문제에서 추출한 데이터로 아래와 같이 나라에 따른 년도별 사망률을 데이터 프레임화 하라.

df_new = df[(df.Period >= 2015) & (df.Dim1 == 'Both sexes')]
df_new.pivot(index = 'Location', columns = 'Period', values = 'First Tooltip')
[output]

 

086. Dim1에 따른 년도별 사망비율의 평균을 구하라.

df['First Tooltip'] = df['First Tooltip'].astype('float')
df.pivot_table(index = 'Dim1', columns = 'Period', values = 'First Tooltip', aggfunc = 'mean')
[output]

 

087. 데이터에서 한국 KOR 데이터만 추출하라.

DataUrl = 'https://raw.githubusercontent.com/Datamanim/pandas/main/winter.csv'
df = pd.read_csv(DataUrl)
df.head()

df[df.Country == 'KOR']

 

088. 한국 올림픽 메달리스트 데이터에서 년도에 따른 medal 갯수를 데이터프레임화 하라.

kr_df = df[df.Country == 'KOR']
kr_df.pivot_table(index = 'Year', columns = 'Medal', aggfunc = 'size').fillna(0)
[output]

 

089. 전체 데이터에서 sport종류에 따른 성별수를 구하라.

df.pivot_table(index = 'Sport', columns = 'Gender', aggfunc = 'size')
[output]

 

090. 전체 데이터에서 Discipline종류에 따른 따른 Medal수를 구하라.

df.pivot_table(index = 'Discipline', columns = 'Medal', aggfunc = 'size')
[output]

 

 


출처 : https://www.datamanim.com/dataset/99_pandas/pandasMain.html

+ Recent posts