Weekly

  1. This question should be answered using the Weekly data set, which is part of the ISLR2 package. This data is similar in nature to the Smarket data from this chapter’s lab, except that it contains 1,089 weekly returns for 21 years, from the beginning of 1990 to the end of 2010.
library(ISLR2)
## Warning: 패키지 'ISLR2'는 R 버전 4.4.0에서 작성되었습니다
library(MASS)
## 
## 다음의 패키지를 부착합니다: 'MASS'
## The following object is masked from 'package:ISLR2':
## 
##     Boston
head(Weekly)
##   Year   Lag1   Lag2   Lag3   Lag4   Lag5    Volume  Today Direction
## 1 1990  0.816  1.572 -3.936 -0.229 -3.484 0.1549760 -0.270      Down
## 2 1990 -0.270  0.816  1.572 -3.936 -0.229 0.1485740 -2.576      Down
## 3 1990 -2.576 -0.270  0.816  1.572 -3.936 0.1598375  3.514        Up
## 4 1990  3.514 -2.576 -0.270  0.816  1.572 0.1616300  0.712        Up
## 5 1990  0.712  3.514 -2.576 -0.270  0.816 0.1537280  1.178        Up
## 6 1990  1.178  0.712  3.514 -2.576 -0.270 0.1544440 -1.372      Down
  1. Produce some numerical and graphical summaries of the Weekly data. Do there appear to be any patterns?
#기초 통계량
summary(Weekly)
##       Year           Lag1               Lag2               Lag3         
##  Min.   :1990   Min.   :-18.1950   Min.   :-18.1950   Min.   :-18.1950  
##  1st Qu.:1995   1st Qu.: -1.1540   1st Qu.: -1.1540   1st Qu.: -1.1580  
##  Median :2000   Median :  0.2410   Median :  0.2410   Median :  0.2410  
##  Mean   :2000   Mean   :  0.1506   Mean   :  0.1511   Mean   :  0.1472  
##  3rd Qu.:2005   3rd Qu.:  1.4050   3rd Qu.:  1.4090   3rd Qu.:  1.4090  
##  Max.   :2010   Max.   : 12.0260   Max.   : 12.0260   Max.   : 12.0260  
##       Lag4               Lag5              Volume            Today         
##  Min.   :-18.1950   Min.   :-18.1950   Min.   :0.08747   Min.   :-18.1950  
##  1st Qu.: -1.1580   1st Qu.: -1.1660   1st Qu.:0.33202   1st Qu.: -1.1540  
##  Median :  0.2380   Median :  0.2340   Median :1.00268   Median :  0.2410  
##  Mean   :  0.1458   Mean   :  0.1399   Mean   :1.57462   Mean   :  0.1499  
##  3rd Qu.:  1.4090   3rd Qu.:  1.4050   3rd Qu.:2.05373   3rd Qu.:  1.4050  
##  Max.   : 12.0260   Max.   : 12.0260   Max.   :9.32821   Max.   : 12.0260  
##  Direction 
##  Down:484  
##  Up  :605  
##            
##            
##            
## 
#scatter plot
pairs(Weekly)

#상관계수
cor(Weekly[,-9])
##               Year         Lag1        Lag2        Lag3         Lag4
## Year    1.00000000 -0.032289274 -0.03339001 -0.03000649 -0.031127923
## Lag1   -0.03228927  1.000000000 -0.07485305  0.05863568 -0.071273876
## Lag2   -0.03339001 -0.074853051  1.00000000 -0.07572091  0.058381535
## Lag3   -0.03000649  0.058635682 -0.07572091  1.00000000 -0.075395865
## Lag4   -0.03112792 -0.071273876  0.05838153 -0.07539587  1.000000000
## Lag5   -0.03051910 -0.008183096 -0.07249948  0.06065717 -0.075675027
## Volume  0.84194162 -0.064951313 -0.08551314 -0.06928771 -0.061074617
## Today  -0.03245989 -0.075031842  0.05916672 -0.07124364 -0.007825873
##                Lag5      Volume        Today
## Year   -0.030519101  0.84194162 -0.032459894
## Lag1   -0.008183096 -0.06495131 -0.075031842
## Lag2   -0.072499482 -0.08551314  0.059166717
## Lag3    0.060657175 -0.06928771 -0.071243639
## Lag4   -0.075675027 -0.06107462 -0.007825873
## Lag5    1.000000000 -0.05851741  0.011012698
## Volume -0.058517414  1.00000000 -0.033077783
## Today   0.011012698 -0.03307778  1.000000000

그래프와 상관계수수 보면 year와 volume을 제외한 다른 변수들은 서로 상관관계가 강하지 않음을 알 수 있음. volume&year의 그래프를 보면 시간이 지날수록 증가하는 추세를 보임. 상관계수도 0.842로 1과 가까움. 다른 변수들 간의 상관계수의 절대값들은 0.1을 넘지 않음.

  1. Use the full data set to perform a logistic regression with Direction as the response and the five lag variables plus Volume as predictors. Use the summary function to print the results. Do any of the predictors appear to be statistically significant? If so, which ones?
wlogis<-glm(Direction~.-Year-Today,data=Weekly,family=binomial)
summary(wlogis)
## 
## Call:
## glm(formula = Direction ~ . - Year - Today, family = binomial, 
##     data = Weekly)
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)   
## (Intercept)  0.26686    0.08593   3.106   0.0019 **
## Lag1        -0.04127    0.02641  -1.563   0.1181   
## Lag2         0.05844    0.02686   2.175   0.0296 * 
## Lag3        -0.01606    0.02666  -0.602   0.5469   
## Lag4        -0.02779    0.02646  -1.050   0.2937   
## Lag5        -0.01447    0.02638  -0.549   0.5833   
## Volume      -0.02274    0.03690  -0.616   0.5377   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 1496.2  on 1088  degrees of freedom
## Residual deviance: 1486.4  on 1082  degrees of freedom
## AIC: 1500.4
## 
## Number of Fisher Scoring iterations: 4
  1. Compute the confusion matrix and overall fraction of correct predictions. Explain what the confusion matrix is telling you about the types of mistakes made by logistic regression.
