Certainly! Below is an R function that implements the K-Nearest Neighbors (K-NN) running-mean smoother specifically tailored for two-class classification problems with a single predictor variable.
Function Overview
- Function Name:
knn_smoother
- Parameters:
x: Numeric vector of predictor values from the training data.
y: Binary response vector from the training data (e.g., 0 and 1).
k: Number of nearest neighbors to consider.
newx: (Optional) Numeric vector of new predictor values where predictions are desired. If not provided, the function will predict for the training data points.
- Returns: A numeric vector containing the smoothed values ( S(x) ), which are the averages of the response values of the ( k )-nearest neighbors for each corresponding
newx.
Function Implementation
knn_smoother <- function(x, y, k, newx = x) {
# Check inputs
if(length(x) != length(y)) {
stop("Length of x and y must be the same.")
}
if(!all(y %in% c(0, 1))) {
stop("All elements of y must be either 0 or 1.")
}
if(k <= 0 || k > length(x)) {
stop("k must be a positive integer less than or equal to the number of data points.")
}
# Initialize vector to store smoothed values
smoothed <- numeric(length(newx))
# For each point in newx, find k nearest neighbors and compute average y
for(i in seq_along(newx)) {
# Compute absolute distances
distances <- abs(x - newx[i])
# Get indices of k smallest distances
neighbor_indices <- order(distances)[1:k]
# Compute average of y in the neighborhood
smoothed[i] <- mean(y[neighbor_indices])
}
return(smoothed)
}
Example Usage
Let's demonstrate how to use the knn_smoother function with a simple example.
# Sample training data
set.seed(123) # For reproducibility
x_train <- sort(runif(20, 0, 10)) # Predictor values from 0 to 10
y_train <- rbinom(20, 1, prob = 0.5) # Binary responses (0 or 1)
# Display training data
data <- data.frame(x = x_train, y = y_train)
print(data)
# Define new points where we want to predict S(x)
x_new <- seq(0, 10, length.out = 100)
# Choose number of neighbors
k <- 5
# Perform K-NN smoothing
smoothed_values <- knn_smoother(x = x_train, y = y_train, k = k, newx = x_new)
# Plot the results
plot(x_train, y_train, pch = 19, col = "blue", xlab = "X", ylab = "S(x)", main = "K-NN Running Mean Smoother")
lines(x_new, smoothed_values, col = "red", lwd = 2)
legend("topright", legend = c("Training Data", paste(k, "NN Smoother")),
col = c("blue", "red"), pch = c(19, NA), lty = c(NA, 1), lwd = c(NA, 2))
Explanation of the Example
-
Data Generation:
- We generate 20 training data points (
x_train) uniformly distributed between 0 and 10.
- The corresponding binary responses (
y_train) are generated randomly with equal probability for 0 and 1.
-
Prediction Points:
x_new consists of 100 points evenly spaced between 0 and 10 where we want to estimate ( S(x) ).
-
K-NN Smoothing:
- We set ( k = 5 ) to consider the 5 nearest neighbors for each prediction.
- The
knn_smoother function calculates the average of the y_train values of these neighbors for each x_new.
-
Visualization:
- The training data points are plotted in blue.
- The smoothed values ( S(x) ) are plotted as a red line showing how the average response changes with
x.
Notes
-
Handling Ties: In cases where multiple points are equidistant, the order function in R will handle ties based on their order in the input vector.
-
Optimal ( k ): Choosing the right number of neighbors ( k ) is crucial. A smaller ( k ) can make the smoother sensitive to noise, while a larger ( k ) might oversmooth the data. It's often recommended to experiment with different ( k ) values or use cross-validation to select the optimal ( k ).
-
Efficiency Consideration: For very large datasets, this implementation might be slow since it uses a for-loop. In such cases, vectorized operations or optimized packages like FNN or kknn can be considered.
Conclusion
The knn_smoother function provided above offers a simple and customizable way to apply K-Nearest Neighbors smoothing to two-class classification problems with a single predictor. By adjusting the number of neighbors ( k ), you can control the smoothness of the resulting estimator to best fit your data.