Question 13

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.

(a) 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  
##            
##            
##            
## 
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
ggscatmat(Weekly, color = "Direction")
## Warning in ggscatmat(Weekly, color = "Direction"): Factor variables are omitted
## in plot
## Warning: The dot-dot notation (`..scaled..`) was deprecated in ggplot2 3.4.0.
## ℹ Please use `after_stat(scaled)` instead.
## ℹ The deprecated feature was likely used in the GGally package.
##   Please report the issue at <]8;;https://github.com/ggobi/ggally/issueshttps://github.com/ggobi/ggally/issues]8;;>.

ggscatmat(Weekly, columns = 2:9, color = "Direction")
## Warning in ggscatmat(Weekly, columns = 2:9, color = "Direction"): Factor
## variables are omitted in plot

Weekly %>% mutate(row = row_number()) %>%
  ggplot(aes(x = row, y = Volume)) + 
  geom_point() + 
  geom_smooth(se = FALSE)
## `geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'

Correlations are all basically zero, except for year and volume which shows an increase in volume over time.

(b) Use the full data set to perform a logistic regression with Direction as the response and the five lag variables plus Volumeas predictors. Use the summary function to print the results. Doany of the predictors appear to be statistically significant? If so, which ones?

glm_fit_wk <- glm(Direction ~ 
                    Lag1 + Lag2 + Lag3 + Lag4 + Lag5 + Volume,
                  data = Weekly, 
                  family = binomial)
summary(glm_fit_wk)
## 
## Call:
## glm(formula = Direction ~ Lag1 + Lag2 + Lag3 + Lag4 + Lag5 + 
##     Volume, family = binomial, data = Weekly)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -1.6949  -1.2565   0.9913   1.0849   1.4579  
## 
## 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

Only Lag2 shows any real significance.

(c) 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.

glm_probs_wk = predict(glm_fit_wk, type = "response")
glm_pred_wk = rep("Down", length(glm_probs_wk)) 
glm_pred_wk[glm_probs_wk > 0.5] <- "Up"

table(glm_pred_wk, Weekly$Direction)
##            
## glm_pred_wk Down  Up
##        Down   54  48
##        Up    430 557
mean(glm_pred_wk == Weekly$Direction)
## [1] 0.5610652

It appears as though 56.1% of the responses are predicted correctly.Training error rate = 43.89%, overly optimistic.There are only 54 out of 484 down days accurately predicted but 557 out of 605 of up days are predicted. So its right only ~ 11% of time when market is down but ~ 92% when up.

(d) 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).

train <- (Weekly$Year < 2009)
Weekly_train <- Weekly[train,]
Weekly_test <- Weekly[!train,]
Direction_train <- Weekly_train$Direction
Direction_test <- Weekly_test$Direction

logistic_wkly <- glm(Direction ~ Lag2, 
                     data = Weekly_train, 
                     family = binomial)

(e) Repeat (d) using LDA.

lda_wkly <- lda(Direction ~ Lag2, data = Weekly, subset = train)
lda_wkly
## Call:
## lda(Direction ~ Lag2, data = Weekly, subset = 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
plot(lda_wkly)

lda_probs <- predict(lda_wkly, Weekly_test)
table(lda_probs$class, Direction_test)
##       Direction_test
##        Down Up
##   Down    9  5
##   Up     34 56
mean(lda_probs$class == Direction_test)
## [1] 0.625

(f) Repeat (d) using QDA.

qda_wkly <- qda(Direction ~ Lag2, data = Weekly, subset = train)
qda_wkly
## Call:
## qda(Direction ~ Lag2, data = Weekly, subset = train)
## 
## Prior probabilities of groups:
##      Down        Up 
## 0.4477157 0.5522843 
## 
## Group means:
##             Lag2
## Down -0.03568254
## Up    0.26036581
qda_pred <- predict(qda_wkly, Weekly_test)
table(qda_pred$class, Direction_test)
##       Direction_test
##        Down Up
##   Down    0  0
##   Up     43 61
mean(qda_pred$class == Direction_test)
## [1] 0.5865385