wlogis.probs<-predict(wlogis, type="response")
wlogis.pred<-rep("Down",1089)
wlogis.pred[wlogis.probs>.5]<-"Up"
table(wlogis.pred,Weekly$Direction)
##            
## wlogis.pred Down  Up
##        Down   54  48
##        Up    430 557
#정확도
mean(wlogis.pred==Weekly$Direction)
## [1] 0.5610652
# Up일 때의 정확도
557/(430+557)
## [1] 0.5643364
#Down일 때의 정확도
54/(54+48)
## [1] 0.5294118

전체 정확도는 56.1%이고 Up을 예측할 때의 정확도는 56.4%로 Down을 예측할 때의 정확도인 53%보다 정확도가 더 높다.

  1. Now fit the logistic regression model using a training data period from 1990 to 2008, with Lag2 as the only predictor. Compute the confusion matrix and the overall fraction of correct predictions for the held out data(that is, the data from 2009 and 2010).
weekly_train=(Weekly$Year<2009)
wlogis_split=glm(Direction~ Lag2, data=Weekly, subset=weekly_train,family="binomial")
summary(wlogis_split)
## 
## Call:
## glm(formula = Direction ~ Lag2, family = "binomial", data = Weekly, 
##     subset = weekly_train)
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)   
## (Intercept)  0.20326    0.06428   3.162  0.00157 **
## Lag2         0.05810    0.02870   2.024  0.04298 * 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 1354.7  on 984  degrees of freedom
## Residual deviance: 1350.5  on 983  degrees of freedom
## AIC: 1354.5
## 
## Number of Fisher Scoring iterations: 4
wlogis_split.probs<-predict(wlogis_split,Weekly[!weekly_train,], type="response")
wlogis_split.pred<-rep("Down",dim(Weekly[!weekly_train,])[1])
wlogis_split.pred[wlogis_split.probs>.5]<-"Up"
table(wlogis_split.pred,Weekly[!weekly_train, ]$Direction)
##                  
## wlogis_split.pred Down Up
##              Down    9  5
##              Up     34 56
#정확도
mean(wlogis_split.pred==Weekly[!weekly_train, ]$Direction)
## [1] 0.625
# Up일 때의 정확도
56/(56+34)
## [1] 0.6222222
#Down일 때의 정확도
9/(9+5)
## [1] 0.6428571

전체 정확도는 62.5%이고 Up을 예측할 때의 정확도는 62.2%로 Down을 예측할 때의 정확도인 64.3%보다 정확도가 더 낮다.

  1. Repeat (d) using LDA
wlda<-lda(Direction~ Lag2, data=Weekly, subset=weekly_train)
wlda
## Call:
## lda(Direction ~ Lag2, data = Weekly, subset = weekly_train)
## 
## Prior probabilities of groups:
##      Down        Up 
## 0.4477157 0.5522843 
## 
## Group means:
##             Lag2
## Down -0.03568254
## Up    0.26036581
## 
## Coefficients of linear discriminants:
##            LD1
## Lag2 0.4414162
wlda.pred<-predict(wlda,Weekly[!weekly_train,])
table(wlda.pred$class,Weekly[!weekly_train,]$Direction)
##       
##        Down Up
##   Down    9  5
##   Up     34 56
#정확도
mean(wlda.pred$class==Weekly[!weekly_train, ]$Direction)
## [1] 0.625
  1. Repeat (d) using QDA
wqda<-qda(Direction~ Lag2, data=Weekly, subset=weekly_train)
wqda
## Call:
## qda(Direction ~ Lag2, data = Weekly, subset = weekly_train)
## 
## Prior probabilities of groups:
##      Down        Up 
## 0.4477157 0.5522843 
## 
## Group means:
##             Lag2
## Down -0.03568254
## Up    0.26036581
wqda.pred<-predict(wqda,Weekly[!weekly_train,])
table(wqda.pred$class,Weekly[!weekly_train,]$Direction)
##       
##        Down Up
##   Down    0  0
##   Up     43 61
#정확도
mean(wqda.pred$class==Weekly[!weekly_train, ]$Direction)
## [1] 0.5865385
  1. Which of these methods appears to provide the best results on this data?
cat('Logistic Regression',mean(wlogis_split.pred==Weekly[!weekly_train, ]$Direction))
## Logistic Regression 0.625
cat('LDA',mean(wlda.pred$class==Weekly[!weekly_train, ]$Direction))
## LDA 0.625
cat('QDA',mean(wqda.pred$class==Weekly[!weekly_train, ]$Direction))
## QDA 0.5865385

정확도가 가장 높은 로지스틱 회귀분석과 LDA가 가장 좋은 결과를 내는 방법이다.

  1. Experiment with different combinations of predictors, including possible transformations and interactions, for each of the methods. Report the variables, method, and associated confusion matrix that appears to provide the best results on the held out data.
