본문 바로가기
배우는 것들/R

데이터 과학을 위한 통계 - 5

by Ho.virus 2021. 1. 31.

4.1.1 회귀식

lm함수를 이용해 선형회귀 모델을 만들 수 있다.

formula 인자에 formula = Y ~ X1 + X2 + … + XN 의 형태로 입력을 해준다.

lung = read.csv("LungDisease.csv")

model = lm(PEFR ~ Exposure, data = lung)

summary(model)
## 
## Call:
## lm(formula = PEFR ~ Exposure, data = lung)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -297.845  -58.783   -1.214   61.024  209.109 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  424.583     20.796  20.417  < 2e-16 ***
## Exposure      -4.185      1.325  -3.158  0.00201 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 101.4 on 120 degrees of freedom
## Multiple R-squared:  0.07674,    Adjusted R-squared:  0.06905 
## F-statistic: 9.974 on 1 and 120 DF,  p-value: 0.002008

위 수치를 이용해 회귀선을 만든다

plot(x = lung$Exposure, y = lung$PEFR)
abline(a = 424.583, b = -4.185)

lm함수로 만든 모델에서 predict함수와 residual 함수를 이용해 적합값(Y.hat), 잔차(e)를 구할 수 있다.

fitted = predict(model)
resid = residuals(model)

4.2 다중 선형회귀

4.2.1 킹 카운티 주택정보 예제

    house = read.csv("house_sales.csv", sep = " ", header = T)

head(house[, c("AdjSalePrice","SqFtTotLiving","SqFtLot","Bathrooms","Bedrooms","BldgGrade" )])
##   AdjSalePrice SqFtTotLiving SqFtLot Bathrooms Bedrooms BldgGrade
## 1       300805          2400    9373      3.00        6         7
## 2      1076162          3764   20156      3.75        4        10
## 3       761805          2060   26036      1.75        4         8
## 4       442065          3200    8618      3.75        5         7
## 5       297065          1720    8620      1.75        4         7
## 6       411781           930    1012      1.50        2         8

킹카운티 주택의 매매값과 주택 가격에 관련된 변수가 기록된 데이터이다. 하나의 변수만으로 주택의 가격을 설명하기에는 무리가 있다.

lm함수의 formula 인자에 많은 항을 추가하여 다중회귀 모델을 만든다. na.omit을 통해 NA(결측값)이 있는 열을 제거한다.

house_lm = lm(AdjSalePrice ~ SqFtTotLiving + SqFtLot + Bathrooms + Bedrooms + BldgGrade, data = house, na.action = na.omit)

summary(house_lm)
## 
## Call:
## lm(formula = AdjSalePrice ~ SqFtTotLiving + SqFtLot + Bathrooms + 
##     Bedrooms + BldgGrade, data = house, na.action = na.omit)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -1950841  -114032   -21451    83578  9549956 
## 
## Coefficients:
##                 Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   -5.287e+05  1.443e+04 -36.629  < 2e-16 ***
## SqFtTotLiving  2.127e+02  3.401e+00  62.552  < 2e-16 ***
## SqFtLot       -1.430e-02  5.760e-02  -0.248    0.804    
## Bathrooms     -1.823e+04  3.225e+03  -5.654 1.58e-08 ***
## Bedrooms      -4.657e+04  2.329e+03 -19.999  < 2e-16 ***
## BldgGrade      1.088e+05  2.164e+03  50.266  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 259400 on 27057 degrees of freedom
## Multiple R-squared:  0.5348, Adjusted R-squared:  0.5348 
## F-statistic:  6222 on 5 and 27057 DF,  p-value: < 2.2e-16

R의 기본 회귀함수에서는 RSE(잔차 표준오차)와 결정계수 R, p-value를 보여주며 계수에 관련해서 standard error와 t,F 통계량을 보여준다.

SqFtLot 변수를 제외하고는 모두 유의미한 t통계량을 보여주었다.

-> 관찰된 상관계수의 크기가 크지않아, 랜덤변이 안에서도 충분히 관찰된만한 수치라고 판단되는것. 모델에 대한 p-value 역시 유의미 하다.