(g) Repeat (d) using KNN with K = 1.

train_X <- as.matrix(Weekly$Lag2[train])
test_X <- as.matrix(Weekly$Lag2[!train])

set.seed(1)
knn_pred <- knn(train_X, test_X, Direction_train, k = 1)
table(knn_pred, Direction_test)
##         Direction_test
## knn_pred Down Up
##     Down   21 30
##     Up     22 31
mean(knn_pred == Direction_test)
## [1] 0.5

(h)Which of these methods appears to provide the best results on this data?

Logistic and LDA are pretty close. QDA is not very good nor is 1NN,which is the worst.

(i) 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. Note that you should also experiment with values for K in the KNN classifier.

logistic_wkly3 <- glm(Direction ~ Lag2:Lag1, 
                     data = Weekly_train, 
                     family = binomial)
summary(logistic_wkly3)
## 
## Call:
## glm(formula = Direction ~ Lag2:Lag1, family = binomial, data = Weekly_train)
## 
## Deviance Residuals: 
##    Min      1Q  Median      3Q     Max  
## -1.368  -1.269   1.077   1.089   1.353  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)    
## (Intercept)  0.21333    0.06421   3.322 0.000893 ***
## Lag2:Lag1    0.00717    0.00697   1.029 0.303649    
## ---
## 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: 1353.6  on 983  degrees of freedom
## AIC: 1357.6
## 
## Number of Fisher Scoring iterations: 4
logistic_probs3 <- predict(logistic_wkly3, Weekly_test, type = "response")
logistic_pred3 = rep("Down", length(Direction_test))
logistic_pred3[logistic_probs3 > 0.5] <- "Up"
table(logistic_pred3, Direction_test)
##               Direction_test
## logistic_pred3 Down Up
##           Down    1  1
##           Up     42 60
mean(logistic_pred3 == Direction_test)
## [1] 0.5865385
qda_wkly2 <- qda(Direction ~ Lag2 + sqrt(abs(Lag2)),
                 data = Weekly,
                 subset = train)
qda_wkly2
## Call:
## qda(Direction ~ Lag2 + sqrt(abs(Lag2)), data = Weekly, subset = train)
## 
## Prior probabilities of groups:
##      Down        Up 
## 0.4477157 0.5522843 
## 
## Group means:
##             Lag2 sqrt(abs(Lag2))
## Down -0.03568254        1.140078
## Up    0.26036581        1.169635
qda_pred2 <- predict(qda_wkly2, Weekly_test)
table(qda_pred2$class, Direction_test)
##       Direction_test
##        Down Up
##   Down   12 13
##   Up     31 48
mean(qda_pred2$class == Direction_test)
## [1] 0.5769231
train_X <- as.matrix(Weekly$Lag2[train])
test_X <- as.matrix(Weekly$Lag2[!train])

set.seed(1)
knn_pred3 <- knn(train_X, test_X, Direction_train, k = 3)
table(knn_pred3, Direction_test)
##          Direction_test
## knn_pred3 Down Up
##      Down   16 20
##      Up     27 41
mean(knn_pred3 == Direction_test)
## [1] 0.5480769
train_X <- as.matrix(Weekly$Lag2[train])
test_X <- as.matrix(Weekly$Lag2[!train])

set.seed(1)
knn_pred100 <- knn(train_X, test_X, Direction_train, k = 100)
table(knn_pred100, Direction_test)
##            Direction_test
## knn_pred100 Down Up
##        Down   10 11
##        Up     33 50
mean(knn_pred100 == Direction_test)
## [1] 0.5769231

Question 13

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(GGally)
Auto <- as_tibble(ISLR::Auto)

(a) 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.

Auto_mpg01 <- Auto %>% 
  mutate(mpg01 = ifelse(mpg > median(mpg), 1, 0))