wlogis_inter<-glm(Direction ~ Lag1 * Lag2, data = Weekly, family = "binomial", subset = weekly_train)
summary(wlogis_inter)
## 
## Call:
## glm(formula = Direction ~ Lag1 * Lag2, family = "binomial", data = Weekly, 
##     subset = weekly_train)
## 
## Coefficients:
##              Estimate Std. Error z value Pr(>|z|)   
## (Intercept)  0.211419   0.064589   3.273  0.00106 **
## Lag1        -0.051505   0.030727  -1.676  0.09370 . 
## Lag2         0.053471   0.029193   1.832  0.06700 . 
## Lag1:Lag2    0.001921   0.007460   0.257  0.79680   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 1354.7  on 984  degrees of freedom
## Residual deviance: 1346.9  on 981  degrees of freedom
## AIC: 1354.9
## 
## Number of Fisher Scoring iterations: 4
wlogis_inter.probs<-predict(wlogis_inter,Weekly[!weekly_train,], type="response")
wlogis_inter.pred<-rep("Down",dim(Weekly[!weekly_train,])[1])
wlogis_inter.pred[wlogis_inter.probs>.5]<-"Up"
table(wlogis_inter.pred,Weekly[!weekly_train, ]$Direction)
##                  
## wlogis_inter.pred Down Up
##              Down    7  8
##              Up     36 53
mean(wlogis_inter.pred==Weekly[!weekly_train, ]$Direction)
## [1] 0.5769231
wlda_inter<-lda(Direction~ Lag1*Lag2, data=Weekly, subset=weekly_train)
wlda_inter
## Call:
## lda(Direction ~ Lag1 * Lag2, data = Weekly, subset = weekly_train)
## 
## Prior probabilities of groups:
##      Down        Up 
## 0.4477157 0.5522843 
## 
## Group means:
##              Lag1        Lag2  Lag1:Lag2
## Down  0.289444444 -0.03568254 -0.8014495
## Up   -0.009213235  0.26036581 -0.1393632
## 
## Coefficients of linear discriminants:
##                    LD1
## Lag1      -0.285484602
## Lag2       0.295080109
## Lag1:Lag2  0.009629381
wlda_inter.pred<-predict(wlda_inter,Weekly[!weekly_train,])
table(wlda_inter.pred$class,Weekly[!weekly_train,]$Direction)
##       
##        Down Up
##   Down    7  8
##   Up     36 53
mean(wlda_inter.pred$class==Weekly[!weekly_train, ]$Direction)
## [1] 0.5769231
wqda_inter<-qda(Direction~ Lag1*Lag2, data=Weekly, subset=weekly_train)
wqda_inter
## Call:
## qda(Direction ~ Lag1 * Lag2, data = Weekly, subset = weekly_train)
## 
## Prior probabilities of groups:
##      Down        Up 
## 0.4477157 0.5522843 
## 
## Group means:
##              Lag1        Lag2  Lag1:Lag2
## Down  0.289444444 -0.03568254 -0.8014495
## Up   -0.009213235  0.26036581 -0.1393632
wqda_inter.pred<-predict(wqda_inter,Weekly[!weekly_train,])
table(wqda_inter.pred$class,Weekly[!weekly_train,]$Direction)
##       
##        Down Up
##   Down   23 36
##   Up     20 25
mean(wqda_inter.pred$class==Weekly[!weekly_train, ]$Direction)
## [1] 0.4615385

로지스틱 회귀분석에서는 interaction term의 유의성이 높지않고, 3개 모델 모두 interaction term을 포함시킨 것의 정확도가 더 낮다.

Auto

  1. In this problem, you will develop a model to predict whether a given car gets high or low gas mileage based on the Auto data set.
library(ISLR2)
head(Auto)
##   mpg cylinders displacement horsepower weight acceleration year origin
## 1  18         8          307        130   3504         12.0   70      1
## 2  15         8          350        165   3693         11.5   70      1
## 3  18         8          318        150   3436         11.0   70      1
## 4  16         8          304        150   3433         12.0   70      1
## 5  17         8          302        140   3449         10.5   70      1
## 6  15         8          429        198   4341         10.0   70      1
##                        name
## 1 chevrolet chevelle malibu
## 2         buick skylark 320
## 3        plymouth satellite
## 4             amc rebel sst
## 5               ford torino
## 6          ford galaxie 500

변수 설명

mpg: 연비
cylinders: 엔진 실린더 개수
displacement: 배기량
horsepower: 마력(hp)
weight: 자동차 무게
acceleration: 초당 가속력
year: 출시 년도
origin: 제조국(1: 미국, 2: 유럽, 3: 일본)
car name: 자동차 이름

  1. Create a binary variable, mpg01, that contains a 1 if mpg contains a value above its median, and a 0 if mpg contains a value below its median. You can compute the median using the median() function. Note you may find it helpful to use the data.frame() function to create a single data set containing both mpg01 and the other Auto variables.
mpg01 <- ifelse(Auto$mpg > median(Auto$mpg),1,0)
Auto<-Auto[,-9] # 자동차 이름 열 제거
Autoplus<- data.frame(Auto, mpg01)
head(Autoplus)
##   mpg cylinders displacement horsepower weight acceleration year origin mpg01
## 1  18         8          307        130   3504         12.0   70      1     0
## 2  15         8          350        165   3693         11.5   70      1     0
## 3  18         8          318        150   3436         11.0   70      1     0
## 4  16         8          304        150   3433         12.0   70      1     0
## 5  17         8          302        140   3449         10.5   70      1     0
## 6  15         8          429        198   4341         10.0   70      1     0
  1. Explore the data graphically in order to investigate the association between mpg01 and the other features. Which of the other features seem most likely to be useful in predicting mpg01? Scatterplots and boxplots may be useful tools to answer this question. Describe your findings.
