R OLS 회귀분석 - R OLS hoegwibunseog

#최소제곱 #단순회귀 #다항회귀 #회귀의유래

R OLS 회귀분석 - R OLS hoegwibunseog

OLS regression이란

Ordinary Least Square즉 최소제곱을 이용한 것을 말한다.

1. 최소제곱

최소제곱을 이해해보자.

일반적으로는 잔차(residual) y-(ax+b)를 제곱하여 더한 값을 최소로 하는 a,b를 구하는 것이다. 수학적으로는 편미분을 해서 구해야하겠지만 R을 이용하여 optim()함수를 이용하여 보자.

x=c(1,2,3,4) y=c(2,3,5,4) plot(x,y,pch=20, col="red") #type="o" 추가하면 선 연결 abline(lm(y~x)) title(main="최소제곱의 이해", font.main=4)

이 4개의 점을 가지고 회귀선까지 그려보면 다음과 같다.

R OLS 회귀분석 - R OLS hoegwibunseog

x=c(1,2,3,4) y=c(2,3,5,4) f <- function(inp){ a= inp[1] b= inp[2] t= a*x+b sum((y-t)^2) } optim(c(1,1),f) #초기값 (a,b)=(1,1)로 시작해서 f를 최소화 하라

optim()을 이용하면 최소가 되는 값을 구할 수 있다.

결국 여기에서 나타나는 par항목의 값이 바로 회귀방정식의 기울기와 절편이 된다.

optim(c(1,1),f) #초기값 (a,b)=(1,1)로 시작해서 f를 최소화 하라 $par [1] 0.7999722 1.5000885 $value [1] 1.8 $counts function gradient 65 NA $convergence [1] 0 $message NULL

$par에 해당하는 부분은 바로 y ~ 0.8x +1.5 이다.

이것을 회귀분석을 해보면 명확하게 나타나고 알 수 있다. (lm(y~x)가 회귀분석)

summary(lm(y~x)) Call: lm(formula = y ~ x) Residuals: 1 2 3 4 -0.3 -0.1 1.1 -0.7 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 1.5000 1.1619 1.291 0.326 x 0.8000 0.4243 1.886 0.200 Residual standard error: 0.9487 on 2 degrees of freedom Multiple R-squared: 0.64, Adjusted R-squared: 0.46 F-statistic: 3.556 on 1 and 2 DF, p-value: 0.2

임의로 만든 값이므로 p값이 유의미하지는 않다.

독립변수에 해당하는 x=c(1,2,3,4)는 오차가 없지만 종속변수인 c(2,3,5,4)는 오차를 포함한 값이다.

2. 회귀의 유래

회귀란 용어가 왜 사용되는가?에 대한 것은 다음을 보시면 이해가 될 것이다.

#임의의 회귀 계수 분석 독립변수=rnorm(40) 종속변수=rnorm(40) plot(독립변수,종속변수, pch=16, main = cor(독립변수,종속변수)) abline(lm(종속변수~독립변수),lwd=2, col=2)

R OLS 회귀분석 - R OLS hoegwibunseog

위의것을 여러번 해보면 set.seed(1)등으로 난수를 고정하지 않아서

다양한 모습이 나타나고 있다.

R OLS 회귀분석 - R OLS hoegwibunseog

이렇게 만들어진 것들은 우연에 의해서이렇게 만들어진 것이다.

그렇다면 강한 양의 상관을 한번 만들어 보자

set.seed(1) a=rnorm(100); b=rnorm(100); c=rnorm(100) x=(a+b)/sqrt(2) y=(b+c)/sqrt(2) plot(x,y,pch=16) #좌표그리기 abline(0,1,lty=2,lwd=2, col=4) # 추세선 abline(lm(y~x),col=2,lwd=2) # 회귀직선 title(main="평균으로의 회귀(Regression to the mean)")

R OLS 회귀분석 - R OLS hoegwibunseog

X(부모성적)와 Y(자식성적)의 상관이 완전하지 않기 때문에, 부모성적과 자식의 성적이 같아지는 것, 즉 y=x가 되지 않고 오히려 평균 y=0에 가까워진다.

이러한 현상을 프랜시스 골턴(Sir Francis Galton, 1822-1911)이 발견한 '평균으로의 회귀(regression th the mean)'이다. 여기에서 회귀(regression, 제자리로 돌아가는 것)이라는 단어가 유래했다 평균으로 회귀란 점점 수평에 가까운 직선이 되는 것을 말한다.

