기본 콘텐츠로 건너뛰기

로지스틱 회귀 분석 (3)





 모델 선택은 분석에 있어 가장 어려운 과정이 될 수 있습니다. 이것 저것 변수를 많이 넣게 되면 오히려 각 변수간 상호 작용의 가능성이 커지고 현상을 설명하는 모델이 너무 복잡해지거나 과보정이 되어 정확한 상관 관계를 보여주지 못할 수 있습니다. 반대로 너무 변수를 적게 넣으면 다른 교란 변수에 의한 영향력을 보정할 수 없게 됩니다. 경우에 따라서는 저자의 주장에 적당한 모델을 선택해 P값을 해킹하는 일이 발생할 수도 있습니다. 


 따라서 연구에 따라서 모델 선택을 어떻게 했는지가 매우 중요한 이슈가 될 수 있습니다. 논문 심사에서 중요하게 보는 문제가 될 수 있기 때문에 구체적으로 왜 이렇게 모델을 선택하고 중요한 변수를 넣거나 넣지 않은 이유를 설명할 수 있어야 합니다. 로지스틱 회귀 분석에서 모델 선정에 중요한 파라미터는 바로 AIC (akaike information criterion)입니다. AIC 가 낮을수록 좋은 모델이라고 할 수 있습니다. 따라서 AIC는 summary()에서 기본으로 보여줍니다. 



library(moonBook)
library(mlbench)

data(PimaIndiansDiabetes)
pima <- pimaindiansdiabetes="" span="">

pima<-subset pima="" pressure="">0)
pima<-subset mass="" pima="">0)
pima<-subset glucose="" pima="">0)