4.2.4 모형 선택 및 단계적 회귀

회귀 모델을 만들며 독립변수를 설정하는 것은 굉장히 중요하다. 변수를 추가할 때마다 RMSE는 감소하고 결정계수 R은 증가하기 때문에 무차별적으로 변수를 추가하다보면 판단지표가 무의미하게 된다.

AIC라는 측정 기준은 변수를 하나 추가할 때마다 점수에 불이익을 주어 이를 해결했다.

 

가능한 모든 변수의 조합에 대해 AIC점수를 측정하는것은 너무 복잡한 계산이 필요하므로,

 

변수를 연속적으로 추가/삭제하는 단계적 회귀,

 

가장 큰 기여도를 갖는 변수부터 하나씩 추가하여 기여도가 유의미하지 않을 때까지 추가하는 전진선택,

 

전체 모델에서 통계적으로 유의미하지 않은 모델을 제거해 나가는 후진선택 등의 방법이 있다.

 

MASS 패키지의 stepAIC 함수의 direction 인자를 통해 이를 구현할 수 있다.

house_full = lm(AdjSalePrice ~ SqFtTotLiving + SqFtLot + Bathrooms + Bedrooms + BldgGrade + PropertyType + NbrLivingUnits + SqFtFinBasement + YrBuilt + YrRenovated + NewConstruction, data = house , na.action = na.omit)