3. 단순회귀 분석(Simple linear regression)

3.1. galton(부모의 키와 자식의 키)

3.1.1 데이터

library(UsingR) str(galton)'data.frame': 928 obs. of 2 variables: $ child : num 61.7 61.7 61.7 61.7 61.7 62.2 62.2 62.2 62.2 62.2 ... $ parent: num 70.5 68.5 65.5 64.5 64 67.5 67.5 67.5 66.5 66.5 ...

이 자료는 플란시스 골턴의 928개의 부모의 키와 아이의 키에 대한 자료이다. 부모의 키는 아빠의 키와 엄마의 키의 산술평균값이다.

3.1.2. 회귀분석

galton.im = lm(child ~ parent, data=galton) > lm.beta(galton.im) Call: lm(formula = child ~ parent, data = galton) Standardized Coefficients:: (Intercept) parent 0.0000000 0.4587624

이를 정리하면 다음과 같다.

3.1.3. 회귀분석 요약결과

summary(lm.beta(galton.im)) Call: lm(formula = child ~ parent, data = galton) Residuals: Min 1Q Median 3Q Max -7.8050 -1.3661 0.0487 1.6339 5.9264 Coefficients: Estimate Standardized Std. Error t value Pr(>|t|) (Intercept) 23.94153 0.00000 2.81088 8.517 <2e-16 *** parent 0.64629 0.45876 0.04114 15.711 <2e-16 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 2.239 on 926 degrees of freedom Multiple R-squared: 0.2105, Adjusted R-squared: 0.2096 F-statistic: 246.8 on 1 and 926 DF, p-value: < 2.2e-16

y= 0.65x+23.94로 부모의 키에 의해 자녀의 키가 결정된다고 나오고 있다.

plot(child ~ parent, data=galton) abline(galton.im,lwd=3, col=2)

R OLS 회귀분석 - R OLS hoegwibunseog

plot()에 회귀결과값을 넣으면 4가지를 확인한 그래프를 그려준다.

par(mfrow=c(2,2)) plot(galton.im)

R OLS 회귀분석 - R OLS hoegwibunseog

3.2. weman (여성의 키와 몸무게 데이터)

30세부터 39세까지 미국 여성 15명이 키와 몸무게 데이터이다.

키는 인치, 몸무게는 파운드이다.

3.2.1 데이터

women height weight 1 58 115 2 59 117 3 60 120 4 61 123 5 62 126 6 63 129 7 64 132 8 65 135 9 66 139 10 67 142 11 68 146 12 69 150 13 70 154 14 71 159 15 72 164

이를 회귀분석해보자.

3.2.2. 회귀분석

fit <- lm(weight ~ height, data=women) > fit Call: lm(formula = weight ~ height, data = women) Coefficients: (Intercept) height -87.52 3.45

3.2.3. 회귀분석 결과

다음은 요약결과이다.

summary(lm.beta(fit)) Call: lm(formula = weight ~ height, data = women) Residuals: Min 1Q Median 3Q Max -1.7333 -1.1333 -0.3833 0.7417 3.1167 Coefficients: Estimate Standardized Std. Error t value Pr(>|t|) (Intercept) -87.51667 0.00000 5.93694 -14.74 1.71e-09 *** height 3.45000 0.99549 0.09114 37.85 1.09e-14 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 1.525 on 13 degrees of freedom Multiple R-squared: 0.991, Adjusted R-squared: 0.9903 F-statistic: 1433 on 1 and 13 DF, p-value: 1.091e-14

Coefficients를 보면 y절편이 되는 intercept는 -87.52이고 height는 3.45이다.

p- value를 보면 p<.001로 유의하게 나온다.

이를 통해서 나타나는 관계는 weight =-87.52 +3.45*height이다.

* Residual stadard error이라는 것은 이 모형을 사용하여 몸무게를 예측하면 1.525파운드의 오차가 있다는 의미이다.

* Multiple R- squared 0.991은 상관계수의 계곱을 말한다. 또한 이 값은 이 모형이 몸무게를 나타내는 분산을 99.1%를 설명해준다는 의미이다.

cor(women$weight, women$height) #상관계수 [1] 0.9954948 (cor(women$weight, women$height)^2) #상관계수의 제곱 [1] 0.9910098

F- statistic은 예측인자들을 고려했을 때에 우연 이상으로 반응 변수를 예측하는 정도이다. 예측인자가 하나인 경우는 키의 회귀계수에 대한 t-test 결과를 나타내게 된다.

3.2.4. 회귀모형의 유의성 검정

