Introduction
In part (b) of the problem, we aim to evaluate the performance of the K-Nearest Neighbors (K-NN) classifier compared to the Least Squares (LS) method in a two-class classification setting. We'll use leave-one-out cross-validation (LOOCV) to estimate prediction errors under two different parameter configurations:
-
Scenario 1:
- Means: ((\mu_1, \mu_2) = (1, 2.5))
- Variances: (\sigma_1^2 = \sigma_2^2 = 1)
- Neighbors: (K = 5, 10, 15)
-
Scenario 2:
- Means: ((\mu_1, \mu_2) = (1, 4))
- Variances: (\sigma_1^2 = \sigma_2^2 = 1)
- Neighbors: (K = 5, 10, 15)
We'll generate 100 observations for each class in both scenarios, apply LOOCV, compute prediction errors for LS and K-NN (with varying (K)), and analyze the results.
Step-by-Step Implementation
1. Data Generation
For each scenario, we'll generate data for two classes:
- Class 0: (Y = 1), (X \sim N(\mu_1, 1))
- Class 1: (Y = 0), (X \sim N(\mu_2, 1))
2. Custom K-NN Function
Assuming you have implemented a K-NN function from part (a), let's name it my_knn. This function takes training features, training labels, a test point, and (K) as input and returns the predicted value based on the average of the responses of the (K) nearest neighbors.
# Example structure of the custom K-NN function from part (a)
my_knn <- function(train_X, train_Y, test_X, K) {
# Calculate distances
distances <- abs(train_X - test_X)
# Identify indices of K nearest neighbors
nn_indices <- order(distances)[1:K]
# Compute the average Y value of the neighbors
S_xi <- mean(train_Y[nn_indices])
return(S_xi)
}
3. Leave-One-Out Cross-Validation (LOOCV)
We'll perform LOOCV for each observation in the dataset:
-
Iterate through each observation:
- Training Set: All observations except the current one.
- Test Set: The current observation.
-
Apply LS Classification:
- Fit a linear regression model: (Y \sim X) using the training set.
- Predict (\hat{Y}) for the test observation.
- Classify as class 1 if (\hat{Y} \geq 0.5), else class 0.
-
Apply K-NN Classification:
- Use the custom
my_knn function with the specified (K).
- Compute (S(x_i)), the average (Y) of the (K) nearest neighbors.
- Classify as class 1 if (S(x_i) \geq 0.5), else class 0.
-
Record Prediction Errors:
- Compare predicted classes with actual classes.
- Calculate the proportion of misclassifications.
4. R Implementation
Below is the R code that encapsulates the above steps. This code assumes that the my_knn function has been correctly implemented in part (a).
# Set seed for reproducibility
set.seed(123)
# Number of observations per class
n <- 100
# Define scenarios
scenarios <- list(
list(mu1 = 1, mu2 = 2.5),
list(mu1 = 1, mu2 = 4)
)
# Define K values
K_values <- c(5, 10, 15)
# Initialize a list to store results
results <- list()
# Loop over each scenario
for (s in 1:length(scenarios)) {
params <- scenarios[[s]]
mu1 <- params$mu1
mu2 <- params$mu2
# Generate data for Class 0
X0 <- rnorm(n, mean = mu1, sd = 1)
Y0 <- rep(1, n)
# Generate data for Class 1
X1 <- rnorm(n, mean = mu2, sd = 1)
Y1 <- rep(0, n)
# Combine data
X <- c(X0, X1)
Y <- c(Y0, Y1)
# Total number of observations
N <- length(Y)
# Initialize vectors/matrices to store predictions
pred_LS <- rep(0, N)
pred_KNN <- matrix(0, nrow = N, ncol = length(K_values))
# Perform LOOCV
for (i in 1:N) {
# Define test and training sets
X_test <- X[i]
Y_true <- Y[i]
X_train <- X[-i]
Y_train <- Y[-i]
# Least Squares Classifier
model_ls <- lm(Y_train ~ X_train)
Y_hat_ls <- predict(model_ls, newdata = data.frame(X_train = X_test))
pred_LS[i] <- ifelse(Y_hat_ls >= 0.5, 1, 0)
# K-NN Classifier for each K
for (k in 1:length(K_values)) {
K <- K_values[k]
S_xi <- my_knn(X_train, Y_train, X_test, K)
pred_KNN[i, k] <- ifelse(S_xi >= 0.5, 1, 0)
}
}
# Calculate error rates
error_LS <- mean(pred_LS != Y)
error_KNN <- apply(pred_KNN, 2, function(pred) mean(pred != Y))
# Store the results
results[[s]] <- list(
scenario = paste0("Scenario ", s, ": (mu1 = ", mu1, ", mu2 = ", mu2, ")"),
error_LS = error_LS,
error_KNN = error_KNN
)
}
# Display the results
for (s in 1:length(results)) {
cat(results[[s]]$scenario, "\n")
cat("Least Squares Error Rate:", round(results[[s]]$error_LS * 100, 2), "%\n")
for (k in 1:length(K_values)) {
cat("K-NN (K =", K_values[k], ") Error Rate:",
round(results[[s]]$error_KNN[k] * 100, 2), "%\n")
}
cat("\n")
}
5. Sample Output and Analysis
Note: The following results are hypothetical and for illustrative purposes only. Actual results may vary based on the random seed and specific implementation of my_knn.
Scenario 1: (mu1 = 1, mu2 = 2.5)
Least Squares Error Rate: 22.00%
K-NN (K = 5 ) Error Rate: 18.50%
K-NN (K = 10 ) Error Rate: 20.00%
K-NN (K = 15 ) Error Rate: 21.00%
Scenario 2: (mu1 = 1, mu2 = 4)
Least Squares Error Rate: 10.00%
K-NN (K = 5 ) Error Rate: 12.50%
K-NN (K = 10 ) Error Rate: 11.00%
K-NN (K = 15 ) Error Rate: 10.50%
6. Interpretation of Results
Scenario 1: ((\mu_1 = 1), (\mu_2 = 2.5))
-
Class Overlap: Moderate. The classes are closer together, leading to more overlap.
-
Least Squares (LS): Error rate of 22% suggests that LS may not effectively capture the boundary between overlapping classes.
-
K-NN Performance:
- K = 5: Lowest error rate at 18.5%. Smaller (K) values allow the classifier to capture local patterns, which is beneficial in overlapping scenarios.
- K = 10 & 15: Error rates increase, approaching LS performance. Larger (K) values smooth out the decision boundary, potentially misclassifying boundary points.
Scenario 2: ((\mu_1 = 1), (\mu_2 = 4))
-
Class Overlap: Minimal. The classes are well-separated, reducing overlap.
-
Least Squares (LS): Lower error rate of 10% indicates better performance when classes are distinct.
-
K-NN Performance:
- K = 5: Slightly higher error at 12.5%, possibly due to sensitivity to outliers.
- K = 10 & 15: Error rates decrease, aligning more closely with LS. Larger (K) values are advantageous in well-separated classes as they reinforce the clear boundaries.
Overall Comparison:
-
Least Squares vs. K-NN:
- LS performs consistently, especially when classes are well-separated. However, in scenarios with overlapping classes, LS may struggle to capture the nuanced boundary, leading to higher error rates.
- K-NN shows flexibility:
- Smaller (K): Better at handling overlapping classes by capturing local variations but may suffer from higher variance.
- Larger (K): More stable and aligns with LS in well-separated scenarios but may lose local detail in overlapping scenarios.
-
Effect of (K) in K-NN:
- Smaller (K) (e.g., (K=5)): Captures fine-grained local structures, beneficial in complex or overlapping data distributions. However, it might be more sensitive to noise.
- Larger (K) (e.g., (K=15)): Provides smoother decision boundaries, reducing variance but potentially increasing bias, especially harmful in overlapping scenarios.
-
Choice of (K):
- Depends on Data Structure:
- Overlapping Classes: Smaller (K) is preferable to capture local nuances.
- Well-Separated Classes: Larger (K) aligns well with clear boundaries and can mirror LS performance.
Conclusion
The comparative analysis between Least Squares and K-Nearest Neighbors classifiers under different scenarios highlights the strengths and limitations of each method:
-
Least Squares (LS): Offers simplicity and consistent performance, particularly effective when classes are well-separated. However, it may not perform optimally in complex or overlapping scenarios due to its linear nature.
-
K-Nearest Neighbors (K-NN): Provides adaptability based on the choice of (K). It excels in capturing local patterns and handling overlapping classes when (K) is small. As (K) increases, K-NN becomes more robust in well-separated settings, aligning its performance with LS.
Selecting the appropriate classifier and optimal (K) value depends on the underlying data distribution and the specific requirements of the classification task.