(b) 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(Auto_mpg01)
##       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                      name    
##  Min.   : 8.00   Min.   :70.00   Min.   :1.000   amc matador       :  5  
##  1st Qu.:13.78   1st Qu.:73.00   1st Qu.:1.000   ford pinto        :  5  
##  Median :15.50   Median :76.00   Median :1.000   toyota corolla    :  5  
##  Mean   :15.54   Mean   :75.98   Mean   :1.577   amc gremlin       :  4  
##  3rd Qu.:17.02   3rd Qu.:79.00   3rd Qu.:2.000   amc hornet        :  4  
##  Max.   :24.80   Max.   :82.00   Max.   :3.000   chevrolet chevette:  4  
##                                                  (Other)           :365  
##      mpg01    
##  Min.   :0.0  
##  1st Qu.:0.0  
##  Median :0.5  
##  Mean   :0.5  
##  3rd Qu.:1.0  
##  Max.   :1.0  
## 
ggscatmat(as.data.frame(Auto_mpg01))
## Warning in ggscatmat(as.data.frame(Auto_mpg01)): Factor variables are omitted in
## plot

Auto_mpg01 %>% 
  ggplot(aes(cut_number(mpg01, 2), displacement)) + 
  geom_boxplot()

Auto_mpg01 %>% 
  ggplot(aes(cut_number(mpg01, 2), horsepower)) + 
  geom_boxplot()

Auto_mpg01 %>% 
  ggplot(aes(cut_number(mpg01, 2), weight)) + 
  geom_boxplot()

Auto_mpg01 %>% 
  ggplot(aes(cut_number(mpg01, 2), acceleration)) + 
  geom_boxplot()

ggplot(Auto_mpg01) +
  geom_count(aes(cut_number(mpg01, 2), cylinders))

ggplot(Auto_mpg01) +
  geom_boxplot(aes(cut_number(mpg01, 2), cylinders))

Auto_mpg01 %>% 
  ggplot(aes(cut_number(mpg01, 2), mpg)) + 
  geom_boxplot()

To predict mpg01, can use mpg. there seems to be neg corr with cylnders and displacement, horsepower, and weight but positive correlation with acceleration.

(c) Split the data into a training set and a test set.

train <- (Auto_mpg01$year %% 2 == 0)
train_auto <- Auto_mpg01[train,]
test_auto <- Auto_mpg01[!train,]

(d) Perform LDA on the training data in order to predict mpg01 sing the variables that seemed most associated with mpg01 in (b). What is the test error of the model obtained?

lda_auto <- lda(mpg01 ~ cylinders + displacement + horsepower + weight, 
                data = Auto_mpg01,
                subset = train)
lda_auto
## Call:
## lda(mpg01 ~ cylinders + displacement + horsepower + weight, data = Auto_mpg01, 
##     subset = train)
## 
## Prior probabilities of groups:
##         0         1 
## 0.4571429 0.5428571 
## 
## Group means:
##   cylinders displacement horsepower   weight
## 0  6.812500     271.7396  133.14583 3604.823
## 1  4.070175     111.6623   77.92105 2314.763
## 
## Coefficients of linear discriminants:
##                        LD1
## cylinders    -0.6741402638
## displacement  0.0004481325
## horsepower    0.0059035377
## weight       -0.0011465750
lda_auto_pred <- predict(lda_auto, test_auto)
table(lda_auto_pred$class, test_auto$mpg01)
##    
##      0  1
##   0 86  9
##   1 14 73
mean(lda_auto_pred$class == test_auto$mpg01)
## [1] 0.8736264
# test error rate is 
1 - mean(lda_auto_pred$class == test_auto$mpg01)
## [1] 0.1263736

(e) 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?

qda_auto <- qda(mpg01 ~ cylinders + displacement + horsepower + weight, 
                data = Auto_mpg01,
                subset = train)
