Week 10 · Margins, kernels, and local prediction
Compare linear, kernel, and nearest-neighbour decision rules.
← Week 9 · Subject contents · Week 11 →
Compare linear, kernel, and nearest-neighbour decision rules.
Work through the problem
A linear boundary scores w·x+b. Distance to the boundary is the absolute score divided by ‖w‖. A large-margin classifier tries to separate examples with room to spare. An RBF kernel k(x,z) = exp(−γ‖x−z‖²) makes the decision depend on local similarity in feature space.
At γ = 1, pairs at distance 1 have similarity e⁻¹, while pairs at distance 3 have similarity e⁻⁹. Nearest neighbours uses distance directly and votes among nearby training points. Concentric circles reveal why a straight boundary can fail when the relevant feature is distance from the centre.
Run the Python lab
from sklearn.datasets import make_circles
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
X,y = make_circles(n_samples=300,noise=.07,factor=.45,random_state=4)
a,b,c,d = train_test_split(X,y,stratify=y,test_size=.3,random_state=7)
scores = []
for model in [SVC(kernel="linear"),SVC(),KNeighborsClassifier(7)]:
pipe = make_pipeline(StandardScaler(),model).fit(a,c)
scores.append(pipe.score(b,d))
print("Linear, RBF, neighbours:", [round(v,3) for v in scores])
assert scores[1] > scores[0] + .25
Output from the lab
Linear, RBF, neighbours: [0.467, 1.0, 1.0]
Practice
- What happens if one feature is multiplied by 100 before fitting?
Check your reasoning
- Without scaling, it can dominate distances and change both local methods.