summary(Autoplus)
##       mpg          cylinders      displacement     horsepower        weight    
##  Min.   : 9.00   Min.   :3.000   Min.   : 68.0   Min.   : 46.0   Min.   :1613  
##  1st Qu.:17.00   1st Qu.:4.000   1st Qu.:105.0   1st Qu.: 75.0   1st Qu.:2225  
##  Median :22.75   Median :4.000   Median :151.0   Median : 93.5   Median :2804  
##  Mean   :23.45   Mean   :5.472   Mean   :194.4   Mean   :104.5   Mean   :2978  
##  3rd Qu.:29.00   3rd Qu.:8.000   3rd Qu.:275.8   3rd Qu.:126.0   3rd Qu.:3615  
##  Max.   :46.60   Max.   :8.000   Max.   :455.0   Max.   :230.0   Max.   :5140  
##   acceleration        year           origin          mpg01    
##  Min.   : 8.00   Min.   :70.00   Min.   :1.000   Min.   :0.0  
##  1st Qu.:13.78   1st Qu.:73.00   1st Qu.:1.000   1st Qu.:0.0  
##  Median :15.50   Median :76.00   Median :1.000   Median :0.5  
##  Mean   :15.54   Mean   :75.98   Mean   :1.577   Mean   :0.5  
##  3rd Qu.:17.02   3rd Qu.:79.00   3rd Qu.:2.000   3rd Qu.:1.0  
##  Max.   :24.80   Max.   :82.00   Max.   :3.000   Max.   :1.0
cor(Autoplus)
##                     mpg  cylinders displacement horsepower     weight
## mpg           1.0000000 -0.7776175   -0.8051269 -0.7784268 -0.8322442
## cylinders    -0.7776175  1.0000000    0.9508233  0.8429834  0.8975273
## displacement -0.8051269  0.9508233    1.0000000  0.8972570  0.9329944
## horsepower   -0.7784268  0.8429834    0.8972570  1.0000000  0.8645377
## weight       -0.8322442  0.8975273    0.9329944  0.8645377  1.0000000
## acceleration  0.4233285 -0.5046834   -0.5438005 -0.6891955 -0.4168392
## year          0.5805410 -0.3456474   -0.3698552 -0.4163615 -0.3091199
## origin        0.5652088 -0.5689316   -0.6145351 -0.4551715 -0.5850054
## mpg01         0.8369392 -0.7591939   -0.7534766 -0.6670526 -0.7577566
##              acceleration       year     origin      mpg01
## mpg             0.4233285  0.5805410  0.5652088  0.8369392
## cylinders      -0.5046834 -0.3456474 -0.5689316 -0.7591939
## displacement   -0.5438005 -0.3698552 -0.6145351 -0.7534766
## horsepower     -0.6891955 -0.4163615 -0.4551715 -0.6670526
## weight         -0.4168392 -0.3091199 -0.5850054 -0.7577566
## acceleration    1.0000000  0.2903161  0.2127458  0.3468215
## year            0.2903161  1.0000000  0.1815277  0.4299042
## origin          0.2127458  0.1815277  1.0000000  0.5136984
## mpg01           0.3468215  0.4299042  0.5136984  1.0000000
pairs(Autoplus)

par(mfrow=c(2,3))
boxplot(cylinders ~ mpg01, data = Autoplus, main = "Cylinders & mpg01")
boxplot(displacement ~ mpg01, data = Autoplus, main = "Displacement & mpg01")
boxplot(horsepower ~ mpg01, data = Autoplus, main = "Horsepower & mpg01")
boxplot(weight ~ mpg01, data = Autoplus, main = "Weight & mpg01")
boxplot(acceleration ~ mpg01, data = Autoplus, main = "Acceleration & mpg01")
boxplot(year ~ mpg01, data = Autoplus, main = "Year & mpg01")

위의 수치들과 그래프들을 종합해보면 mpg01을 예측할 때 가장 유용한 변수는 mpg, cylinders, displacement, horsepower, weight이다.

  1. Split the data into a training set and test set.
set.seed(2)
train<-sample(nrow(Autoplus)*0.7)
auto_train<-Autoplus[train, ]
auto_test<-Autoplus[-train, ]
  1. Perform LDA on the training data in order to predict mpg01 using the variables that seemed most associated with mpg01 in (b). What is the test error of the model obtained?
alda <- lda(mpg01 ~ cylinders + displacement + horsepower + weight, data = Autoplus, subset = train)
alda
## Call:
## lda(mpg01 ~ cylinders + displacement + horsepower + weight, data = Autoplus, 
##     subset = train)
## 
## Prior probabilities of groups:
##         0         1 
## 0.6423358 0.3576642 
## 
## Group means:
##   cylinders displacement horsepower   weight
## 0  6.784091     275.6250  131.68750 3637.381
## 1  4.040816     106.4541   78.04082 2227.612
## 
## Coefficients of linear discriminants:
##                       LD1
## cylinders    -0.446091128
## displacement -0.002075782
## horsepower    0.011483399
## weight       -0.001146243
alda.pred<-predict(alda,auto_test)
table(alda.pred$class,auto_test$mpg01)
##    
##      0  1
##   0 18 16
##   1  2 82
mean(alda.pred$class==auto_test$mpg01)
## [1] 0.8474576
  1. Perform QDA on the training data in order to predict mpg01 using the variables that seemed most associated with mpg01 in (b). What is the test error of the model obtained?
aqda <- qda(mpg01 ~ cylinders + displacement + horsepower + weight, data = Autoplus, subset = train)
aqda
## Call:
## qda(mpg01 ~ cylinders + displacement + horsepower + weight, data = Autoplus, 
##     subset = train)
## 
## Prior probabilities of groups:
##         0         1 
## 0.6423358 0.3576642 
## 
## Group means:
##   cylinders displacement horsepower   weight
## 0  6.784091     275.6250  131.68750 3637.381
## 1  4.040816     106.4541   78.04082 2227.612
aqda.pred<-predict(aqda,auto_test)
table(aqda.pred$class,auto_test$mpg01)
##    
##      0  1
##   0 18 19
##   1  2 79
mean(aqda.pred$class==auto_test$mpg01)
## [1] 0.8220339
  1. Perform logistic regression on the training data in order to predict mpg01 using the variables that seemed most associated with mpg01 in (b). What is the test error of the model obtained?
