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?

library(ISLR)
## Warning: package 'ISLR' was built under R version 4.4.3
names(Weekly)
## [1] "Year"      "Lag1"      "Lag2"      "Lag3"      "Lag4"      "Lag5"     
## [7] "Volume"    "Today"     "Direction"
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

The only significant pattern appears to be a positive correlation between volume and year

attach(Weekly)
plot(Volume)

**From the above plot it’s clear that the average number of weekly traded shares increases over time from 1990 to 2010

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

#Logistic Regression Model
glm.fit= glm(Direction~Lag1+Lag2+Lag3+Lag4+Lag5+Volume,data=Weekly,family=binomial)
summary(glm.fit)
## 
## Call:
## glm(formula = Direction ~ Lag1 + Lag2 + Lag3 + Lag4 + Lag5 + 
##     Volume, 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
coef(glm.fit)
## (Intercept)        Lag1        Lag2        Lag3        Lag4        Lag5 
##  0.26686414 -0.04126894  0.05844168 -0.01606114 -0.02779021 -0.01447206 
##      Volume 
## -0.02274153
#summary(glm.fit)$coef[, 4]
summary(glm.fit)$coef
##                Estimate Std. Error    z value    Pr(>|z|)
## (Intercept)  0.26686414 0.08592961  3.1056134 0.001898848
## Lag1        -0.04126894 0.02641026 -1.5626099 0.118144368
## Lag2         0.05844168 0.02686499  2.1753839 0.029601361
## Lag3        -0.01606114 0.02666299 -0.6023760 0.546923890
## Lag4        -0.02779021 0.02646332 -1.0501409 0.293653342
## Lag5        -0.01447206 0.02638478 -0.5485006 0.583348244
## Volume      -0.02274153 0.03689812 -0.6163330 0.537674762

From the above output, it is clear that there is only one significant predictor. Lag 2 has a positive significant relationship with direction, with a coefficient of 0.0584 and a p-value of 0.0296, which is less than the significance level of 0.05. This indicates that if the market had a positive return two days ago, it is more likely to have a positive return today.

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

set.seed(123)
glm.probs=predict(glm.fit,type='response')
#glm.probs
contrasts(Direction)
##      Up
## Down  0
## Up    1
# Confusion matrix
# Convert probabilities to class labels using 0.5 threshold
glm.pred <- ifelse(glm.probs > 0.5, "Up", "Down")
#Create confusion matrix
table(glm.pred, Direction)
##         Direction
## glm.pred Down  Up
##     Down   54  48
##     Up    430 557
#Overall fraction of correct predictions
(54+557) /1089
## [1] 0.5610652
mean(glm.pred==Direction )
## [1] 0.5610652

logistic regression correctly predicted the movement of the market 56.11 % of the time.
logistic regression here is biased toward predicting “Up” and struggles with identifying “Down” days

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

#Create training indicator
train = (Year < 2009)

#Define test set (2009–2010)
Weekly.test = Weekly[!train, ]
Direction.test = Direction[!train]

#Fit logistic regression with Lag2 as predictor on training set
glm.fit = glm(Direction ~ Lag2, data = Weekly, family = binomial, subset = train)

#Predict on test set
glm.probs = predict(glm.fit, Weekly.test, type = "response")

#Initialize predictions to "Down"
glm.pred = rep("Down", nrow(Weekly.test))

#Assign "Up" to probabilities > 0.5
glm.pred[glm.probs > 0.5] = "Up"

#Confusion matrix
table(glm.pred, Direction.test)
##         Direction.test
## glm.pred Down Up
##     Down    9  5
##     Up     34 56
#Overall fraction of correct predictions
mean(glm.pred == Direction.test)
## [1] 0.625

(e) Repeat (d) using LDA

# Load MASS package for LDA
library(MASS)

#Training indicator
train = (Year < 2009)

#Define test data (2009–2010)
Weekly_test_lda = Weekly[!train, ]
Direction_test_lda = Direction[!train]

