05-17 06:36
Notice
Recent Posts
Recent Comments
관리 메뉴

Scientific Computing & Data Science

[Artificial Intelligence] Multiple Linear Regression with R 본문

Artificial Intelligence

[Artificial Intelligence] Multiple Linear Regression with R

cinema4dr12 2016. 2. 6. 23:54

이번 글에서는 Multiple Linear Regression(다중 선형 회귀분석)에 대한 기초 통계 이론에 대한 소개와 이에 대한 R 프로그래밍에 대해 알아보기로 한다.

Theoretical Background

일반적으로 얻어지는 데이터들은 여러 개의 독립변수들에 의해 얻어진다. Multiple Linear Regression은 이러한 여러 개의 독립변수(설명변수)들과 종속변수(반응변수)들 간의 관계(모델)를 도출하고, 얻어진 모델을 이용하여 특정 독립 변수에 대한 추정값을 얻는 기법이다. 다음은 n개의 독립변수들을 갖는 Multiple Linear Regression 모델이다:


\( \displaystyle{ y = \beta_0 x_0 + \beta_1 x_1 + \cdots + \beta_n x_n +\epsilon = \begin{bmatrix}\beta_0 \ \beta_1 \ \beta_n \end{bmatrix} \begin{bmatrix} x_o \\ x_1 \\ \vdots \\ x_n \end{bmatrix} + \epsilon  }  \)


여기서 \(x_0 = 1\)이다. 특히 \(\beta_0 , \beta_1 , ..., \beta_n\)을 결정계수라고 부른다.


현실적으로, 종속변수들이 완전히 서로 독립일 경우는 극히 드물다. 즉, 종속변수가 어느 정도의 상관성이 존재하며, 각 독립변수 간의 상관성을 분석할 필요가 있는데 이를 다중공선성이라고 한다. 독립변수 간 상관성이 높을수록 Linear Regression 결과는 안 좋을 수 있다.

변수 선택

하나의 종속변수를 결정하는 독립변수들의 조합으로 만들어지는 회귀 모형은 무수히 많으므로, 가장 적합한 모형을 선택하는 방법이 필요하다. 일반적으로 결정계수가 크며 MSE가 최소화되는 회귀 모형을 찾도록 하며, 다음의 방법들이 알려져 있다.

모든 가능한 회귀(All Possible Regression)


모든 가능한 변수들의 조합으로 회귀 모형을 분석하는 것이다. 만약 n개의 변수가 있는 경우 1,2,...,n개까지의 변수의 조합으로 회귀 모형을 분석한다.

전진선택법 (Forward Selection)

반응변수에 영향을 줄 것으로 생각되는 n의 설명변수들 중에서 가장 크게 영향을 줄 것으로 판단되는 변수부터 하나씩 선택하여 더 이상 중요한 변수가 없다고 판단될 때 변수의 선택을 중단하는 방법이다.

후진제거법 (Backward Elimination)

반응변수에 영향을 주리라고 생각되는 n개의 설명변수들 중에서 가장 작게 영향을 주리라고 여겨지는 변수부터 하나씩 제거하여 나가면서 더 이상 제거할 변수가 없다고 판단될 때 변수의 제거를 중단하는 방법이다.

단계별 선택법 (Stepwise Selection)

전진선택법과 후진제거법의 단점을 보완한 방법으로 중요한 변수를 하나씩 선택하여 나가면서 이미 선택된 변수가 새로운 변수가 추가되면서 중요성을 상실하여 제거될 수 있는지를 매 단계별로 검토하는 방법이다.


Example - R

다중선형회귀분석에 대한 R 프로그래밍 예제를 살펴보자. 데이터는 R의 built-in data인 mtcars를 활용하도록 한다.


Motor Trend Car Road Tests

[Description]
The data was extracted from the 1974 Motor Trend US magazine, and comprises fuel consumption and 10 aspects of automobile design and performance for 32 automobiles (1973–74 models).