회귀모형의 유의성을 검정하려고 하면 anova()를 이용하여 분산분석표를 만들어서 분석해야 한다.

anova(fit) Analysis of Variance Table Response: weight Df Sum Sq Mean Sq F value Pr(>F) height 1 3332.7 3332.7 1433 1.091e-14 *** Residuals 13 30.2 2.3 --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

p값이 유의수준 0.05보다 매우 작으므로 회귀계수가 모두 0이라는 귀무가설을 기각할 수 있으므로 이 회귀식은 통계적으로 유의하다.

3.2.5 그래프

plot(weight ~ height, data=women) abline(fit, col=2) title(main="women의 키에 따른 몸무게 회귀분석")

R OLS 회귀분석 - R OLS hoegwibunseog

이 그래프에서 키가 작을 때와 클때에는 회귀모델이 잘 안맞고 구부러져서 예측이 어려울 것이란 생각이 든다. (회귀계수에 대한 예측은 fitted()를 이용한다. 이것은 적절한 모델에서 다시 설명할 예정이다)

4. 다항회귀분석(ploynomal regression)

그래프에서 회귀선이 한번 구브러지면 더 정확한 예측이 될 것이라고 생각이 든다.

이런 경우 1차식을 2차식으로 바꾸면 더 정확해질 것이다.

즉, 다항회귀는 한 개의 예측변수와 반응변수의 관계가 n차 다항식이면 더 유리한 경우에 적용한다.

R OLS 회귀분석 - R OLS hoegwibunseog

fit2 <- lm(weight ~ height +I(height^2), data=women) summary(lm.beta(fit2))

I()는 ()안의 내용을 수치적으로 계산하여 해석하라는 의미이다.

fit2 <- lm(weight ~ height +I(height^2), data=women) #I()는 포뮬러 지정시 ()의 값을 수식을 있는 그대로 수치로 계산하여 해석하라는 의미 > summary(lm.beta(fit2)) Call: lm(formula = weight ~ height + I(height^2), data = women) Residuals: Min 1Q Median 3Q Max -0.50941 -0.29611 -0.00941 0.28615 0.59706 Coefficients: Estimate Standardized Std. Error t value Pr(>|t|) (Intercept) 261.87818 0.00000 25.19677 10.393 2.36e-07 *** height -7.34832 -2.12035 0.77769 -9.449 6.58e-07 *** I(height^2) 0.08306 3.11720 0.00598 13.891 9.32e-09 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 0.3841 on 12 degrees of freedom Multiple R-squared: 0.9995, Adjusted R-squared: 0.9994 F-statistic: 1.139e+04 on 2 and 12 DF, p-value: < 2.2e-16

plot(weight ~ height, data=women) lines(women$height,fitted(fit2), col=2,lwd=2) title(main="women's regression의 fit model ")

R OLS 회귀분석 - R OLS hoegwibunseog

그래프를 보면 변수에 대하여 제곱처리를 하여 다항함수 형태로 만들면 회귀선에 대하여 좀 더 예측이 잘 되는 모델을 구성할 수 있다.

4.3. 모델의 적절성 (scatterplot 이용)

이 모델이 적합한지 보는 방법으로 car{}에 들어있는 scatterplot()를 이용하여 시각적으로 확인하는 방법이다.

#scatterplot library(car) scatterplot(weight ~ height, data = women,pch=19, cex=1.2, regLine=list(method=lm,lty=2, lwd=3,col="tomato"), smooth=list(smoother=loessLine, spread=FALSE, col.smooth="green3"), main="women Age 30 ~39")

R OLS 회귀분석 - R OLS hoegwibunseog

이 그래프를 보면 직선 모형보다 곡선모형이 더 잘맞는 것으로 보인다.

박중희

연세대학교 인지공학연구실

(주)자유자재교육

(사)한사협 교육연구소 소장

참고

#optim {stats} # General-purpose optimization based on Nelder–Mead, # quasi-Newton and conjugate-gradient algorithms. # It includes an option for box-constrained optimization and simulated annealing. optim(par, fn, gr = NULL, ..., method = c("Nelder-Mead", "BFGS", "CG", "L-BFGS-B", "SANN", "Brent"), lower = -Inf, upper = Inf, control = list(), hessian = FALSE) optimHess(par, fn, gr = NULL, ..., control = list()) par Initial values for the parameters to be optimized over. fn A function to be minimized (or maximized), with first argument the vector of parameter s over which minimization is to take place. It should return a scalar result.