library("MASS") 
step = stepAIC(house_full, direction = "both") 
## Start:  AIC=671316
## AdjSalePrice ~ SqFtTotLiving + SqFtLot + Bathrooms + Bedrooms + 
##     BldgGrade + PropertyType + NbrLivingUnits + SqFtFinBasement + 
##     YrBuilt + YrRenovated + NewConstruction
## 
##                   Df  Sum of Sq        RSS    AIC
## - NbrLivingUnits   1 3.6803e+09 1.6030e+15 671314
## - YrRenovated      1 1.2789e+10 1.6030e+15 671314
## - SqFtLot          1 2.5471e+10 1.6030e+15 671314
## - NewConstruction  1 7.1632e+10 1.6030e+15 671315
## <none>                          1.6030e+15 671316
## - SqFtFinBasement  1 2.8579e+11 1.6033e+15 671319
## - PropertyType     2 7.8637e+12 1.6108e+15 671444
## - Bathrooms        1 1.0095e+13 1.6131e+15 671484
## - Bedrooms         1 2.9035e+13 1.6320e+15 671800
## - SqFtTotLiving    1 1.4207e+14 1.7450e+15 673612
## - YrBuilt          1 1.4711e+14 1.7501e+15 673690
## - BldgGrade        1 2.3338e+14 1.8364e+15 674993
## 
## Step:  AIC=671314.1
## AdjSalePrice ~ SqFtTotLiving + SqFtLot + Bathrooms + Bedrooms + 
##     BldgGrade + PropertyType + SqFtFinBasement + YrBuilt + YrRenovated + 
##     NewConstruction
## 
##                   Df  Sum of Sq        RSS    AIC
## - YrRenovated      1 1.2524e+10 1.6030e+15 671312
## - SqFtLot          1 2.5211e+10 1.6030e+15 671313
## - NewConstruction  1 7.2192e+10 1.6031e+15 671313
## <none>                          1.6030e+15 671314
## + NbrLivingUnits   1 3.6803e+09 1.6030e+15 671316
## - SqFtFinBasement  1 2.8911e+11 1.6033e+15 671317
## - PropertyType     2 7.8769e+12 1.6109e+15 671443
## - Bathrooms        1 1.0152e+13 1.6131e+15 671483
## - Bedrooms         1 2.9229e+13 1.6322e+15 671801
## - SqFtTotLiving    1 1.4222e+14 1.7452e+15 673613
## - YrBuilt          1 1.4802e+14 1.7510e+15 673702
## - BldgGrade        1 2.3544e+14 1.8384e+15 675021
## 
## Step:  AIC=671312.3
## AdjSalePrice ~ SqFtTotLiving + SqFtLot + Bathrooms + Bedrooms + 
##     BldgGrade + PropertyType + SqFtFinBasement + YrBuilt + NewConstruction
## 
##                   Df  Sum of Sq        RSS    AIC
## - SqFtLot          1 2.5083e+10 1.6030e+15 671311
## - NewConstruction  1 7.1293e+10 1.6031e+15 671311
## <none>                          1.6030e+15 671312
## + YrRenovated      1 1.2524e+10 1.6030e+15 671314
## + NbrLivingUnits   1 3.4152e+09 1.6030e+15 671314
## - SqFtFinBasement  1 2.9330e+11 1.6033e+15 671315
## - PropertyType     2 7.8650e+12 1.6109e+15 671441
## - Bathrooms        1 1.0238e+13 1.6132e+15 671483
## - Bedrooms         1 2.9219e+13 1.6322e+15 671799
## - SqFtTotLiving    1 1.4221e+14 1.7452e+15 673611
## - YrBuilt          1 1.6196e+14 1.7650e+15 673915
## - BldgGrade        1 2.3548e+14 1.8385e+15 675020
## 
## Step:  AIC=671310.7
## AdjSalePrice ~ SqFtTotLiving + Bathrooms + Bedrooms + BldgGrade + 
##     PropertyType + SqFtFinBasement + YrBuilt + NewConstruction
## 
##                   Df  Sum of Sq        RSS    AIC
## - NewConstruction  1 6.3500e+10 1.6031e+15 671310
## <none>                          1.6030e+15 671311
## + SqFtLot          1 2.5083e+10 1.6030e+15 671312
## + YrRenovated      1 1.2396e+10 1.6030e+15 671313
## + NbrLivingUnits   1 3.1669e+09 1.6030e+15 671313
## - SqFtFinBasement  1 2.8652e+11 1.6033e+15 671314
## - PropertyType     2 7.8468e+12 1.6109e+15 671439
## - Bathrooms        1 1.0215e+13 1.6132e+15 671481
## - Bedrooms         1 2.9451e+13 1.6325e+15 671801
## - SqFtTotLiving    1 1.4593e+14 1.7490e+15 673667
## - YrBuilt          1 1.6199e+14 1.7650e+15 673914
## - BldgGrade        1 2.3547e+14 1.8385e+15 675018
## 
## Step:  AIC=671309.8
## AdjSalePrice ~ SqFtTotLiving + Bathrooms + Bedrooms + BldgGrade + 
##     PropertyType + SqFtFinBasement + YrBuilt
## 
##                   Df  Sum of Sq        RSS    AIC
## <none>                          1.6031e+15 671310
## + NewConstruction  1 6.3500e+10 1.6030e+15 671311
## + SqFtLot          1 1.7290e+10 1.6031e+15 671311
## + YrRenovated      1 1.1567e+10 1.6031e+15 671312
## + NbrLivingUnits   1 3.7093e+09 1.6031e+15 671312
## - SqFtFinBasement  1 2.6805e+11 1.6033e+15 671312
## - PropertyType     2 8.5458e+12 1.6116e+15 671450
## - Bathrooms        1 1.0235e+13 1.6133e+15 671480
## - Bedrooms         1 2.9483e+13 1.6326e+15 671801
## - SqFtTotLiving    1 1.4722e+14 1.7503e+15 673686
## - YrBuilt          1 1.7535e+14 1.7784e+15 674117
## - BldgGrade        1 2.3572e+14 1.8388e+15 675020
step
## 
## Call:
## lm(formula = AdjSalePrice ~ SqFtTotLiving + Bathrooms + Bedrooms + 
##     BldgGrade + PropertyType + SqFtFinBasement + YrBuilt, data = house, 
##     na.action = na.omit)
## 
## Coefficients:
##               (Intercept)              SqFtTotLiving  
##                6227632.22                     186.50  
##                 Bathrooms                   Bedrooms  
##                  44721.72                  -49807.18  
##                 BldgGrade  PropertyTypeSingle Family  
##                 139179.23                   23328.69  
##     PropertyTypeTownhouse            SqFtFinBasement  
##                  92216.25                       9.04  
##                   YrBuilt  
##                  -3592.47