qda_auto
## Call:
## qda(mpg01 ~ cylinders + displacement + horsepower + weight, data = Auto_mpg01, 
##     subset = train)
## 
## Prior probabilities of groups:
##         0         1 
## 0.4571429 0.5428571 
## 
## Group means:
##   cylinders displacement horsepower   weight
## 0  6.812500     271.7396  133.14583 3604.823
## 1  4.070175     111.6623   77.92105 2314.763
qda_auto_pred <- predict(qda_auto, test_auto)
table(qda_auto_pred$class, test_auto$mpg01)
##    
##      0  1
##   0 89 13
##   1 11 69
mean(qda_auto_pred$class == test_auto$mpg01)
## [1] 0.8681319
# test error rate is 
1 - mean(qda_auto_pred$class == test_auto$mpg01)
## [1] 0.1318681

(f) 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?

logistic_auto <- glm(mpg01 ~ cylinders + displacement + horsepower + weight,
                     data = Auto_mpg01,
                     subset = train,
                     family = binomial)
summary(logistic_auto)
## 
## Call:
## glm(formula = mpg01 ~ cylinders + displacement + horsepower + 
##     weight, family = binomial, data = Auto_mpg01, subset = train)
## 
## Deviance Residuals: 
##      Min        1Q    Median        3Q       Max  
## -2.48027  -0.03413   0.10583   0.29634   2.57584  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept)  17.658730   3.409012   5.180 2.22e-07 ***
## cylinders    -1.028032   0.653607  -1.573   0.1158    
## displacement  0.002462   0.015030   0.164   0.8699    
## horsepower   -0.050611   0.025209  -2.008   0.0447 *  
## weight       -0.002922   0.001137  -2.569   0.0102 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 289.58  on 209  degrees of freedom
## Residual deviance:  83.24  on 205  degrees of freedom
## AIC: 93.24
## 
## Number of Fisher Scoring iterations: 7
logistic_probs_auto <- predict(logistic_auto, test_auto, type = "response")
logistic_pred_auto <- rep(0,length(test_auto$mpg01))
logistic_pred_auto[logistic_probs_auto > 0.5] <- 1

table(logistic_pred_auto, test_auto$mpg01)
##                   
## logistic_pred_auto  0  1
##                  0 89 11
##                  1 11 71
mean(logistic_pred_auto == test_auto$mpg01)
## [1] 0.8791209
1 - mean(logistic_pred_auto == test_auto$mpg01)
## [1] 0.1208791

(g) Perform KNN on the training data, with several values of K, in order to predict mpg01. Use only the variables that seemed most associated with mpg01 in (b). What test errors do you obtain? Which value of K seems to perform the best on this data set?

train_auto_X <- cbind(
  Auto_mpg01$cylinders, 
  Auto_mpg01$displacement, 
  Auto_mpg01$horsepower,
  Auto_mpg01$weight
)[train,]

test_auto_X <- cbind(
  Auto_mpg01$cylinders, 
  Auto_mpg01$displacement, 
  Auto_mpg01$horsepower,
  Auto_mpg01$weight
)[!train,]

set.seed(1)
knn_auto1 <- knn(train_auto_X, test_auto_X, train_auto$mpg01, k = 1)
table(knn_auto1, test_auto$mpg01)
##          
## knn_auto1  0  1
##         0 83 11
##         1 17 71
mean(knn_auto1 == test_auto$mpg01)
## [1] 0.8461538
#test error
1 - mean(knn_auto1 == test_auto$mpg01)
## [1] 0.1538462
knn_auto10 <- knn(train_auto_X, test_auto_X, train_auto$mpg01, k = 10)
table(knn_auto10, test_auto$mpg01)
##           
## knn_auto10  0  1
##          0 77  7
##          1 23 75
mean(knn_auto10 == test_auto$mpg01)
## [1] 0.8351648
#test error
1 - mean(knn_auto10 == test_auto$mpg01)
## [1] 0.1648352

##Question 16

Using the Boston data set, fit classification models in order to predict whether a given suburb has a crime rate above or below the median. Explore logistic regression, LDA, and KNN models using various subsets of the predictors. Describe your findings.