#Fit LDA model using Lag2
lda.fit = lda(Direction ~ Lag2, data = Weekly, subset = train)

#Predict on test data
lda.pred = predict(lda.fit, Weekly_test_lda)

#Confusion matrix
table(lda.pred$class, Direction_test_lda)
##       Direction_test_lda
##        Down Up
##   Down    9  5
##   Up     34 56
#Overall fraction of correct predictions
mean(lda.pred$class == Direction_test_lda)
## [1] 0.625

(f) Repeat (d) using QDA.

set.seed(123)
#Training indicator
train = (Year < 2009)

#Define test data (2009–2010)
Weekly_test_qda = Weekly[!train, ]
Direction_test_qda = Direction[!train]

#Fit QDA model using Lag2
qda.fit = qda(Direction ~ Lag2, data = Weekly, subset = train)

#Predict on test data
qda.pred = predict(qda.fit, Weekly_test_qda)

#Confusion matrix
table(qda.pred$class, Direction_test_qda)
##       Direction_test_qda
##        Down Up
##   Down    0  0
##   Up     43 61
#Overall fraction of correct predictions
mean(qda.pred$class == Direction_test_qda)
## [1] 0.5865385
# Load the required package
library(class)

#Define training and test sets
train = (Year < 2009)

#Create the predictor and response variables
train.X = as.matrix(Lag2[train])     # Training predictor
test.X = as.matrix(Lag2[!train])     # Test predictor
train.Direction = Direction[train]   # Training response
test.Direction = Direction[!train]   # Test response

#Run KNN with k = 1
set.seed(1)  # For reproducibility
knn.pred = knn(train.X, test.X, train.Direction, k = 1)

#Confusion matrix
table(knn.pred, test.Direction)
##         test.Direction
## knn.pred Down Up
##     Down   21 30
##     Up     22 31
#Accuracy
mean(knn.pred == test.Direction)
## [1] 0.5

(h) Repeat (d) using naive Bayes.

#Load the e1071 package
library(e1071)

#Define the training and test sets
train = (Year < 2009)

#Fit the Naive Bayes model using Lag2 as the only predictor
nb.fit = naiveBayes(Direction ~ Lag2, data = Weekly, subset = train)

#Create test set
Weekly.test = Weekly[!train, ]
Direction.test = Direction[!train]

#Predict on test set
nb.pred = predict(nb.fit, Weekly.test)

#Confusion matrix
table(nb.pred, Direction.test)
##        Direction.test
## nb.pred Down Up
##    Down    0  0
##    Up     43 61
#Overall Fraction of correct predictions
mean(nb.pred == Direction.test)
## [1] 0.5865385

(i) Which of these methods appears to provide the best results on this data?
In terms of the Overall fraction of correct predictions the Logistic Regression and LDA appear to provide the best results for predicting stock market direction in the 2009–2010 test data, when using Lag2 as the only predictor.logistic regression and linear discriminant model provide the best results with the highest correct prediction fraction of 0.625
(j) 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.

library(ISLR)
library(MASS)
library(class)
library(e1071)

# Set training and test sets
train = (Weekly$Year < 2009)
Weekly.train = Weekly[train, ]
Weekly.test = Weekly[!train, ]
Direction.test = Weekly$Direction[!train]

#Logistic Regression with Lag2 and Lag1:Lag2 interaction
glm.fit = glm(Direction ~ Lag2 + I(Lag1*Lag2), data=Weekly.train, family=binomial)
glm.probs = predict(glm.fit, Weekly.test, type="response")
glm.pred = ifelse(glm.probs > 0.5, "Up", "Down")
glm.table = table(glm.pred, Direction.test)
glm.acc = mean(glm.pred == Direction.test)


#LDA with Lag1 and Lag2
lda.fit = lda(Direction ~ Lag1 + Lag2, data=Weekly.train)
lda.pred = predict(lda.fit, Weekly.test)$class
lda.table = table(lda.pred, Direction.test)
lda.acc = mean(lda.pred == Direction.test)


