CS 460G Midterm Hub / Notebooks / k-NN and Decision Trees
Python notebook · kNN-DecisionTree.ipynb

k-NN and Decision Trees

Two non-parametric classifiers on the same split, compared

practice nbQ6 material

Two models, one dataset, one split — a controlled comparison of the two non-parametric methods.

Structure

The notebook is the Iris pipeline from Linear-Classification.ipynb up to the split, then branches twice: once for k-NN and once for the decision tree, each with its own boundary plot and its own metrics.

Cell-by-cell, from the branch point

Data preparation — identical to the classification notebook

iris = datasets.load_iris()
features, labels = iris['data'], iris['target']
X = features[:, 0:2]        # sepal length, sepal width
y = labels
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25)

Then, unlike the earlier notebook, a train/test class distribution check:

plt.hist(y_train, label='train')
plt.hist(y_test,  label='test')
plt.legend()

Side-by-side histograms with alpha defaulting to 1, so the bars obscure each other. It is a real flaw in the notebook — the correct call is plt.hist(..., density=True, alpha=0.5) — and it is worth knowing because "label distribution shown incorrectly" was an actual grading deduction in Assignment 1.

k-NN

from sklearn.neighbors import KNeighborsClassifier
kNN_Model = KNeighborsClassifier(n_neighbors=3)
kNN_Model.fit(X_train, y_train)
y_pred = kNN_Model.predict(X_test)

Three lines that do almost nothing at fit. k-NN stores the training set; all the computation happens in predict. That is the definition of a lazy learner, and it is the first thing to say if asked to explain this cell.

The boundary, in two panels

DecisionBoundaryDisplay.from_estimator(kNN_Model, X_train, response_method="predict", cmap="RdBu_r", alpha=0.5)
plt.scatter(X_train[:,0], X_train[:,1], c=y_train); plt.title('Training samples'); plt.show()

DecisionBoundaryDisplay.from_estimator(kNN_Model, X_train, ...)
plt.scatter(X_test[:,0], X_test[:,1], c=y_test); plt.title('Test samples')

Why two panels with the same grid: the boundary is computed once from X_train and shown twice — once with training points on top, once with test points. This is the correct construction, and it is exactly what was missing (train panel omitted) in the graded Assignment 1 submission.

The k-NN boundary is visibly jagged and locally adaptive — a staircase of Voronoi cells. That shape is the visual signature of a model with no global functional form.

k-NN results

print('kNN accuracy: ', 100*accuracy_score(y_test, y_pred))
# 71.05

print('kNN:\n', confusion_matrix(y_pred, y_test))
# [[14  0  0]
#  [ 0  7  7]
#  [ 0  4  6]]

F1 = f1_score(y_test, y_pred, average=None)
# Setosa 1.0 | Versicolor 0.56 | Virginica 0.522
ClassPrecisionRecallF1Reading
setosa1.001.001.00linearly separable on sepal length/width
versicolor——0.56overlaps virginica
virginica——0.52overlaps versicolor

The average=None detail matters: without it, f1_score returns a single macro-averaged number and you lose the per-class diagnosis. The whole point of this notebook is the per-class breakdown.

Decision tree

from sklearn.tree import DecisionTreeClassifier
DTree_Model = DecisionTreeClassifier()      # note: no max_depth
DTree_Model.fit(X_train, y_train)
y_dtree = DTree_Model.predict(X_test)

No hyperparameters at all — so the tree grows until every leaf is pure. On 112 training points that means a deep tree.

Tree results

print('DTree accuracy: ', 100*accuracy_score(y_test, y_dtree))
# 68.42

print('DTree:\n', confusion_matrix(y_dtree, y_test))
# [[14  0  0]
#  [ 0  4  5]
#  [ 0  7  8]]
ClassF1versus k-NN
setosa1.00same
versicolor0.40k-NN better (0.56)
virginica0.571tree better (0.52)

So the two models fail in opposite directions — the tree confuses virginica as versicolor; k-NN confuses versicolor as virginica. That asymmetry, with overall accuracy 68.4% vs 71.1%, is the interesting observation and the one to write down.

The three-way prediction plot

plt.plot(y_test,  'o', c='b',    label='target')
plt.plot(y_dtree, '*', c='r',    label='DTree')
plt.plot(y_pred,  '^', c='lime', label='kNN')

A per-sample comparison across 38 test points. Where the blue circle has a red star on it, the tree is right; where it has a lime triangle, k-NN is. This plot is how you find the disagreements without computing them — and it is the honest way to show two models' relative performance on a small sample.

What to explain in an exam

> "This notebook fits k-NN and a decision tree to the same data. Why does the tree not clearly win?" > Because a default DecisionTreeClassifier has no regularisation: it grows until every leaf is pure, so on 112 training points it can memorise the training set and its axis-aligned rectangles cut through the versicolor/virginica overlap region. k-NN with $k=3$ also overfits, but its local averaging smooths the boundary slightly. With only two features and 38 test points, neither model has enough information to separate the two overlapping classes, so both land in the 68–71% range. The lesson is that model complexity has to be controlled — max_depth or min_samples_leaf for the tree, larger $k$ for k-NN — and that the choice must be made on validation data, not by trying both on the test set.

What this notebook does NOT do. It does not tune $k$, does not prune the tree, does not stratify the split, and does not set random_state anywhere. Every number in it is one draw. If you quote 71.05% as "k-NN's accuracy on Iris", you are quoting a single unseeded split of 38 samples — a reminder that the whole model-selection deck (W5L3) exists to fix exactly this.