states <- as.data.frame(state.x77[,c("Murder", "Population", "Illiteracy", "Income", "Frost")])
fit = lm(Murder~Population+Illiteracy+Income+Frost, data=states)
summary(fit)##
## Call:
## lm(formula = Murder ~ Population + Illiteracy + Income + Frost,
## data = states)
##
## Residuals:
## Min 1Q Median 3Q Max
## -4.7960 -1.6495 -0.0811 1.4815 7.6210
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 1.235e+00 3.866e+00 0.319 0.7510
## Population 2.237e-04 9.052e-05 2.471 0.0173 *
## Illiteracy 4.143e+00 8.744e-01 4.738 2.19e-05 ***
## Income 6.442e-05 6.837e-04 0.094 0.9253
## Frost 5.813e-04 1.005e-02 0.058 0.9541
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 2.535 on 45 degrees of freedom
## Multiple R-squared: 0.567, Adjusted R-squared: 0.5285
## F-statistic: 14.73 on 4 and 45 DF, p-value: 9.133e-08
## 2.5 % 97.5 %
## (Intercept) -6.552191e+00 9.0213182149
## Population 4.136397e-05 0.0004059867
## Illiteracy 2.381799e+00 5.9038743192
## Income -1.312611e-03 0.0014414600
## Frost -1.966781e-02 0.0208304170
##
## Call:
## lm(formula = weight ~ height, data = women)
##
## Coefficients:
## (Intercept) height
## -87.52 3.45
plot(weight~height, data=women)
abline(fit, col="red")
title(expression(italic(weight==3.45%*%height-87.52)))
3.이 그래프를 이해하기 위해서는 회귀의 가정을 고려해야 합니다.
정규성(Normality): 반응변수(종속변수)가 정규분포한다면 잔차가 또한 정규분포하며 평균은 0입니다. 그래프의 오른쪽 위에 있는 normal Q-Q plot은 표준화된 잔차의 probability plot 입니다. 정규성 가정을 만족한다면 이 그래프의 점들은 45도 각도의 직선 위에 있어야 합니다. 이 그래프는 이 와 다르기 때문에 정규성 가정을 위반한 것입니다.
독립성(Independence): 반응변수(종속변수)는 서로 독립적이어야 합니다. 예측 변수의 독립성은 이 그래프로 알수 없습니다. 데이터를 어떻게 모았는지 알아야 합니다. 어떤 사람의 몸무게가 다른 사람의 몸무게에 영향을 미친다고 볼 이유는 없지만 만약 가족들을 대상으로 데이터를 모았다면 독립성 가정에 영향을 미칠 수 있습니다.
선형성(Linearity): 종속변수와 독립변수가 선형관계에 있다면 잔차와 예측치 사이에 어떤 체계적인 관계가 있으면 안 됩니다. 왼쪽 위에 있는 Residuals vs Fitted 그래프에서 무작위 잡음(random noise) 이외에는 어떤 관계가 보이면 안됩니다. 이 모형에서는 곡선 관계를 보이고 있기 때문에 회귀식을 다항식으로 고려해야합니다.
등분산성(Homoscedasticity): 분산이 일정하다는 가정을 만족한다면 왼쪽 아래 그래프에서 수평선 주위로 random band 형태로 나타나야 합니다. 이 그래프에서는 등분산성을 만족하는 것으로 보입니다.
마지막으로 오른쪽 아래의 잔차 대 영향력(leverage) 그래프에서는 주의를 기울여야 하는 개개인의 관찰치에 대한 정보를 제공합니다. 이 그래프에서는 이상치, 큰 지레점, 영향 관측치를 확인할 수 있습니다.
states <- as.data.frame(state.x77[,c("Murder", "Population", "Illiteracy", "Income", "Frost")])
fit = lm(Murder~Population+Illiteracy+Income+Frost, data=states)
par(mfrow=c(2,2))
plot(fit)## Population Illiteracy Income Frost
## 1.245282 2.165848 1.345822 2.082547
## Population Illiteracy Income Frost
## FALSE FALSE FALSE FALSE
이상관측치 종합적인 회귀분석은 이상관측치의 선별을 포함합니다. 이상 관측치에는 이상치, 큰지레점, 영향관측치 등이 포함되는데 이들은 회귀결과에 불균형한 영향을 미칠 수 있으므로 보다 정밀한 조사를 필요로 합니다.
이상치(outlier) 이상치는 회귀모형을 잘 예측되지 않는 관측치로 비정상적으로 큰 양수 또는 음수의 잔차를 갖습니다. 대략 이야기하면 표준잔차의 2배이상으로 크거나 작은거나 이상치라고 할 수 있습니다. car 패키지의 outlierTest()를 사용합시다.
## rstudent unadjusted p-value Bonferroni p
## Nevada 3.542929 0.00095088 0.047544
hat.plot <- function(fit){
p <- length(coefficients(fit))
n <- length(fitted(fit))
plot(hatvalues(fit), main="Index Plot of Hat Value")
abline(h=c(2,3)*p/n, col='red', lty=2)
identify(1:n, hatvalues(fit), names(hatvalues(fit)))
}
hatvalues(fit)## Alabama Alaska Arizona Arkansas California
## 0.09819211 0.43247319 0.12264914 0.08722029 0.34087628
## Colorado Connecticut Delaware Florida Georgia
## 0.05469964 0.09474658 0.05859637 0.12940379 0.05803142
## Hawaii Idaho Illinois Indiana Iowa
## 0.22443594 0.06905425 0.09683616 0.03871740 0.04627447
## Kansas Kentucky Louisiana Maine Maryland
## 0.05245106 0.05131253 0.17022388 0.09966458 0.06942663
## Massachusetts Michigan Minnesota Mississippi Missouri
## 0.02687166 0.05740920 0.04638897 0.14748152 0.04199088
## Montana Nebraska Nevada New Hampshire New Jersey
## 0.05253317 0.04421328 0.09508977 0.06387335 0.06616617
## New Mexico New York North Carolina North Dakota Ohio
## 0.15998871 0.23298637 0.05218913 0.10529028 0.08652446
## Oklahoma Oregon Pennsylvania Rhode Island South Carolina
## 0.05117056 0.19057634 0.11185698 0.04562377 0.10445404
## South Dakota Tennessee Texas Utah Vermont
## 0.07553161 0.04580225 0.13392638 0.06970746 0.08788063
## Virginia Washington West Virginia Wisconsin Wyoming
## 0.03230467 0.21662901 0.05839687 0.04173326 0.06012359
## integer(0)
cutoff <- 4/(nrow(states)-length(fit$coefficients)-2)
plot(fit, which=4, cook.levels=cutoff)
abline(h=cutoff, lty=2, col='red') - 그래프를 보면 Alaska, Hawaii, Nevada가 영향관측치임을 알수 있습니다. - Cook’D plot은 영향관측치를 찾는데 도움을 주지만 모형에 어떤 영향을 미치는 지에 대한 정보를 주지는 않습니다.Added-variable plot은 이런 점에서 도움이 되는 데 하나의 반응 변수와 K개의 예측변수가 있는 경우 k개의 added-variable plot을 만들 수 있습니다.
- 각 plot에 포함되어 있는 선이 그 plot에 그려져 있는 예측변수와 반응변수 사이의 회귀선 입니다. 한 관측치의 점이 없어질 경우 회귀선에 어떤 형향을 미칠지 그림을 보면서 상상할 수 있습니다.
car::influencePlot(fit, id.method="identify", main="Influence Plot",
sub="Circle size is proportional to Cook's distance")## StudRes Hat CookD
## Alaska 1.7536917 0.43247319 0.448050997
## California -0.2761492 0.34087628 0.008052956
## Nevada 3.5429286 0.09508977 0.209915743
## Rhode Island -2.0001631 0.04562377 0.035858963
states <- as.data.frame(state.x77[,c("Murder", "Population", "Illiteracy", "Income", "Frost")])
fit1 = lm(Murder~Population+Illiteracy+Income+Frost, data=states)
summary(fit1)##
## Call:
## lm(formula = Murder ~ Population + Illiteracy + Income + Frost,
## data = states)
##
## Residuals:
## Min 1Q Median 3Q Max
## -4.7960 -1.6495 -0.0811 1.4815 7.6210
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 1.235e+00 3.866e+00 0.319 0.7510
## Population 2.237e-04 9.052e-05 2.471 0.0173 *
## Illiteracy 4.143e+00 8.744e-01 4.738 2.19e-05 ***
## Income 6.442e-05 6.837e-04 0.094 0.9253
## Frost 5.813e-04 1.005e-02 0.058 0.9541
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 2.535 on 45 degrees of freedom
## Multiple R-squared: 0.567, Adjusted R-squared: 0.5285
## F-statistic: 14.73 on 4 and 45 DF, p-value: 9.133e-08
##
## Call:
## lm(formula = Murder ~ Population + Illiteracy, data = states)
##
## Residuals:
## Min 1Q Median 3Q Max
## -4.7652 -1.6561 -0.0898 1.4570 7.6758
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 1.652e+00 8.101e-01 2.039 0.04713 *
## Population 2.242e-04 7.984e-05 2.808 0.00724 **
## Illiteracy 4.081e+00 5.848e-01 6.978 8.83e-09 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 2.481 on 47 degrees of freedom
## Multiple R-squared: 0.5668, Adjusted R-squared: 0.5484
## F-statistic: 30.75 on 2 and 47 DF, p-value: 2.893e-09
## Analysis of Variance Table
##
## Model 1: Murder ~ Population + Illiteracy
## Model 2: Murder ~ Population + Illiteracy + Income + Frost
## Res.Df RSS Df Sum of Sq F Pr(>F)
## 1 47 289.25
## 2 45 289.17 2 0.078505 0.0061 0.9939
## df AIC
## fit1 6 241.6429
## fit2 4 237.6565
## Start: AIC=97.75
## Murder ~ Population + Illiteracy + Income + Frost
##
## Df Sum of Sq RSS AIC
## - Frost 1 0.021 289.19 95.753
## - Income 1 0.057 289.22 95.759
## <none> 289.17 97.749
## - Population 1 39.238 328.41 102.111
## - Illiteracy 1 144.264 433.43 115.986
##
## Step: AIC=95.75
## Murder ~ Population + Illiteracy + Income
##
## Df Sum of Sq RSS AIC
## - Income 1 0.057 289.25 93.763
## <none> 289.19 95.753
## - Population 1 43.658 332.85 100.783
## - Illiteracy 1 236.196 525.38 123.605
##
## Step: AIC=93.76
## Murder ~ Population + Illiteracy
##
## Df Sum of Sq RSS AIC
## <none> 289.25 93.763
## - Population 1 48.517 337.76 99.516
## - Illiteracy 1 299.646 588.89 127.311
##
## Call:
## lm(formula = Murder ~ Population + Illiteracy, data = states)
##
## Residuals:
## Min 1Q Median 3Q Max
## -4.7652 -1.6561 -0.0898 1.4570 7.6758
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 1.652e+00 8.101e-01 2.039 0.04713 *
## Population 2.242e-04 7.984e-05 2.808 0.00724 **
## Illiteracy 4.081e+00 5.848e-01 6.978 8.83e-09 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 2.481 on 47 degrees of freedom
## Multiple R-squared: 0.5668, Adjusted R-squared: 0.5484
## F-statistic: 30.75 on 2 and 47 DF, p-value: 2.893e-09
min.model=lm(Murder~1,data=states)
fwd.model=step(min.model,direction = "forward",
scope=(Murder~Population+Illiteracy+Income+Frost), trace=0)
summary(fwd.model)##
## Call:
## lm(formula = Murder ~ Illiteracy + Population, data = states)
##
## Residuals:
## Min 1Q Median 3Q Max
## -4.7652 -1.6561 -0.0898 1.4570 7.6758
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 1.652e+00 8.101e-01 2.039 0.04713 *
## Illiteracy 4.081e+00 5.848e-01 6.978 8.83e-09 ***
## Population 2.242e-04 7.984e-05 2.808 0.00724 **
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 2.481 on 47 degrees of freedom
## Multiple R-squared: 0.5668, Adjusted R-squared: 0.5484
## F-statistic: 30.75 on 2 and 47 DF, p-value: 2.893e-09
이러한 stepwise regression을 너무 과신하지 말아야 합니다. 주의깊고 현명하게 변수를 고르는 것을 완전히 대체할 수는 없습니다.
모든 부분집합회귀(all subset regression)
require(leaps)
states <- as.data.frame(state.x77[,c("Murder","Population","Illiteracy",
"Income","Frost")])
leaps <- regsubsets(Murder~Population+Illiteracy+Income+Frost, data=states, nbest=4)
plot(leaps, scale="adjr2")shrinkage <- function(fit, k=10){
require(bootstrap)
theta.fit <- function(x,y){lsfit(x,y)}
theta.predict <- function(fit,x){cbind(1,x)%*%fit$coef}
x <- fit$model[,2:ncol(fit$model)]
y <- fit$model[,1]
results <- crossval(x, y, theta.fit, theta.predict, ngroup=k)
r2 <- cor(y, fit$fitted.values)^2
r2cv <- cor(y, results$cv.fit)^2
cat("Original R-sqaure = ", r2, "\n")
cat(k, "Fold cross-validated R-squre = ", r2cv, "\n")
cat("Change = ",r2-r2cv,'\n')
}## Original R-sqaure = 0.5669502
## 10 Fold cross-validated R-squre = 0.4829558
## Change = 0.08399446
## Original R-sqaure = 0.5668327
## 10 Fold cross-validated R-squre = 0.5193594
## Change = 0.04747325
states <- as.data.frame(state.x77[,c("Murder","Population","Illiteracy",
"Income","Frost")])
zstates <- as.data.frame(scale(states))
zfit <- lm(Murder~Population+Illiteracy+Income+Frost, data=zstates)
coef(zfit)## (Intercept) Population Illiteracy Income Frost
## -2.054026e-16 2.705095e-01 6.840496e-01 1.072372e-02 8.185407e-03
require(rwa)
rwa = rwa(states, outcome = "Murder", predictors = c("Population","Illiteracy","Income","Frost"),
applysigns = TRUE)
rwa## $predictors
## [1] "Population" "Illiteracy" "Income" "Frost"
##
## $rsquare
## [1] 0.5669502
##
## $result
## Variables Raw.RelWeight Rescaled.RelWeight Sign Sign.Rescaled.RelWeight
## 1 Population 0.08347436 14.723401 + 14.723401
## 2 Illiteracy 0.33450175 59.000195 + 59.000195
## 3 Income 0.03111968 5.488962 - -5.488962
## 4 Frost 0.11785445 20.787442 - -20.787442
##
## $n
## [1] 50
##
## $lambda
## [,1] [,2] [,3] [,4]
## [1,] 0.97665854 0.03825815 0.11970553 -0.17419815
## [2,] 0.03825815 0.90844089 -0.21876833 -0.35413540
## [3,] 0.11970553 -0.21876833 0.96418584 0.09031425
## [4,] -0.17419815 -0.35413540 0.09031425 0.91437763
##
## $RXX
## Population Illiteracy Income Frost
## Population 1.0000000 0.1076224 0.2082276 -0.3321525
## Illiteracy 0.1076224 1.0000000 -0.4370752 -0.6719470
## Income 0.2082276 -0.4370752 1.0000000 0.2262822
## Frost -0.3321525 -0.6719470 0.2262822 1.0000000
##
## $RXY
## Population Illiteracy Income Frost
## 0.3436428 0.7029752 -0.2300776 -0.5388834
- 참조: https://cran.r-project.org/web/packages/rwa/readme/README.html