pima$obesity[pima$mass>=30]=2
pima$obesity[pima$mass<30 span="">
pima$obesity[pima$mass<25 span="">
table(pima$obesity)

out=glm(diabetes~factor(obesity)+pressure+glucose+age+pedigree,family=binomial,data=pima)
summary(out)
extractOR(out)

> out=glm(diabetes~factor(obesity)+pressure+glucose+age+pedigree,family=binomial,data=pima)
> summary(out)

Call:
glm(formula = diabetes ~ factor(obesity) + pressure + glucose + 
    age + pedigree, family = binomial, data = pima)

Deviance Residuals: 
    Min       1Q   Median       3Q      Max  
-2.8133  -0.7259  -0.3803   0.7219   2.5514  

Coefficients:
                  Estimate Std. Error z value Pr(>|z|)    
(Intercept)      -8.223152   0.831018  -9.895  < 2e-16 ***
factor(obesity)1  1.225678   0.471464   2.600 0.009330 ** 
factor(obesity)2  2.174498   0.441818   4.922 8.58e-07 ***
pressure         -0.001569   0.008389  -0.187 0.851656    
glucose           0.034531   0.003597   9.600  < 2e-16 ***
age               0.032288   0.008562   3.771 0.000163 ***
pedigree          0.984527   0.305211   3.226 0.001257 ** 
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 931.94  on 723  degrees of freedom
Residual deviance: 676.98  on 717  degrees of freedom
AIC: 690.98

Number of Fisher Scoring iterations: 5

> extractOR(out)
                   OR  lcl   ucl      p
(Intercept)      0.00 0.00  0.00 0.0000
factor(obesity)1 3.41 1.35  8.58 0.0093
factor(obesity)2 8.80 3.70 20.91 0.0000
pressure         1.00 0.98  1.01 0.8517
glucose          1.04 1.03  1.04 0.0000
age              1.03 1.02  1.05 0.0002
pedigree         2.68 1.47  4.87 0.0013


 여기서 AIC는 690.98입니다. 만약 여기서 혈압 (pressure)를 빼면 어떨까요?

> out=glm(diabetes~factor(obesity)+glucose+age+pedigree,family=binomial,data=pima)
> summary(out)

Call:
glm(formula = diabetes ~ factor(obesity) + glucose + age + pedigree, 
    family = binomial, data = pima)

Deviance Residuals: 
    Min       1Q   Median       3Q      Max  
-2.8102  -0.7283  -0.3808   0.7295   2.5530  

Coefficients:
                  Estimate Std. Error z value Pr(>|z|)    
(Intercept)      -8.306914   0.701427 -11.843  < 2e-16 ***
factor(obesity)1  1.224595   0.471094   2.599  0.00934 ** 
factor(obesity)2  2.165589   0.438837   4.935 8.02e-07 ***
glucose           0.034457   0.003573   9.644  < 2e-16 ***
age               0.031815   0.008175   3.892 9.95e-05 ***
pedigree          0.985863   0.305021   3.232  0.00123 ** 
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 931.94  on 723  degrees of freedom
Residual deviance: 677.01  on 718  degrees of freedom
AIC: 689.01

 그 결과 AIC는 689.01으로 소폭 감소했습니다. 그 다음엔 가족력 (pedigree)을 빼보겠습니다. 


> out=glm(diabetes~factor(obesity)+glucose+age,family=binomial,data=pima)
> summary(out)

Call:
glm(formula = diabetes ~ factor(obesity) + glucose + age, family = binomial, 
    data = pima)

Deviance Residuals: 
    Min       1Q   Median       3Q      Max  
-2.2393  -0.7657  -0.3874   0.7429   2.6414  

Coefficients:
                  Estimate Std. Error z value Pr(>|z|)    
(Intercept)      -7.911011   0.680699 -11.622  < 2e-16 ***
factor(obesity)1  1.249056   0.474545   2.632 0.008486 ** 
factor(obesity)2  2.219298   0.442638   5.014 5.34e-07 ***
glucose           0.034991   0.003523   9.932  < 2e-16 ***
age               0.030844   0.008092   3.812 0.000138 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 931.94  on 723  degrees of freedom
Residual deviance: 687.99  on 719  degrees of freedom
AIC: 697.99

Number of Fisher Scoring iterations: 5


 그 결과 697.99으로 소폭 증가했습니다. 이 세 모델은 AIC가 비슷하지만 그래도 두 번째 모델이 가장 작다는 결론을 내릴 수 있습니다. 하지만 어떤 변수를 넣고 뺄지는 만약 변수의 숫자가 매우 많아지면 상당한 복잡한 문제가 됩니다. 당연히 이를 자동화할 수 있는 방법이 있는데 바로 단계적 (stepwise model selection)으로 모델을 결정하는 것입니다. R에서는 step ()을 이용해서 구현할 수 있으며 가장 많은 모델에서 하나씩 줄여나가며 최적의 조합을 찾는 backward selection과 반대로 하나씩 변수를 추가해가면서 최적의 모델을 찾는 forward selection 두 가지 방법이 있습니다. 


 우선 5개의 변수를 가진 모델에서 하나씩 줄여나가는 backward 방식을 사용해 보겠습니다. 



full.model=glm(diabetes~factor(obesity)+pressure+glucose+age+pedigree,family=binomial,data=pima)
reduce.model=step(full.model,direction = "backward")


우선 가장 변수가 많은 모델을 결정한 다음 이를 step에 넣고 backward로 방향을 정해줍니다. 

> reduce.model=step(full.model,direction = "backward")
Start:  AIC=690.98
diabetes ~ factor(obesity) + pressure + glucose + age + pedigree

                  Df Deviance    AIC
- pressure         1   677.01 689.01
                 676.98 690.98
- pedigree         1   687.91 699.91
- age              1   691.44 703.44
- factor(obesity)  2   721.17 731.17
- glucose          1   793.36 805.36

Step:  AIC=689.01
diabetes ~ factor(obesity) + glucose + age + pedigree

                  Df Deviance    AIC
                 677.01 689.01
- pedigree         1   687.99 697.99
- age              1   692.36 702.36
- factor(obesity)  2   722.21 730.21
- glucose          1   794.37 804.37


 선정된 모델은 summary로 더 간결하게 알 수 있습니다. 


summary(reduce.model)


> summary(reduce.model)

Call:
glm(formula = diabetes ~ factor(obesity) + glucose + age + pedigree, 
    family = binomial, data = pima)

Deviance Residuals: 
    Min       1Q   Median       3Q      Max  
-2.8102  -0.7283  -0.3808   0.7295   2.5530  

Coefficients:
                  Estimate Std. Error z value Pr(>|z|)    
(Intercept)      -8.306914   0.701427 -11.843  < 2e-16 ***
factor(obesity)1  1.224595   0.471094   2.599  0.00934 ** 
factor(obesity)2  2.165589   0.438837   4.935 8.02e-07 ***
glucose           0.034457   0.003573   9.644  < 2e-16 ***
age               0.031815   0.008175   3.892 9.95e-05 ***
pedigree          0.985863   0.305021   3.232  0.00123 ** 
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 931.94  on 723  degrees of freedom
Residual deviance: 677.01  on 718  degrees of freedom
AIC: 689.01

Number of Fisher Scoring iterations: 5


 선택된 모델은 앞서 본 두 번째 모델입니다. 반대로 forward의 경우 처음에는 변수가 하나도 없는 모델에서 시작해야 합니다. scope에 full model을 적어주고 중간 결과를 생략하기 위해 trace = 0을 표기했습니다. 


model1=glm(diabetes~1,family=binomial,data=pima)
forward.model=step(model1, direction = "forward",
                   scope=(diabetes~factor(obesity)+pressure+glucose+age+pedigree), trace = 0)
summary(forward.model)


> summary(forward.model)

Call:
glm(formula = diabetes ~ glucose + factor(obesity) + age + pedigree, 
    family = binomial, data = pima)

Deviance Residuals: 
    Min       1Q   Median       3Q      Max  
-2.8102  -0.7283  -0.3808   0.7295   2.5530  

Coefficients:
                  Estimate Std. Error z value Pr(>|z|)    
(Intercept)      -8.306914   0.701427 -11.843  < 2e-16 ***
glucose           0.034457   0.003573   9.644  < 2e-16 ***
factor(obesity)1  1.224595   0.471094   2.599  0.00934 ** 
factor(obesity)2  2.165589   0.438837   4.935 8.02e-07 ***
age               0.031815   0.008175   3.892 9.95e-05 ***
pedigree          0.985863   0.305021   3.232  0.00123 ** 
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 931.94  on 723  degrees of freedom
Residual deviance: 677.01  on 718  degrees of freedom
AIC: 689.01

Number of Fisher Scoring iterations: 5




 역시 같은 결과가 나왔습니다. stepwise 방식은 널리 사용되기는 하지만 사실 만능은 아닙니다. AIC와 독립적으로 결과 변수를 설명하는데 매우 중요한 원인이 되는 변수가 있을 수 있으며 이를 빼는 것이 반드시 좋은 것이 아닐 수 있기 때문입니다. stepwise 방식을 사용할 경우 모델 선정에서 주관적으로 결정한 것이 아니라 객관적인 기준을 가지고 선정한 인상을 줄 수 있지만, 이 역시 사용자가 주관적으로 특정 변수를 뺄 가능성은 얼마든지 존재합니다. 따라서 필수적인 방식은 아니지만, 모델 선정에 있어 참고할 수 있는 중요한 방법인 점은 분명합니다. 

댓글

이 블로그의 인기 게시물

100 테슬라급 자기장 도달

 미국의 로스 알라모스 국립 연구소 (Los Alamos National Laboratory) 에서 과학자들이 지금까지 인간이 개발한 가장 강력한 자기장을 발생시키는 장치 개발에 도전하고 있습니다. 자기장의 세기를 나타내는 방법으로 자기력선의 밀도를 나타내기 위해 단위 면적당 자기력선의 수를 표시하는 단위인 테슬라 (T) 가 있습니다. (1T = 1Wb/㎡  웨버 (Wb) 는 자속의 단위)   의료용으로 사용되는 초전도체를 이용한 MRI 의 경우 1.5 - 3 테슬라급의 강력한 자기장으로 인체 내부를 볼 수 있게 만들지만 과학 연구용으로 이보다 더 강력한 자기장이 필요할 수 있습니다. 최근에 등장한 90 테슬라급 자기장에 이어 이번에 로스 알라모스 국립 연구소에서는 100 테슬라급인 100.75 T 를 실현 했다고 합니다.   이를 구현한 것은 18000 파운드 (8.16 톤 정도) 의 코일과 여기에 에너지를 공급할 1200 메가줄 (Megajoule) 급 모터 제네레이터등의 설비입니다.  (   The 1,200-megajoule motor generator that powers the magnetic pulse.  )  이와 같은 연구를 통해 알아내고자 하는 것은  Quantum Phase transitions and new ultra high field magnetic states Electronic Structure determination Topologically protected states of matter  로 요약할 수 있다고 합니다.   아무튼 수 T 급 MRI 만 해도 자기장의 힘이 엄청난데 100 T 라니 엄청난 자기장이네요. 이는 지구 자기장 세기보다 200만배 강력한 (물론 좁은 범위에서 작용하는 자기장이라 지구 전체...

고대 양서류 이야기 (2) - 악어를 닮은 거대 양서류들

  페름기에는 다양한 양막류가 진화해서 앞서 소개한 육상형 템노스폰딜리는 점차 설 자리를 잃게 됩니다. 하지만 양서류는 본래 자신의 서식지인 물과 습지에서 여전히 번성을 누렸습니다. 당시에는 악어류 같은 대형 양서형 파충류도 없던 시절이었기 때문에 이와 비슷한 생태학적 지위는 여전히 양서류의 몫이었습니다. 이들에 대한 이야기는 제 책인 포식자에서 비교적 간단히 다뤘는데, 오늘은 여기에 대한 보충 설명입니다.  책 정보:  http://book.naver.com/bookdb/book_detail.nhn?bid=13347200 Yes 24:  http://www.yes24.com/24/goods/58772859 11번가:  http://books.11st.co.kr/product/SellerProductDetail.tmall?method=getSellerProductDetail&prdNo=1977867160 알라딘:  http://www.aladin.co.kr/shop/wproduct.aspx?ItemId=134877825 교보문고:  http://www.kyobobook.co.kr/product/detailViewKor.laf?ejkGb=KOR&mallGb=KOR&barcode=9788970447988&orderClick=LAG&Kc= 인터파크 :  http://book.interpark.com/product/BookDisplay.do?_method=detail&sc.prdNo=279593764&sc.saNo=003002003&bid1=search_auto&bid2=detail&bid3=prd_img&bid4=001 영풍문고:  http://www.ypbooks.co.kr/book.yp?bookcd=100843205&gubun=NV ...

이빨이 다시 진화한 개구리

  ( CT scans of Gastrotheca guentheri skulls revealed what appeared to be identical rows of teeth on both the upper and lower jaws, which researchers later confirmed through dissection. Credit: Florida Museum/Daniel Paluh )  개구리는 2억년 전 진화 과정에서 이빨을 잃어버리고 큰 턱과 혀를 이용해 곤충 같은 작은 먹이를 잡아 먹는 방향으로 진화했습니다. 파충류나 포유류 같은 다른 사지류와의 경쟁에서 밀려 양서류가 쇠퇴하고 멸종하던 시기에도 개구리는 여전히 생존할 수 있었던 비결입니다.   이빨이 없는 덕분에 큰 혀를 발사하기 편해졌을지는 모르지만, 이빨이 없으면 종종 불편할 때가 있습니다. 씹는 대신 삼키기 때문에 음식을 씹을 수 없다는 점은 문제되지 않지만, 필사적으로 달아나려는 먹이를 잡기 힘들기 때문입니다. 이런 이유 때문에 일부 개구리는 이빨 같이 보이는 엄니 (fang)을 지니고 있으나 이는 사라진 이빨이 다시 난 것이 아니라 다른 부분이 진화한 것입니다.   이는 돌로의 법칙 ( Dollo's Law )으로 알려져 있습니다. 진화 과정에서 퇴화한 부분이 다시 생겨나지 않으며 대신 필요하면 다른 부분이 진화해 그 역할을 대신한다는 것입니다. 예를 들어 아가미가 사라진 사지 동물은 다시 물에 들어온다고 해도 아가미가 다시 생기진 않습니다. 대신 고래처럼 폐가 커져서 그 기능을 대신하게 됩니다.   하지만 모든 법칙엔 예외가 있기 마련입니다. 남미에서 발견된 멸종 위기 개구리 중 하나인 구엔터 유대류 개구리 ( Gastrotheca guentheri, Guenther's marsupial frog, dentate marsupial frog)는 완전한 형태의 이빨을 지니고 있습니다. 참고로 유대류 개구리라는 명칭은...