R의 선형회귀분석 모델을 자동으로 선정해주는 프로그램을 이용하여 ggplot2의 mpg데이터를 분석하여 보았다.

데이터는 numeric과 같은 숫자만 가능하기 때문에 선정한 데이터는 displ, cty, hwy를 선택하였다.

displ은 배기량, cty는 시내주행 연비, hwy는 고속주행 연비이다.

step(lm(종속변수~설명변수, 데이터세트), scope=list(lower=~1, upper=~설명변수), direction="변수선택방법") 함수를 이용하여 변수를 선택하였다.



=============================== R ===============================

library("ggplot2")

# mpg 데이터 불러오기.

mpg <- ggplot2::mpg

# 데이터 타입 확인.

class(mpg)

# 테이블과 데이터 프레임의 혼합이기 때문에 데이터 프레임으로 바꿔준다.

mpg <- data.frame(mpg)

# 데이터 확인

mpg


# displ, cty, hwy

# 배기량,시내주행 연비, 고속주행 연비

# 배기량과 시내주행 연비, 고속주행 연비의 회귀분석

step(lm(displ~1, mpg), scope=list(lower=~1,upper=~cty+hwy), direction = "forward")

step(lm(displ~1, mpg), scope=list(lower=~1,upper=~cty+hwy), direction = "backward")

step(lm(displ~1, mpg), scope=list(lower=~1,upper=~cty+hwy), direction = "both")


# 선택한 선형회귀를 확인  

pick <- lm(formula = displ ~ cty, data = mpg)

summary(pick)


=============================== R ===============================




============================== Result ==============================

> step(lm(displ~1, mpg), scope=list(lower=~1,upper=~cty+hwy), direction = "forward")

Start:  AIC=120.88

displ ~ 1


       Df Sum of Sq    RSS      AIC

+ cty   1    247.99 140.93 -114.657

+ hwy   1    228.21 160.70  -83.927

<none>              388.91  120.881


Step:  AIC=-114.66

displ ~ cty


       Df Sum of Sq    RSS     AIC

<none>              140.93 -114.66

+ hwy   1  0.032839 140.89 -112.71


Call:

lm(formula = displ ~ cty, data = mpg)


Coefficients:

(Intercept)          cty  

     7.5585      -0.2424  


> step(lm(displ~1, mpg), scope=list(lower=~1,upper=~cty+hwy), direction = "backward")

Start:  AIC=120.88

displ ~ 1



Call:

lm(formula = displ ~ 1, data = mpg)


Coefficients:

(Intercept)  

      3.472  


> step(lm(displ~1, mpg), scope=list(lower=~1,upper=~cty+hwy), direction = "both")

Start:  AIC=120.88

displ ~ 1


       Df Sum of Sq    RSS      AIC

+ cty   1    247.99 140.93 -114.657

+ hwy   1    228.21 160.70  -83.927

<none>              388.91  120.881


Step:  AIC=-114.66

displ ~ cty


       Df Sum of Sq    RSS     AIC

<none>              140.93 -114.66

+ hwy   1     0.033 140.89 -112.71

- cty   1   247.987 388.91  120.88


Call:

lm(formula = displ ~ cty, data = mpg)


Coefficients:

(Intercept)          cty  

     7.5585      -0.2424  


> lm(formula = displ ~ cty, data = mpg)


Call:

lm(formula = displ ~ cty, data = mpg)


Coefficients:

(Intercept)          cty  

     7.5585      -0.2424  





###### 선택한 선형회귀식 ######

> pick <- lm(formula = displ ~ cty, data = mpg)

> summary(pick)


Call:

lm(formula = displ ~ cty, data = mpg)


Residuals:

    Min      1Q  Median      3Q     Max 

-1.8800 -0.5072 -0.1392  0.4830  3.0776 


Coefficients:

            Estimate Std. Error t value Pr(>|t|)    

(Intercept)   7.5585     0.2086   36.24   <2e-16 ***

cty          -0.2424     0.0120  -20.20   <2e-16 ***