alogis <- glm(mpg01 ~ cylinders + displacement + horsepower + weight, data = Autoplus, subset = train, family="binomial")
summary(alogis)
## 
## Call:
## glm(formula = mpg01 ~ cylinders + displacement + horsepower + 
##     weight, family = "binomial", data = Autoplus, subset = train)
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept)  15.550194   2.878745   5.402  6.6e-08 ***
## cylinders    -0.631193   0.639513  -0.987   0.3236    
## displacement -0.007109   0.014815  -0.480   0.6313    
## horsepower   -0.044299   0.023190  -1.910   0.0561 .  
## weight       -0.002898   0.001142  -2.538   0.0112 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 357.33  on 273  degrees of freedom
## Residual deviance: 105.85  on 269  degrees of freedom
## AIC: 115.85
## 
## Number of Fisher Scoring iterations: 8
alogis.probs<-predict(alogis,auto_test, type="response")
alogis.pred<-rep(0,nrow(auto_test))
alogis.pred[alogis.probs>.5]=1
table(alogis.pred,auto_test$mpg01)
##            
## alogis.pred  0  1
##           0 20 21
##           1  0 77
mean(alogis.pred==auto_test$mpg01)
## [1] 0.8220339

LDA 방법의 정확도가 84.7%로 가장 높음.

Boston

  1. Using the Boston data set, fit classification models in order to predict whether a given census tract has a crime rate above or below the median. Hint: You will have to create the response variable yourself, using the variables that are contained in Boston data set.
library(ISLR2)
head(Boston)
##      crim zn indus chas   nox    rm  age    dis rad tax ptratio  black lstat
## 1 0.00632 18  2.31    0 0.538 6.575 65.2 4.0900   1 296    15.3 396.90  4.98
## 2 0.02731  0  7.07    0 0.469 6.421 78.9 4.9671   2 242    17.8 396.90  9.14
## 3 0.02729  0  7.07    0 0.469 7.185 61.1 4.9671   2 242    17.8 392.83  4.03
## 4 0.03237  0  2.18    0 0.458 6.998 45.8 6.0622   3 222    18.7 394.63  2.94
## 5 0.06905  0  2.18    0 0.458 7.147 54.2 6.0622   3 222    18.7 396.90  5.33
## 6 0.02985  0  2.18    0 0.458 6.430 58.7 6.0622   3 222    18.7 394.12  5.21
##   medv
## 1 24.0
## 2 21.6
## 3 34.7
## 4 33.4
## 5 36.2
## 6 28.7

변수 설명

crim: 마을별 1인당 범죄율
zn: 25,000 평방피트이상인 주거용 토지의 비율
indus: 마을 당 비소매상업부지의의 비율
chas: 찰스강에 대한 더미변수(강 경계에 위치한 경우 1, 아니면 0)
nox: 10ppm 당 일산화질소 농도
rm: 거주지당 평균 방의 개수
age:1940년 이전에 건축된 주택의 자가거주 비율
dis: 5개의 보스턴 직업센터까지의 접근성 지수
rad: 방사형 도로까지의 접근성 지수
tax: 10,000 달러 당 재산세율
ptratio: 마을별 학생/교사 비율
black: 마을별 흑인의 비율율 lstat: 저소득계층의 비율
medv: 자가주택의 가격의 중앙값

  1. Create a binary variable, crim01, that contains a 1 if crim contains a value above its median, and a 0 if crim contains a value below its median.
crim01 <- ifelse(Boston$crim > median(Boston$crim),1,0)
bostonplus<- data.frame(Boston, crim01)
head(bostonplus)
##      crim zn indus chas   nox    rm  age    dis rad tax ptratio  black lstat
## 1 0.00632 18  2.31    0 0.538 6.575 65.2 4.0900   1 296    15.3 396.90  4.98
## 2 0.02731  0  7.07    0 0.469 6.421 78.9 4.9671   2 242    17.8 396.90  9.14
## 3 0.02729  0  7.07    0 0.469 7.185 61.1 4.9671   2 242    17.8 392.83  4.03
## 4 0.03237  0  2.18    0 0.458 6.998 45.8 6.0622   3 222    18.7 394.63  2.94
## 5 0.06905  0  2.18    0 0.458 7.147 54.2 6.0622   3 222    18.7 396.90  5.33
## 6 0.02985  0  2.18    0 0.458 6.430 58.7 6.0622   3 222    18.7 394.12  5.21
##   medv crim01
## 1 24.0      0
## 2 21.6      0
## 3 34.7      0
## 4 33.4      0
## 5 36.2      0
## 6 28.7      0
  1. Explore the data graphically in order to investigate the association between crim01 and the other features.
