DSCI 571 Lecture 3: \(k\)-nearest neighbours and SVM RBFs

Varada Kolhatkar

Focus on the breath!

Announcements

Recap: iClicker overfitting 1

Which scenarios, by themselves, do NOT provide sufficient evidence that a model is overfitting? Select all that apply.

    1. Training accuracy is 0.98, while validation accuracy is 0.60.
    1. A wildlife classifier learns that snow in the background is strongly associated with “wolf” in the training data. On validation images where wolves appear in a variety of backgrounds, its performance drops substantially.
    1. A classifier has a highly irregular decision boundary, but you are not given its training or validation performance.
    1. Training and validation accuracies are both approximately 0.88.
    1. A cancer-detection model learns that a ruler in the corner of an image is associated with positive cases. This association was present in the training data but not in validation data, where performance drops substantially.

Recap: iClicker overfitting 2

Which of the following statements about overfitting is true?

    1. Overfitting makes the model more accurate on both training and unseen data.
    1. Overfitting means the model captures noise or irrelevant details from the training data.
    1. Overfitting is desirable because it reduces both training and test error.
    1. Overfitting can be identified by looking at training performance alone.

Recap: iClicker underfitting

How might one address the issue of underfitting in a machine learning model.

    1. Introduce more noise to the training data.
    1. Remove features that might be relevant to the prediction.
    1. Increase the model’s complexity (e.g., more parameters, useful features, or deeper trees)
    1. Use a smaller dataset for training.

The fundamental tradeoff

  • As you increase the model complexity, training score tends to go up and the gap between train and validation scores tends to go up.
  • How to pick a model?
    • Compare validation scores using cross-validation on the training data.
    • Don’t choose based on training score alone.

Today’s big questions

  • How do \(k\)-NN and RBF SVMs use similarity to make predictions?
  • How do \(k\), \(C\), and \(\gamma\) affect model complexity and generalization?
  • Why do feature scales and the number of features matter for similarity-based models?

We’ll explore these questions through visual examples and prediction activities.

Similarity-based algorithms

  • Use similarity or distance metrics to predict targets.
  • Examples: \(k\)-nearest neighbors, Support Vector Machines (SVMs) with RBF Kernel.

\(k\)-nearest neighbours intuition

Predict the query point’s class using a majority vote of its \(k\) nearest neighbours.

\(k\)-nearest neighbours

  • Classifies an object based on the majority label among its \(k\) closest neighbors.
  • Main hyperparameter: \(k\) or n_neighbors in sklearn
  • Distance Metrics: Euclidean
  • Strengths: simple and intuitive, can learn complex decision boundaries
  • Challenges: Sensitive to the choice of distance metric and scaling (coming up).

iClicker 3.1

Select all of the following statements which are TRUE.

    1. Analogy-based models find examples from the test set that are most similar to the query example we are predicting.
    1. Euclidean distance will always have a non-negative value.
    1. With \(k\)-NN, setting the hyperparameter \(k\) to larger values typically reduces training error.
    1. Similar to decision trees, \(k\)-NNs finds a small set of good features.
    1. In standard (\(k\))-NN classification with uniform weighting and \(k>1\), the closest neighbour always contributes more to the prediction than the other \(k-1\) neighbours.

Curse of dimensionality

  • As dimensionality increases, the space gets much bigger and data points become more spread out.
  • Distances become less informative:
    • Even the nearest neighbours may be far away.
    • Points start to look similarly distant.
  • This makes it harder to generalize from limited data.
  • How to deal with this?
    • Dimensionality reduction (e.g., PCA)
    • Feature selection

RBF SVM intuition

Can a decision stump classify these points perfectly?

Orange points near zero lie between two groups of Blue points on the x axis.

A decision stump makes one split. Where would you split on \(x\)?

No single threshold works: the Orange points lie between two Blue groups.

What if we add \(x^2\) as a feature?

The original points beside their representation using x and x squared. Orange points have small x squared values; Blue points have large values.

Can a decision stump classify these points perfectly now?

Yes! Split on \(x^2 \leq 1.5\): Orange below the threshold, Blue above it.

RBF SVM

  • Adding \(x^2\) made these points easy to separate with one straight line.
  • RBF SVM uses the same idea, but with a richer feature representation.
  • The RBF kernel lets SVM work in that new space using similarities, without explicitly creating the new features.
  • SVM learns a straight separating boundary there, which can appear curved in the original space.

What is a kernel?

A kernel is a function that compares two examples. Here, we interpret its output as similarity.

  • The Radial Basis Function (RBF) kernel gives nearby points high similarity and distant points low similarity.
  • SVM learns how to combine these similarities to separate the classes.
  • Two hyperparameters shape the result: gamma and C.

RBF similarity

The radial basis function (RBF) kernel gives nearby points higher similarity.

\[ K(x,z) = \exp\!\left(-\gamma\|x-z\|^2\right) \]

Same point Nearby points Far-apart points
Similarity 1 Higher similarity Similarity approaches 0
  • \(\|x-z\|\) is the Euclidean distance.
  • \(\gamma > 0\) controls how quickly similarity falls with distance.

How gamma changes similarity

