setup_KNN() fits weighted k-nearest-neighbor models with the kknn package (Hechenbichler and Schliep 2004). This chapter examines the effect of \(k\) and of feature scaling, and tunes \(k\) by nested resampling.
k is the number of neighbors; kernel the function that weights neighbors by distance, with "optimal" the kernel derived by Hechenbichler and Schliep (2004) and "rectangular" the unweighted average; distance the parameter \(q\) of the Minkowski distance, 2 for Euclidean; and scale = TRUE standardizes the features before computing distances. Factors are one-hot encoded internally.
draw_line(k_values,list(Training =knn_db[["rsq_training"]], Test =knn_db[["rsq_test"]]), xlab ="k (number of neighbors)", ylab ="R-squared")
With \(k = 1\) the training \(R^2\) is 1, since each training case is its own nearest neighbor, and the test \(R^2\) is below 0. As \(k\) grows, training \(R^2\) falls and test \(R^2\) rises, then levels off: the bias–variance tradeoff of Section 24.3, with flexibility decreasing from left to right.
For the heart failure data, the AUC and Brier score of the predicted probabilities:
With 49 deaths in each training set, small neighborhoods contain few deaths, and the estimated probabilities are coarse; performance improves up to the largest \(k\) examined.
25.2 Feature scaling
The diabetes features have different scales: age in years, BMI in kg/m², the serum measurements in their own units. Without standardization:
Without scaling, the distance is dominated by the features with the largest standard deviations, s1 (34.6) and s2 (30.4), while s5, one of the most predictive features (Section 15.1), has a standard deviation of 0.52 and contributes almost nothing.
The tuned kNN model has a mean test \(R^2\) of 0.456, below the 0.493 of the linear model. The result is consistent with the additive models of Section 23.1, in which most features have linear or nearly linear effects: a global model with ten coefficients estimates such a dependence with less variance than averages over local neighborhoods in ten dimensions.
Hechenbichler, Klaus, and Klaus Schliep. 2004. Weighted k-Nearest-Neighbor Techniques and Ordinal Classification. Discussion Paper No. 399. Ludwig-Maximilians-Universität München, Sonderforschungsbereich 386.