---

Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1


Residual standard error: 0.7794 on 232 degrees of freedom

Multiple R-squared:  0.6376, Adjusted R-squared:  0.6361 

F-statistic: 408.2 on 1 and 232 DF,  p-value: < 2.2e-16

============================== Result ==============================




먼저 direction의 forward, backward, both를 설명하자면 아래와 같다.
forward      -- 변수를 선택하지 않고 하나씩 추가하면서 가장 나은 형태를 선택
backward   -- 변수를 전부 넣고 하나씩 빼면서 가장 나은 형태를 선택
both            -- 변수를 하나씩 넣으면서 기존의 방법보다 안 좋아지는 변수를 제외하며 선택

먼저 선택된 선형회귀식은 다음과 같다.
displ = -0.2424 * cty + 7.5585

이는 forward, both에서 선택된 식이다.

이제 선택된 식을 기반으로 선형회귀분석을 실시한 결과를 해석해보자.

수정된 결정계수는 63.6%이고 F-statistic은 408.2, p-value는 2.2*10^(-16)이다.
Adjusted R-squared:  0.6361  
F-statistic: 408.2 on 1 and 232 DF,  p-value: < 2.2e-16

F-statistic, p-value는 적절하지만 결정계수가  낮게 나왔다고 판단된다.

따라서 좋은 분석이 아니라고 생각한다.

그렇지만 일단 얻은 데이터와 자료의 시각화를 해보았다.



=============================== R ===============================

pick <- lm(formula = displ ~ cty, data = mpg)

plot(pick)

=============================== R ===============================



위는 회귀 분석 모델 진단 그래프들이다.





산점도로 확인해보니 역시나 1차로는 영 보기 좋지가 않다. 자 그럼 다차 그래프 선형회귀를 시행해보자.

위에서 3차 이상이라고 말했으니 3차부터 확인해보자.



================================ R ================================

# make new column cty2, cty3

mpg$cty2 <- mpg$cty^2

mpg$cty3 <- mpg$cty^3

# new linear regression

step(lm(displ~1, mpg), scope=list(lower=~1,upper=~cty+cty2+cty3), direction = "forward")

pick <- lm(formula = displ ~ cty + cty2 + cty3, data = mpg)

summary(pick)

================================ R ================================


============================== Result ==============================

> pick <- lm(formula = displ ~ cty + cty2 + cty3, data = mpg)

> summary(pick)


Call:

lm(formula = displ ~ cty + cty2 + cty3, data = mpg)


Residuals:

     Min       1Q   Median       3Q      Max 

-1.85017 -0.51245  0.02756  0.35983  3.04013 


Coefficients:

              Estimate Std. Error t value Pr(>|t|)    

(Intercept)  5.9072130  1.5281312   3.866 0.000144 ***

cty          0.2067654  0.2474421   0.836 0.404241    

cty2        -0.0329365  0.0126695  -2.600 0.009935 ** 

cty3         0.0006998  0.0002045   3.422 0.000736 ***

---

Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1


Residual standard error: 0.7011 on 230 degrees of freedom

Multiple R-squared:  0.7093, Adjusted R-squared:  0.7055 

F-statistic: 187.1 on 3 and 230 DF,  p-value: < 2.2e-16


============================== Result ==============================



이전보다 결정계수는 올라가고 F-statistic은 떨어졌다. 


Coefficients: 
              Estimate Std. Error t value Pr(>|t|)     
(Intercept)  5.9072130  1.5281312   3.866 0.000144 *** 
cty           0.2067654  0.2474421   0.836 0.404241     
cty2        -0.0329365  0.0126695  -2.600 0.009935 **  
cty3         0.0006998  0.0002045   3.422 0.000736 ***

cty의 Pr이 다른 값보다 훨씬 높기 때문에 제거를 할까 생각도 해보았지만 역시 그것만으로는 해결이 안 되는 무언가가 있다는 생각이 든다.


일단 내일 생각을 다시 해봐야겠다.

+ Recent posts