#QDA with Lag2 only
qda.fit = qda(Direction ~ Lag2, data=Weekly.train)
qda.pred = predict(qda.fit, Weekly.test)$class
qda.table = table(qda.pred, Direction.test)
qda.acc = mean(qda.pred == Direction.test)

#Naive Bayes with Lag2 + Volume
nb.fit = naiveBayes(Direction ~ Lag2 + Volume, data=Weekly.train)
nb.pred = predict(nb.fit, Weekly.test)
nb.table = table(nb.pred, Direction.test)
nb.acc = mean(nb.pred == Direction.test)


#KNN, using K = 1, 3, 5, 10
train.X = as.matrix(Weekly.train[, c("Lag2")])
test.X = as.matrix(Weekly.test[, c("Lag2")])
train.Direction = Weekly.train$Direction

knn.results = list()
for (k in c(1, 3, 5, 10)) {
  set.seed(1)
  knn.pred = knn(train.X, test.X, train.Direction, k = k)
  acc = mean(knn.pred == Direction.test)
  tbl = table(knn.pred, Direction.test)
  knn.results[[paste0("K=", k)]] = list("table"=tbl, "acc"=acc)
}


# Print All Results
cat("Logistic Regression:\n")
## Logistic Regression:
print(glm.table)
##         Direction.test
## glm.pred Down Up
##     Down    3  3
##     Up     40 58
cat("Accuracy:", glm.acc, "\n\n")
## Accuracy: 0.5865385
cat("LDA:\n")
## LDA:
print(lda.table)
##         Direction.test
## lda.pred Down Up
##     Down    7  8
##     Up     36 53
cat("Accuracy:", lda.acc, "\n\n")
## Accuracy: 0.5769231
cat("QDA:\n")
## QDA:
print(qda.table)
##         Direction.test
## qda.pred Down Up
##     Down    0  0
##     Up     43 61
cat("Accuracy:", qda.acc, "\n\n")
## Accuracy: 0.5865385
cat("Naive Bayes:\n")
## Naive Bayes:
print(nb.table)
##        Direction.test
## nb.pred Down Up
##    Down   43 57
##    Up      0  4
cat("Accuracy:", nb.acc, "\n\n")
## Accuracy: 0.4519231
cat("KNN Results:\n")
## KNN Results:
for (kname in names(knn.results)) {
  cat(kname, "\n")
  print(knn.results[[kname]]$table)
  cat("Accuracy:", knn.results[[kname]]$acc, "\n\n")
}
## K=1 
##         Direction.test
## knn.pred Down Up
##     Down   21 30
##     Up     22 31
## Accuracy: 0.5 
## 
## K=3 
##         Direction.test
## knn.pred Down Up
##     Down   16 20
##     Up     27 41
## Accuracy: 0.5480769 
## 
## K=5 
##         Direction.test
## knn.pred Down Up
##     Down   16 21
##     Up     27 40
## Accuracy: 0.5384615 
## 
## K=10 
##         Direction.test
## knn.pred Down Up
##     Down   17 21
##     Up     26 40
## Accuracy: 0.5480769

14. 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.

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

# Load necessary package
library(ISLR)

# Load the Auto dataset
data("Auto")

# Remove rows with missing values
Auto = na.omit(Auto)

# Create binary variable mpg01
mpg01 = ifelse(Auto$mpg > median(Auto$mpg), 1, 0)

# Combine with original data
Auto = data.frame(Auto, mpg01)