[Format]
A data frame with 32 observations on 11 variables.
[, 1]	mpg	Miles/(US) gallon
[, 2]	cyl	Number of cylinders
[, 3]	disp	Displacement (cu.in.)
[, 4]	hp	Gross horsepower
[, 5]	drat	Rear axle ratio
[, 6]	wt	Weight (1000 lbs)
[, 7]	qsec	1/4 mile time
[, 8]	vs	V/S
[, 9]	am	Transmission (0 = automatic, 1 = manual)
[,10]	gear	Number of forward gears
[,11]	carb	Number of carburetors



mtcars의 여섯 개의 변수를 선택한다: 반응변수(mpg), 설명변수(cyl, disp, hp, drat, wt)


mtcars_sel <- mtcars[, c(1:6)]


산점도 행렬과 상관계수로 다중공선성 1차 진단을 수행한다.


pairs(mtcars_sel, panel = panel.smooth)

cor(mtcars_sel[,-1])


[산점도 행렬]


[설명변수들간의 상관관계 분석]


> cor(mtcars_sel[,-1])

            cyl       disp         hp       drat         wt

cyl   1.0000000  0.9020329  0.8324475 -0.6999381  0.7824958

disp  0.9020329  1.0000000  0.7909486 -0.7102139  0.8879799

hp    0.8324475  0.7909486  1.0000000 -0.4487591  0.6587479

drat -0.6999381 -0.7102139 -0.4487591  1.0000000 -0.7124406

wt    0.7824958  0.8879799  0.6587479 -0.7124406  1.0000000


모델 생성 후 값을 추정한다. 우선 모델을 생성하도록 한다.


model <- lm(mpg~., data = mtcars_sel)


> model


Call:

lm(formula = mpg ~ ., data = mtcars_sel)


Coefficients:

(Intercept)          cyl         disp           hp         drat           wt  

   36.00836     -1.10749      0.01236     -0.02402      0.95221     -3.67329 


모델에 대한 전반적인 분석을 수행한다.


> summary(model)


Call:

lm(formula = mpg ~ ., data = mtcars_sel)


Residuals:

    Min      1Q  Median      3Q     Max 

-3.7014 -1.6850 -0.4226  1.1681  5.7263 


Coefficients:

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

(Intercept) 36.00836    7.57144   4.756  6.4e-05 ***

cyl         -1.10749    0.71588  -1.547  0.13394    

disp         0.01236    0.01190   1.039  0.30845    

hp          -0.02402    0.01328  -1.809  0.08208 .  

drat         0.95221    1.39085   0.685  0.49964    

wt          -3.67329    1.05900  -3.469  0.00184 ** 

---

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


Residual standard error: 2.538 on 26 degrees of freedom

Multiple R-squared:  0.8513, Adjusted R-squared:  0.8227 

F-statistic: 29.77 on 5 and 26 DF,  p-value: 5.618e-10


F-statistic, p-value 등 각각이 의미하는 바는, 통계 기초 이론을 통해 알아보기 바란다.


이제 생성된 모델을 기반으로 값을 예측해 보자.

cyl = 12, disp = 170, hp = 120, drat = 4.0, wt = 2.7에 대하여 mpg가 어떤 값을 갖는지 예측해 본다.


> predict(model, data.frame(cyl = 12, disp = 170, hp = 120, drat = 4.0, wt = 2.7))

       1 

15.82813


단계별선택법(Stepwise Selection)으로 변수선택을 해보자.


> out <- step(model, direction = "both")

Start:  AIC=64.95

mpg ~ cyl + disp + hp + drat + wt


       Df Sum of Sq    RSS    AIC

- drat  1     3.018 170.44 63.526

- disp  1     6.949 174.38 64.255

<none>              167.43 64.954

- cyl   1    15.411 182.84 65.772

- hp    1    21.066 188.49 66.746