Boston_tb <- as_tibble(Boston)

Boston_tb <- Boston_tb %>%
  mutate(crim01 = ifelse(crim > median(crim), 1, 0))

cor(Boston_tb)
##                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
ggscatmat(as.data.frame(Boston_tb))

Need to add factor to seperate ‘high crime’ (crim01 = 1) vs ‘low crime’ (crim01 = 0)

Boston_tb_f <- Boston_tb %>%
  mutate(crim_gp = 
           as.factor(
             ifelse(crim < median(crim), "below median", "above median")
             )
         ) %>%
  select(crim_gp, everything())

Boston_tb_f <- as.data.frame(Boston_tb_f)
ggscatmat(Boston_tb_f)
## Warning in ggscatmat(Boston_tb_f): Factor variables are omitted in plot

ggscatmat(Boston_tb_f, color = "crim_gp")
## Warning in cor(xvalue, yvalue, use = "pairwise.complete.obs", method =
## corMethod): the standard deviation is zero
## Warning in cor(xvalue, yvalue, use = "pairwise.complete.obs", method =
## corMethod): the standard deviation is zero

## Warning in cor(xvalue, yvalue, use = "pairwise.complete.obs", method =
## corMethod): the standard deviation is zero

## Warning in cor(xvalue, yvalue, use = "pairwise.complete.obs", method =
## corMethod): the standard deviation is zero

## Warning in cor(xvalue, yvalue, use = "pairwise.complete.obs", method =
## corMethod): the standard deviation is zero

## Warning in cor(xvalue, yvalue, use = "pairwise.complete.obs", method =
## corMethod): the standard deviation is zero

## Warning in cor(xvalue, yvalue, use = "pairwise.complete.obs", method =
## corMethod): the standard deviation is zero

## Warning in cor(xvalue, yvalue, use = "pairwise.complete.obs", method =
## corMethod): the standard deviation is zero

## Warning in cor(xvalue, yvalue, use = "pairwise.complete.obs", method =
## corMethod): the standard deviation is zero

## Warning in cor(xvalue, yvalue, use = "pairwise.complete.obs", method =
## corMethod): the standard deviation is zero

## Warning in cor(xvalue, yvalue, use = "pairwise.complete.obs", method =
## corMethod): the standard deviation is zero

## Warning in cor(xvalue, yvalue, use = "pairwise.complete.obs", method =
## corMethod): the standard deviation is zero

## Warning in cor(xvalue, yvalue, use = "pairwise.complete.obs", method =
## corMethod): the standard deviation is zero

## Warning in cor(xvalue, yvalue, use = "pairwise.complete.obs", method =
## corMethod): the standard deviation is zero

## Warning in cor(xvalue, yvalue, use = "pairwise.complete.obs", method =
## corMethod): the standard deviation is zero

## Warning in cor(xvalue, yvalue, use = "pairwise.complete.obs", method =
## corMethod): the standard deviation is zero

## Warning in cor(xvalue, yvalue, use = "pairwise.complete.obs", method =
## corMethod): the standard deviation is zero

## Warning in cor(xvalue, yvalue, use = "pairwise.complete.obs", method =
## corMethod): the standard deviation is zero

## Warning in cor(xvalue, yvalue, use = "pairwise.complete.obs", method =
## corMethod): the standard deviation is zero

## Warning in cor(xvalue, yvalue, use = "pairwise.complete.obs", method =
## corMethod): the standard deviation is zero

## Warning in cor(xvalue, yvalue, use = "pairwise.complete.obs", method =
## corMethod): the standard deviation is zero

## Warning in cor(xvalue, yvalue, use = "pairwise.complete.obs", method =
## corMethod): the standard deviation is zero

## Warning in cor(xvalue, yvalue, use = "pairwise.complete.obs", method =
## corMethod): the standard deviation is zero