# View the structure
str(Auto)
## 'data.frame':    392 obs. of  10 variables:
##  $ mpg         : num  18 15 18 16 17 15 14 14 14 15 ...
##  $ cylinders   : num  8 8 8 8 8 8 8 8 8 8 ...
##  $ displacement: num  307 350 318 304 302 429 454 440 455 390 ...
##  $ horsepower  : num  130 165 150 150 140 198 220 215 225 190 ...
##  $ weight      : num  3504 3693 3436 3433 3449 ...
##  $ acceleration: num  12 11.5 11 12 10.5 10 9 8.5 10 8.5 ...
##  $ year        : num  70 70 70 70 70 70 70 70 70 70 ...
##  $ origin      : num  1 1 1 1 1 1 1 1 1 1 ...
##  $ name        : Factor w/ 304 levels "amc ambassador brougham",..: 49 36 231 14 161 141 54 223 241 2 ...
##  $ mpg01       : num  0 0 0 0 0 0 0 0 0 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.

# Graphical investigation of mpg01 and other variables
pairs(Auto[, -9])

cor(Auto[, -9])
##                     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
corrplot::corrplot.mixed(cor(Auto[, -9]), upper="circle")

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

From the boxplots, it appears that weight and horsepower are the most likely to be useful in predicting mpg01. Higher weight and horsepower seem to be associated with lower gas mileage.

Most useful (strong negative correlations): cylinders, displacement, horsepower, weight
mpg itself is obviously very strongly positively correlated (since mpg01 is derived from mpg), but it’s not a predictor since mpg is the outcome variable.

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

library(caTools)
set.seed(123)
split <- sample.split(Auto$mpg01, SplitRatio = 0.7)
train <- subset(Auto, split == TRUE)
test <- subset(Auto, split == FALSE)

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

# Load the MASS package
library(MASS)
set.seed(123)

# Fit LDA model
lda_model <- lda(mpg01 ~ weight + horsepower, data = train)
summary(lda_model)
##         Length Class  Mode     
## prior   2      -none- numeric  
## counts  2      -none- numeric  
## means   4      -none- numeric  
## scaling 2      -none- numeric  
## lev     2      -none- character
## svd     1      -none- numeric  
## N       1      -none- numeric  
## call    3      -none- call     
## terms   3      terms  call     
## xlevels 0      -none- list
# Predict on test data
lda_pred <- predict(lda_model, newdata = test)

# Create confusion matrix
table(lda_pred$class, test$mpg01)
##    
##      0  1
##   0 49  6
##   1 10 53
# Test error
mean(lda_pred$class != test$mpg01)
## [1] 0.1355932

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

# Load the MASS package
library(MASS)
set.seed(123)
# Fit QDA model
qda_model <- qda(mpg01 ~ weight + horsepower, data = train)

# Predict on test data
qda_pred <- predict(qda_model, newdata = test)

# Create confusion matrix
table(qda_pred$class, test$mpg01)
##    
##      0  1
##   0 49  8
##   1 10 51
# Compute test error
mean(qda_pred$class != test$mpg01)
## [1] 0.1525424

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

set.seed(123)
# Fit logistic regression model
log_model <- glm(mpg01 ~ weight + horsepower, data = train, family = binomial)

# Predict probabilities on test set
log_probs <- predict(log_model, newdata = test, type = "response")

# Convert probabilities to class predictions (0 or 1)
log_pred <- ifelse(log_probs > 0.5, 1, 0)

# Confusion matrix
table(log_pred, test$mpg01)
##         
## log_pred  0  1
##        0 53  8
##        1  6 51
# Test error rate
mean(log_pred != test$mpg01)
## [1] 0.1186441

(g) Perform naive Bayes 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?

set.seed(123)
# Fit Naive Bayes model using selected predictors
nb_model <- naiveBayes(mpg01 ~ weight + horsepower, data = train)

# Predict on the test set
nb_pred <- predict(nb_model, newdata = test)

# Confusion matrix
conf_mat <- table(nb_pred, test$mpg01)
print(conf_mat)
##        
## nb_pred  0  1
##       0 50  5
##       1  9 54
# Test error rate
test_error <- mean(nb_pred != test$mpg01)
test_error
## [1] 0.1186441

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

