Sub topic 2
Choosing k: Bias Versus Variance
This chapter assumes you know features, labels, train/test sets, vectors, and Euclidean distance.
Choosing k
In k-nearest neighbours (k-NN), k is the number of nearby training examples used for a prediction. A small k follows local details closely. A large k averages over a wider region.
This creates a bias–variance trade-off:
- Small
khas low bias but high variance. Predictions can change sharply because of one noisy example. - Large
khas higher bias but lower variance. Predictions are smoother but may ignore useful local structure.
| Choice | Typical effect |
|---|---|
| Small k | Flexible boundary, sensitive to noise |
| Large k | Smooth boundary, may underfit |
Choose k with validation data rather than selecting it from the test set. Cross-validation evaluates candidate values on several training folds.
from sklearn.datasets import load_iris
from sklearn.model_selection import GridSearchCV
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
model = make_pipeline(StandardScaler(), KNeighborsClassifier())
search = GridSearchCV(
model,
{
"kneighborsclassifier__n_neighbors": [1, 3, 5, 9, 15],
"kneighborsclassifier__weights": ["uniform", "distance"],
},
cv=5,
)
search.fit(X, y)
print(search.best_params_)Why feature scaling matters
Distance calculations compare changes in feature values. A feature measured in thousands can dominate a feature measured between zero and one, even when the smaller-scale feature is more useful.
Standardization rescales each feature using its training-fold mean and standard deviation. Put the scaler inside a pipeline. This makes each cross-validation fold learn scaling only from its own training portion.
Giving closer neighbours more weight
Uniform voting gives every selected neighbour equal influence. Distance-weighted voting gives closer examples more influence, often using a weight such as 1 divided by distance. This can help when class boundaries are gradual or when a relatively large k is needed for stability.
caption: How k and voting weights affect a prediction
alt: A query point uses nearby labelled examples; closer examples receive stronger influence when weighted voting is enabled.
flowchart TD
A[Query point] --> B[Find k nearest examples]
B --> C{Voting rule}
C --> D[Uniform: equal votes]
C --> E[Distance weighted: closer votes count more]
D --> F[Predicted class]
E --> FWeighted voting does not fix poor scaling. Distances must represent meaningful similarity first.
Exercise
Why can increasing k reduce variance but increase bias?
Show answer
More neighbours make predictions less sensitive to individual noisy examples, reducing variance, but averaging across a wider region can hide local patterns, increasing bias.