## Warning in cor(xvalue, yvalue, use = "pairwise.complete.obs", method =
## corMethod): the standard deviation is zero

## Warning in cor(xvalue, yvalue, use = "pairwise.complete.obs", method =
## corMethod): the standard deviation is zero

## Warning in cor(xvalue, yvalue, use = "pairwise.complete.obs", method =
## corMethod): the standard deviation is zero

## Warning in cor(xvalue, yvalue, use = "pairwise.complete.obs", method =
## corMethod): the standard deviation is zero

## Warning in cor(xvalue, yvalue, use = "pairwise.complete.obs", method =
## corMethod): the standard deviation is zero
## Warning in ggscatmat(Boston_tb_f, color = "crim_gp"): Factor variables are
## omitted in plot

Will give NA when use color since the crim01 and factors are 1-1 correspondence. Remember it calculates correlation by factor

train <- 1:(length(Boston_tb$crim)/2)
test <- (length(Boston_tb$crim)/2 + 1):length(Boston_tb$crim)

Boston_train <- Boston_tb[train,]
Boston_test <- Boston_tb[test,]

glm_crim <- glm(crim01 ~ . -crim, 
                data = Boston_tb,
                family = binomial,
                subset = train)
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
summary(glm_crim)
## 
## Call:
## glm(formula = crim01 ~ . - crim, family = binomial, data = Boston_tb, 
##     subset = train)
## 
## Deviance Residuals: 
##      Min        1Q    Median        3Q       Max  
## -2.83229  -0.06593   0.00000   0.06181   2.61513  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -91.319906  19.490273  -4.685 2.79e-06 ***
## zn           -0.815573   0.193373  -4.218 2.47e-05 ***
## indus         0.354172   0.173862   2.037  0.04164 *  
## chas          0.167396   0.991922   0.169  0.86599    
## nox          93.706326  21.202008   4.420 9.88e-06 ***
## rm           -4.719108   1.788765  -2.638  0.00833 ** 
## age           0.048634   0.024199   2.010  0.04446 *  
## dis           4.301493   0.979996   4.389 1.14e-05 ***
## rad           3.039983   0.719592   4.225 2.39e-05 ***
## tax          -0.006546   0.007855  -0.833  0.40461    
## ptratio       1.430877   0.359572   3.979 6.91e-05 ***
## black        -0.017552   0.006734  -2.606  0.00915 ** 
## lstat         0.190439   0.086722   2.196  0.02809 *  
## medv          0.598533   0.185514   3.226  0.00125 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 329.367  on 252  degrees of freedom
## Residual deviance:  69.568  on 239  degrees of freedom
## AIC: 97.568
## 
## Number of Fisher Scoring iterations: 10
# note that chas and tax have no significance

crim_probs <- predict(glm_crim, Boston_test, type = "response")
crim_pred <- rep(0, length(test))
crim_pred[crim_probs > .5] <- 1 

table(crim_pred, Boston_test$crim01)
##          
## crim_pred   0   1
##         0  68  24
##         1  22 139
mean(crim_pred == Boston_test$crim01)
## [1] 0.8181818
1 - mean(crim_pred == Boston_test$crim01) # test error
## [1] 0.1818182
glm2_crim <- glm(crim01 ~ . -crim - chas - tax, 
                 data = Boston_tb,
                 family = binomial,
                 subset = train)
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
summary(glm2_crim)
## 
## Call:
## glm(formula = crim01 ~ . - crim - chas - tax, family = binomial, 
##     data = Boston_tb, subset = train)
## 
## Deviance Residuals: 
##      Min        1Q    Median        3Q       Max  
## -3.07309  -0.06280   0.00000   0.04518   2.52250  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -95.004862  20.048738  -4.739 2.15e-06 ***
## zn           -0.850179   0.184521  -4.607 4.08e-06 ***
## indus         0.413284   0.157156   2.630 0.008544 ** 
## nox          89.142048  19.552114   4.559 5.13e-06 ***
## rm           -4.631311   1.678561  -2.759 0.005796 ** 
## age           0.050660   0.023105   2.193 0.028337 *  
## dis           4.513311   0.954809   4.727 2.28e-06 ***
## rad           2.968052   0.677653   4.380 1.19e-05 ***
## ptratio       1.483118   0.369531   4.014 5.98e-05 ***
## black        -0.016615   0.006504  -2.554 0.010636 *  
## lstat         0.209340   0.086666   2.415 0.015714 *  
## medv          0.631766   0.183235   3.448 0.000565 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 329.367  on 252  degrees of freedom
## Residual deviance:  70.529  on 241  degrees of freedom
## AIC: 94.529
## 
## Number of Fisher Scoring iterations: 10
crim2_probs <- predict(glm2_crim, Boston_test, type = "response")
crim2_pred <- rep(0, length(test))
crim2_pred[crim2_probs > .5] <- 1 