library(class)
#the predictor features for train and test sets
train_features <- train[, c("weight", "horsepower")]
test_features <- test[, c("weight", "horsepower")]

# Vector of K values to try
k_values <- 1:20

# Pre-allocate vector for errors (better than growing inside loop)
knn_errors <- numeric(length(k_values))

# Loop over K values
for (i in seq_along(k_values)) {
  k <- k_values[i]
  knn_pred <- knn(train = train_features, test = test_features, cl = train$mpg01, k = k)
  knn_errors[i] <- mean(knn_pred != test$mpg01)
}

# Print test errors
print(knn_errors)
##  [1] 0.1440678 0.1440678 0.1271186 0.1271186 0.1440678 0.1525424 0.1355932
##  [8] 0.1440678 0.1355932 0.1271186 0.1271186 0.1186441 0.1271186 0.1186441
## [15] 0.1186441 0.1186441 0.1271186 0.1355932 0.1355932 0.1271186
# Best K with the smallest test error
best_k <- k_values[which.min(knn_errors)]
print(best_k)
## [1] 12

16. 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. Explore logistic regression, LDA, naive Bayes, and KNN models using various subsets of the predictors. Describe your findings. Hint: You will have to create the response variable yourself, using the variables that are contained in the Boston data set.

# Load libraries
library(MASS)
library(e1071)
library(class)
library(caTools)

#Load the Boston dataset
data("Boston")

#Create binary response variable crim01
median_crim <- median(Boston$crim)
Boston$crim01 <- ifelse(Boston$crim > median_crim, 1, 0)

#Train/Test split (70/30)
set.seed(123)
split <- sample.split(Boston$crim01, SplitRatio = 0.7)
train <- subset(Boston, split == TRUE)
test  <- subset(Boston, split == FALSE)

#Predictors I used
predictors <- c("lstat", "rm", "dis", "nox", "age")

#Training and test data
train_X <- train[, predictors]
test_X  <- test[, predictors]
train_Y <- train$crim01
test_Y  <- test$crim01

##Logistic Regression
log_model <- glm(crim01 ~ ., data = data.frame(train_X, crim01 = train_Y), family = binomial)
log_probs <- predict(log_model, newdata = test_X, type = "response")
log_pred <- ifelse(log_probs > 0.5, 1, 0)
log_error <- mean(log_pred != test_Y)

##LDA
lda_model <- lda(crim01 ~ ., data = data.frame(train_X, crim01 = train_Y))
lda_pred <- predict(lda_model, newdata = test_X)$class
lda_error <- mean(lda_pred != test_Y)

##Naive Bayes
nb_model <- naiveBayes(as.factor(crim01) ~ ., data = data.frame(train_X, crim01 = as.factor(train_Y)))
nb_pred <- predict(nb_model, newdata = test_X)
nb_error <- mean(nb_pred != test_Y)

##KNN for k = 1 to 20
#Scale features for KNN
train_X_scaled <- scale(train_X)
test_X_scaled  <- scale(test_X, center = attr(train_X_scaled, "scaled:center"),
                                 scale = attr(train_X_scaled, "scaled:scale"))

k_values <- 1:20
knn_errors <- numeric(length(k_values))
for (i in seq_along(k_values)) {
  k <- k_values[i]
  knn_pred <- knn(train = train_X_scaled, test = test_X_scaled, cl = train_Y, k = k)
  knn_errors[i] <- mean(knn_pred != test_Y)
}
best_k <- k_values[which.min(knn_errors)]

## Results
cat("Test Errors:\n")
## Test Errors:
cat("Logistic Regression:", round(log_error, 4), "\n")
## Logistic Regression: 0.1382
cat("LDA:", round(lda_error, 4), "\n")
## LDA: 0.1513
cat("Naive Bayes:", round(nb_error, 4), "\n")
## Naive Bayes: 0.1645
cat("KNN (best k =", best_k, "):", round(min(knn_errors), 4), "\n")
## KNN (best k = 9 ): 0.1184