- wt    1    77.476 244.90 75.124


Step:  AIC=63.53

mpg ~ cyl + disp + hp + wt


       Df Sum of Sq    RSS    AIC

- disp  1     6.176 176.62 62.665

<none>              170.44 63.526

- hp    1    18.048 188.49 64.746

+ drat  1     3.018 167.43 64.954

- cyl   1    24.546 194.99 65.831

- wt    1    90.925 261.37 75.206


Step:  AIC=62.66

mpg ~ cyl + hp + wt


       Df Sum of Sq    RSS    AIC

<none>              176.62 62.665

- hp    1    14.551 191.17 63.198

+ disp  1     6.176 170.44 63.526

- cyl   1    18.427 195.05 63.840

+ drat  1     2.245 174.38 64.255

- wt    1   115.354 291.98 76.750

> out


Call:

lm(formula = mpg ~ cyl + hp + wt, data = mtcars_sel)


Coefficients:

(Intercept)          cyl           hp           wt  

   38.75179     -0.94162     -0.01804     -3.16697 


cyl, hp, wt의 변수가 선택되었음을 알 수 있다. Fitting Model에 대한 summary를 살펴보자.


> summary(out)


Call:

lm(formula = mpg ~ cyl + hp + wt, data = mtcars_sel)


Residuals:

    Min      1Q  Median      3Q     Max 

-3.9290 -1.5598 -0.5311  1.1850  5.8986 


Coefficients:

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

(Intercept) 38.75179    1.78686  21.687  < 2e-16 ***

cyl         -0.94162    0.55092  -1.709 0.098480 .  

hp          -0.01804    0.01188  -1.519 0.140015    

wt          -3.16697    0.74058  -4.276 0.000199 ***

---

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


Residual standard error: 2.512 on 28 degrees of freedom

Multiple R-squared:  0.8431, Adjusted R-squared:  0.8263 

F-statistic: 50.17 on 3 and 28 DF,  p-value: 2.184e-11


따라서 Fitting Model에 대한 formula는


> formula(out)

mpg ~ cyl + hp + wt


이번에는 선택된 변수만으로 Model을 생성해보자.


model <- lm(formula(out), data = mtcars_sel)


> model


Call:

lm(formula = formula(out), data = mtcars_sel)


Coefficients:

(Intercept)          cyl           hp           wt  

   38.75179     -0.94162     -0.01804     -3.16697


Fitting Model에 대한 summary는 다음과 같다.


> summary(model)


Call:

lm(formula = formula(out), data = mtcars_sel)


Residuals:

    Min      1Q  Median      3Q     Max 

-3.9290 -1.5598 -0.5311  1.1850  5.8986 


Coefficients:

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

(Intercept) 38.75179    1.78686  21.687  < 2e-16 ***

cyl         -0.94162    0.55092  -1.709 0.098480 .  

hp          -0.01804    0.01188  -1.519 0.140015    

wt          -3.16697    0.74058  -4.276 0.000199 ***

---

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


Residual standard error: 2.512 on 28 degrees of freedom

Multiple R-squared:  0.8431, Adjusted R-squared:  0.8263 

F-statistic: 50.17 on 3 and 28 DF,  p-value: 2.184e-11


이제 얻은 결과를 이용하여 mpg 값을 예측해 보자.


predict(model, data.frame(cyl = 12, disp = 170, hp = 120, drat = 4.0, wt = 2.7))


> predict(model, data.frame(cyl = 12, disp = 170, hp = 120, drat = 4.0, wt = 2.7))

       1 

16.73699 


전진선택법(Forward Selection)에 의한 변수선택을 하려면 다음과 같이 명령을 입력한다.


out <- step(model, direction = "forward")


또는 후진제거법(Backward Elimination)에 의한 변수선택을 하려면 다음과 같이 명령을 입력한다.


out <- step(model, direction = "backward")


Comments