summary(bostonplus)
##       crim                zn             indus            chas        
##  Min.   : 0.00632   Min.   :  0.00   Min.   : 0.46   Min.   :0.00000  
##  1st Qu.: 0.08205   1st Qu.:  0.00   1st Qu.: 5.19   1st Qu.:0.00000  
##  Median : 0.25651   Median :  0.00   Median : 9.69   Median :0.00000  
##  Mean   : 3.61352   Mean   : 11.36   Mean   :11.14   Mean   :0.06917  
##  3rd Qu.: 3.67708   3rd Qu.: 12.50   3rd Qu.:18.10   3rd Qu.:0.00000  
##  Max.   :88.97620   Max.   :100.00   Max.   :27.74   Max.   :1.00000  
##       nox               rm             age              dis        
##  Min.   :0.3850   Min.   :3.561   Min.   :  2.90   Min.   : 1.130  
##  1st Qu.:0.4490   1st Qu.:5.886   1st Qu.: 45.02   1st Qu.: 2.100  
##  Median :0.5380   Median :6.208   Median : 77.50   Median : 3.207  
##  Mean   :0.5547   Mean   :6.285   Mean   : 68.57   Mean   : 3.795  
##  3rd Qu.:0.6240   3rd Qu.:6.623   3rd Qu.: 94.08   3rd Qu.: 5.188  
##  Max.   :0.8710   Max.   :8.780   Max.   :100.00   Max.   :12.127  
##       rad              tax           ptratio          black       
##  Min.   : 1.000   Min.   :187.0   Min.   :12.60   Min.   :  0.32  
##  1st Qu.: 4.000   1st Qu.:279.0   1st Qu.:17.40   1st Qu.:375.38  
##  Median : 5.000   Median :330.0   Median :19.05   Median :391.44  
##  Mean   : 9.549   Mean   :408.2   Mean   :18.46   Mean   :356.67  
##  3rd Qu.:24.000   3rd Qu.:666.0   3rd Qu.:20.20   3rd Qu.:396.23  
##  Max.   :24.000   Max.   :711.0   Max.   :22.00   Max.   :396.90  
##      lstat            medv           crim01   
##  Min.   : 1.73   Min.   : 5.00   Min.   :0.0  
##  1st Qu.: 6.95   1st Qu.:17.02   1st Qu.:0.0  
##  Median :11.36   Median :21.20   Median :0.5  
##  Mean   :12.65   Mean   :22.53   Mean   :0.5  
##  3rd Qu.:16.95   3rd Qu.:25.00   3rd Qu.:1.0  
##  Max.   :37.97   Max.   :50.00   Max.   :1.0
cor(bostonplus)
##                crim          zn       indus         chas         nox
## crim     1.00000000 -0.20046922  0.40658341 -0.055891582  0.42097171
## zn      -0.20046922  1.00000000 -0.53382819 -0.042696719 -0.51660371
## indus    0.40658341 -0.53382819  1.00000000  0.062938027  0.76365145
## chas    -0.05589158 -0.04269672  0.06293803  1.000000000  0.09120281
## nox      0.42097171 -0.51660371  0.76365145  0.091202807  1.00000000
## rm      -0.21924670  0.31199059 -0.39167585  0.091251225 -0.30218819
## age      0.35273425 -0.56953734  0.64477851  0.086517774  0.73147010
## dis     -0.37967009  0.66440822 -0.70802699 -0.099175780 -0.76923011
## rad      0.62550515 -0.31194783  0.59512927 -0.007368241  0.61144056
## tax      0.58276431 -0.31456332  0.72076018 -0.035586518  0.66802320
## ptratio  0.28994558 -0.39167855  0.38324756 -0.121515174  0.18893268
## black   -0.38506394  0.17552032 -0.35697654  0.048788485 -0.38005064
## lstat    0.45562148 -0.41299457  0.60379972 -0.053929298  0.59087892
## medv    -0.38830461  0.36044534 -0.48372516  0.175260177 -0.42732077
## crim01   0.40939545 -0.43615103  0.60326017  0.070096774  0.72323480
##                  rm         age         dis          rad         tax    ptratio
## crim    -0.21924670  0.35273425 -0.37967009  0.625505145  0.58276431  0.2899456
## zn       0.31199059 -0.56953734  0.66440822 -0.311947826 -0.31456332 -0.3916785
## indus   -0.39167585  0.64477851 -0.70802699  0.595129275  0.72076018  0.3832476
## chas     0.09125123  0.08651777 -0.09917578 -0.007368241 -0.03558652 -0.1215152
## nox     -0.30218819  0.73147010 -0.76923011  0.611440563  0.66802320  0.1889327
## rm       1.00000000 -0.24026493  0.20524621 -0.209846668 -0.29204783 -0.3555015
## age     -0.24026493  1.00000000 -0.74788054  0.456022452  0.50645559  0.2615150
## dis      0.20524621 -0.74788054  1.00000000 -0.494587930 -0.53443158 -0.2324705
## rad     -0.20984667  0.45602245 -0.49458793  1.000000000  0.91022819  0.4647412
## tax     -0.29204783  0.50645559 -0.53443158  0.910228189  1.00000000  0.4608530
## ptratio -0.35550149  0.26151501 -0.23247054  0.464741179  0.46085304  1.0000000
## black    0.12806864 -0.27353398  0.29151167 -0.444412816 -0.44180801 -0.1773833
## lstat   -0.61380827  0.60233853 -0.49699583  0.488676335  0.54399341  0.3740443
## medv     0.69535995 -0.37695457  0.24992873 -0.381626231 -0.46853593 -0.5077867
## crim01  -0.15637178  0.61393992 -0.61634164  0.619786249  0.60874128  0.2535684
##               black      lstat       medv      crim01
## crim    -0.38506394  0.4556215 -0.3883046  0.40939545
## zn       0.17552032 -0.4129946  0.3604453 -0.43615103
## indus   -0.35697654  0.6037997 -0.4837252  0.60326017
## chas     0.04878848 -0.0539293  0.1752602  0.07009677
## nox     -0.38005064  0.5908789 -0.4273208  0.72323480
## rm       0.12806864 -0.6138083  0.6953599 -0.15637178
## age     -0.27353398  0.6023385 -0.3769546  0.61393992
## dis      0.29151167 -0.4969958  0.2499287 -0.61634164
## rad     -0.44441282  0.4886763 -0.3816262  0.61978625
## tax     -0.44180801  0.5439934 -0.4685359  0.60874128
## ptratio -0.17738330  0.3740443 -0.5077867  0.25356836
## black    1.00000000 -0.3660869  0.3334608 -0.35121093
## lstat   -0.36608690  1.0000000 -0.7376627  0.45326273
## medv     0.33346082 -0.7376627  1.0000000 -0.26301673
## crim01  -0.35121093  0.4532627 -0.2630167  1.00000000
pairs(bostonplus)