\(\gamma > 0\) controls how quickly similarity falls with distance.

Distance \(r\) \(\gamma = 0.1\) \(\gamma = 1\) \(\gamma = 10\)
0 1 1 1
0.5 0.975 0.779 0.0821
1 0.905 0.368 0.0000454
2 0.670 0.0183 \(4.25\times 10^{-18}\)

At distance 1, similarity is about 0.9 with \(\gamma=0.1\), but almost zero with \(\gamma=10\).

Intuition for gamma

  • Small gamma (\(\gamma\)): Similarities falls gradually with distance
  • Large gamma (\(\gamma\)): Similarities falls quickly with distance

Intuition for C

How strongly do we penalize training mistakes?

Small C Large C
Stronger regularization Weaker regularization
More tolerance for training mistakes More pressure to classify training points correctly
Can allow a simpler boundary Can allow a more intricate boundary

Training identifies the support vectors

A fitted RBF SVM has a curved boundary. Support vectors are outlined among the blue and orange training points.

  • Training learns which points contribute to the decision function and their weights.
  • These are the support vectors; they can be a large fraction of the training set.

How does an RBF SVM predict?

For a new query point:

  1. Compute its RBF similarity to each support vector.
  2. Multiply each similarity by its learned weight and class sign.
  3. Add these contributions and a bias; use the score’s sign to choose the class.

SVM learns how to combine similarities during training.

(Optional) SVM prediction formula

For binary classification, encode Blue as \(-1\) and Orange as \(+1\):

\[ f(x_\text{new}) = \sum_{i\in\text{SV}} \underbrace{\alpha_i}_{\text{learned weight}}\;\underbrace{y_i}_{\text{class sign}}\;\underbrace{K(x_i,x_\text{new})}_{\text{similarity}} + b \]

  • \(x_i\): a support vector; \(\alpha_i > 0\): its learned weight; \(b\): learned bias.
  • Positive score: Orange. Negative score: Blue. Zero is the decision boundary.

For example: \(\underbrace{1.2(0.8)}_{\text{Orange}}-\underbrace{0.7(0.5)}_{\text{Blue}}-\underbrace{0.1}_{\text{bias}}=0.51\) \(\quad\Rightarrow\quad\) Orange

Effect of gamma and C on decision boundaries

Six fitted RBF SVM boundaries on the same dataset. Columns increase gamma from 0.1 to 10; rows increase C from 0.1 to 100.

  1. Across a row: hold C fixed and increase gamma.
  2. Down a column: hold gamma fixed and increase C.

Which settings might underfit or overfit? Choose both using cross-validation.

KNNs vs RBF SVM

\(k\)-NN (uniform weights) SVM with RBF
Find the query’s nearest \(k\) training points Compare the query with the learned support vectors
Each neighbour gets one vote Each similarity gets a learned, signed weight
Neighbours change with the query Support vectors stay fixed; similarities change

More comments on RBF SVM

  • A useful candidate when classes need a nonlinear decision boundary.
  • Requires choosing both \(C\) and \(\gamma\) using validation data.
  • Distances depend on feature scales: preprocessing matters (coming up).
  • Training can be expensive with many examples.

iClicker 3.2

Select all of the following statements which are TRUE.

    1. In sklearn’s RBF SVC, increasing gamma typically increases the training score, but it does not necessarily increase the validation score.
    1. If we increase gamma but decrease C, we can’t be certain whether the model becomes more or less complex.

Class demo

Models

Supervised models we have seen

  • Decision trees: Split data into subsets based on feature values to create decision rules
  • \(k\)-NNs: Classify based on the majority vote from \(k\) nearest neighbors
  • SVM RBFs: Create a boundary using an RBF kernel to separate classes

Comparison of models (activity)

Model Parameters and hyperparameters Strengths Weaknesses
Decision Trees
KNNs
SVM RBF

Our workflow so far

Split \(\to\) Explore \(\to\) Compare \(\to\) Refit \(\to\) Evaluate

  • Compare model types and hyperparameters using cross-validation on training data.
  • Keep the test set untouched until the final evaluation.

Preprocessing motivation: example

Suppose we want to match a student with a compatible roommate using two features:

  • Preferred quiet hours per week.
  • Number of followers on social media.

For this example, we measure similarity using Euclidean distance.

Preprocessing motivation: example

  • Our student prefers 40 quiet hours per week and has 25,000 followers.
Candidate Quiet hours/week Followers Euclidean distance calculation Distance
A 35 40,000 \(\sqrt{5^2 + 15{,}000^2}\) 15,000.00
B 37 30,000 \(\sqrt{3^2 + 5{,}000^2}\) 5,000.00
C 40 50,000 \(\sqrt{0^2 + 25{,}000^2}\) 25,000.00
D 10 25,000 \(\sqrt{30^2 + 0^2}\) 30.00

Based on the distances, the two nearest neighbors (2-NN) are:

  • Candidate D (Distance: 30.00)
  • Candidate B (Distance: 5,000.00)

What’s the problem here?

Follower counts dominate the distance because of their much larger scale. Candidate D is closest despite preferring 30 fewer quiet hours per week!