table(crim2_pred, Boston_test$crim01)
##           
## crim2_pred   0   1
##          0  67  24
##          1  23 139
mean(crim2_pred == Boston_test$crim01)
## [1] 0.8142292
1 - mean(crim2_pred == Boston_test$crim01) # test error
## [1] 0.1857708

This wouldbe for the Logistic regression

lda_crim <- lda(crim01 ~ . -crim, data = Boston_tb, subset = train)
lda_crim_preds <- predict(lda_crim, Boston_test)
table(lda_crim_preds$class, Boston_test$crim01)
##    
##       0   1
##   0  80  24
##   1  10 139
mean(lda_crim_preds$class == Boston_test$crim01)
## [1] 0.8656126
1 - mean(lda_crim_preds$class == Boston_test$crim01) # test error
## [1] 0.1343874
lda2_crim <- lda(crim01 ~ . -crim - chas - tax, 
                 data = Boston_tb, 
                 subset = train)
lda2_crim_preds <- predict(lda2_crim, Boston_test)
table(lda2_crim_preds$class, Boston_test$crim01)
##    
##       0   1
##   0  80  21
##   1  10 142
mean(lda2_crim_preds$class == Boston_test$crim01)
## [1] 0.8774704
1 - mean(lda2_crim_preds$class == Boston_test$crim01) # test error
## [1] 0.1225296
attach(Boston_tb)
train_xb <- cbind(zn, indus, chas, nox, rm, age, dis, rad, tax, ptratio,
                  black, lstat, medv)[train,]
test_xb <- cbind(zn, indus, chas, nox, rm, age, dis, rad, tax, ptratio,
                 black, lstat, medv)[test,]  

train_crim01 <- crim01[train]

set.seed(1)
knn_pred_bos <- knn(train_xb, test_xb, train_crim01, k = 1)
table(knn_pred_bos, Boston_test$crim01)
##             
## knn_pred_bos   0   1
##            0  85 111
##            1   5  52
1 - mean(knn_pred_bos == Boston_test$crim01) # test error k =1
## [1] 0.458498
knn10_pred_bos <- knn(train_xb, test_xb, train_crim01, k = 10)
table(knn10_pred_bos, Boston_test$crim01)
##               
## knn10_pred_bos   0   1
##              0  83  23
##              1   7 140
1 - mean(knn10_pred_bos == Boston_test$crim01) 
## [1] 0.1185771
knn_pred_bos <- knn(train_xb, test_xb, train_crim01, k = 1)
table(knn_pred_bos, Boston_test$crim01)
##             
## knn_pred_bos   0   1
##            0  85 111
##            1   5  52
1 - mean(knn_pred_bos == Boston_test$crim01) # test error k =1
## [1] 0.458498
knn100_pred_bos <- knn(train_xb, test_xb, train_crim01, k = 100)
table(knn100_pred_bos, Boston_test$crim01)
##                
## knn100_pred_bos   0   1
##               0  86 120
##               1   4  43
1 - mean(knn100_pred_bos == Boston_test$crim01) 
## [1] 0.4901186

This is for LDA