par(mfrow=c(3,5))
boxplot(zn ~ crim01, data = bostonplus, main = "zn & crim01")
boxplot(indus ~ crim01, data = bostonplus, main = "indus & crim01")
boxplot(chas ~ crim01, data = bostonplus, main = "chas & crim01")
boxplot(nox ~ crim01, data = bostonplus, main = "nox & crim01")
boxplot(rm ~ crim01, data = bostonplus, main = "rm & crim01")
boxplot(age ~ crim01, data = bostonplus, main = "age & crim01")
boxplot(dis ~ crim01, data = bostonplus, main = "dis & crim01")
boxplot(rad ~ crim01, data = bostonplus, main = "rad & crim01")
boxplot(tax ~ crim01, data = bostonplus, main = "tax & crim01")
boxplot(ptratio ~ crim01, data = bostonplus, main = "ptratio & crim01")
boxplot(black ~ crim01, data = bostonplus, main = "black & crim01")
boxplot(lstat ~ crim01, data = bostonplus, main = "lstat & crim01")
boxplot(medv ~ crim01, data = bostonplus, main = "medv & crim01")

위의 수치들과 그래프들을 종합해보면 crim01을 예측할 때 가장 유용한 변수는 indus, nox, age, dis, rad, tax이다.

  1. Split the data into a training set and test set.
set.seed(2)
btrain<-sample(nrow(bostonplus)*0.7)
boston_train<-bostonplus[btrain, ]
boston_test<-bostonplus[-btrain, ]
  1. Perform LDA on the training data in order to predict crim01 using all variables.
#Logistic Regression
blogis_a <- glm(crim01 ~ ., data = bostonplus, subset = btrain, family="binomial")
## Warning: glm.fit: 알고리즘이 수렴하지 않았습니다
## Warning: glm.fit: 적합된 확률값들이 0 또는 1 입니다
summary(blogis_a)
## 
## Call:
## glm(formula = crim01 ~ ., family = "binomial", data = bostonplus, 
##     subset = btrain)
## 
## Coefficients:
##               Estimate Std. Error    z value Pr(>|z|)    
## (Intercept) -1.604e+16  1.044e+08 -153663445   <2e-16 ***
## crim         4.369e+15  9.794e+06  446063648   <2e-16 ***
## zn          -1.952e+13  2.074e+05  -94116146   <2e-16 ***
## indus       -4.772e+12  9.287e+05   -5139070   <2e-16 ***
## chas        -1.914e+14  1.398e+07  -13689582   <2e-16 ***
## nox          4.185e+15  7.905e+07   52945376   <2e-16 ***
## rm          -5.043e+13  1.382e+07   -3650155   <2e-16 ***
## age         -9.634e+11  2.176e+05   -4427362   <2e-16 ***
## dis         -6.701e+13  3.301e+06  -20302018   <2e-16 ***
## rad          3.366e+14  2.428e+06  138666512   <2e-16 ***
## tax         -5.552e+12  6.564e+04  -84583168   <2e-16 ***
## ptratio      2.224e+14  2.210e+06  100596897   <2e-16 ***
## black        2.189e+13  1.064e+05  205791141   <2e-16 ***
## lstat        2.303e+13  1.061e+06   21703614   <2e-16 ***
## medv         1.708e+13  1.189e+06   14365726   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 450.65  on 353  degrees of freedom
## Residual deviance: 648.79  on 339  degrees of freedom
## AIC: 678.79
## 
## Number of Fisher Scoring iterations: 25
blogis_a.probs<-predict(blogis_a,boston_test, type="response")
blogis_a.pred<-rep(0,nrow(boston_test))
blogis_a.pred[blogis_a.probs>.5]=1
table(blogis_a.pred,boston_test$crim01)
##              
## blogis_a.pred   0   1
##             0  12   0
##             1   5 135
mean(blogis_a.pred==boston_test$crim01)
## [1] 0.9671053

모든 변수의 추정 계수가 통계적으로 유의하다고 나옴. 정확도도 96.7%로 높게 나옴.

#LDA
blda_a <- lda(crim01 ~ ., data = bostonplus, subset = btrain)
blda_a
## Call:
## lda(crim01 ~ ., data = bostonplus, subset = btrain)
## 
## Prior probabilities of groups:
##         0         1 
## 0.6666667 0.3333333 
## 
## Group means:
##         crim        zn     indus       chas       nox       rm      age
## 0 0.09301674 22.398305  6.444746 0.05508475 0.4639606 6.426911 49.83305
## 1 1.01016424  2.576271 12.248814 0.11864407 0.6017458 6.357703 82.00847
##        dis      rad      tax  ptratio    black     lstat     medv
## 0 5.225892 4.190678 295.8051 17.73305 388.9124  9.134195 25.45847
## 1 2.982705 5.033898 340.0847 17.66102 363.6945 12.840763 24.25085
## 
## Coefficients of linear discriminants:
##                   LD1
## crim     1.7379398567
## zn       0.0002354896
## indus   -0.0102358034
## chas     0.0336838021
## nox      3.9093069414
## rm       0.4472964829
## age      0.0098605632
## dis     -0.0532252212
## rad      0.1345181399
## tax      0.0006061110
## ptratio  0.1990744467
## black    0.0030884882
## lstat    0.0030285219
## medv     0.0157608224
blda_a.pred<-predict(blda_a,boston_test)
table(blda_a.pred$class,boston_test$crim01)
##    
##       0   1
##   0  17   3
##   1   0 132
mean(blda_a.pred$class==boston_test$crim01)
## [1] 0.9802632

정확도가 98%로 높게 나옴.

#QDA
bqda_a <- qda(crim01 ~ ., data = bostonplus, subset = btrain)
bqda_a
## Call:
## qda(crim01 ~ ., data = bostonplus, subset = btrain)
## 
## Prior probabilities of groups:
##         0         1 
## 0.6666667 0.3333333 
## 
## Group means:
##         crim        zn     indus       chas       nox       rm      age
## 0 0.09301674 22.398305  6.444746 0.05508475 0.4639606 6.426911 49.83305
## 1 1.01016424  2.576271 12.248814 0.11864407 0.6017458 6.357703 82.00847
##        dis      rad      tax  ptratio    black     lstat     medv
## 0 5.225892 4.190678 295.8051 17.73305 388.9124  9.134195 25.45847
## 1 2.982705 5.033898 340.0847 17.66102 363.6945 12.840763 24.25085
bqda_a.pred<-predict(bqda_a,boston_test)
table(bqda_a.pred$class,boston_test$crim01)
##    
##       0   1
##   0  16   0
##   1   1 135
mean(bqda_a.pred$class==boston_test$crim01)
## [1] 0.9934211

정확도가 99.3%로 매우 높게 나옴. 모든 변수들을 포함한 모델을 사용할 때 QDA 방법의 정확도가 가장 높음.

  1. Perform LDA on the training data in order to predict crim01 using the variables that seemed most associated with crim01 in (b).
#Logistic Regression
blogis <- glm(crim01 ~ indus + nox + age + dis + rad + tax, data = bostonplus, subset = btrain, family="binomial")
summary(blogis)
## 
## Call:
## glm(formula = crim01 ~ indus + nox + age + dis + rad + tax, family = "binomial", 
##     data = bostonplus, subset = btrain)
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -28.270990   4.318242  -6.547 5.88e-11 ***
## indus        -0.088496   0.049471  -1.789   0.0736 .  
## nox          50.296106   8.470018   5.938 2.88e-09 ***
## age           0.003096   0.009206   0.336   0.7366    
## dis           0.168815   0.151746   1.112   0.2659    
## rad           0.556877   0.129065   4.315 1.60e-05 ***
## tax          -0.003906   0.003162  -1.235   0.2167    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 450.65  on 353  degrees of freedom
## Residual deviance: 214.13  on 347  degrees of freedom
## AIC: 228.13
## 
## Number of Fisher Scoring iterations: 7
blogis.probs<-predict(blogis,boston_test, type="response")
blogis.pred<-rep(0,nrow(boston_test))
blogis.pred[blogis.probs>.5]=1
table(blogis.pred,boston_test$crim01)
##            
## blogis.pred   0   1
##           0  12   0
##           1   5 135
mean(blogis.pred==boston_test$crim01)
## [1] 0.9671053

모든 변수를 포함한 모델과 정확도는 동일하지만, 각 계수들의 통계적 유의성이 더 감소함.(p-value가 더 큼.)

#LDA
blda <- lda(crim01 ~ indus + nox + age + dis + rad + tax, data = bostonplus, subset = btrain)
blda
## Call:
## lda(crim01 ~ indus + nox + age + dis + rad + tax, data = bostonplus, 
##     subset = btrain)
## 
## Prior probabilities of groups:
##         0         1 
## 0.6666667 0.3333333 
## 
## Group means:
##       indus       nox      age      dis      rad      tax
## 0  6.444746 0.4639606 49.83305 5.225892 4.190678 295.8051
## 1 12.248814 0.6017458 82.00847 2.982705 5.033898 340.0847
## 
## Coefficients of linear discriminants:
##                LD1
## indus  0.002900596
## nox    8.572070230
## age    0.011460414
## dis   -0.063449167
## rad    0.185990960
## tax    0.001364278
blda.pred<-predict(blda,boston_test)
table(blda.pred$class,boston_test$crim01)
##    
##       0   1
##   0   7   0
##   1  10 135
mean(blda.pred$class==boston_test$crim01)
## [1] 0.9342105

정확도가 93.2%로 모든 변수를 포함한 모델보다 정확도가 감소함.

#QDA
bqda <- qda(crim01 ~ indus + nox + age + dis + rad + tax, data = bostonplus, subset = btrain)
bqda
## Call:
## qda(crim01 ~ indus + nox + age + dis + rad + tax, data = bostonplus, 
##     subset = btrain)
## 
## Prior probabilities of groups:
##         0         1 
## 0.6666667 0.3333333 
## 
## Group means:
##       indus       nox      age      dis      rad      tax
## 0  6.444746 0.4639606 49.83305 5.225892 4.190678 295.8051
## 1 12.248814 0.6017458 82.00847 2.982705 5.033898 340.0847
bqda.pred<-predict(bqda,boston_test)
table(bqda.pred$class,boston_test$crim01)
##    
##       0   1
##   0  12 132
##   1   5   3
mean(bqda.pred$class==boston_test$crim01)
## [1] 0.09868421

정확도가 9.87%로 모든 변수를 포함한 모델보다 정확도가 확연히 감소함. 세 가지 방법 모두 변수들을 선별한 모델보다 모든 변수를 포함한 모델의 정확도와 통계적 유의성이 더 높기 때문에 모든 변수를 포함한 모델을 사용하는 것이 더 좋다.