CS 460G Midterm Hub / Notebooks / SVM Classification
Python notebook · Copy of SVM-classifiation.ipynb

SVM Classification

Linear SVM, support vectors, and the XOR kernel demonstration

practice nbQ6 material

The most exam-relevant practice notebook, because it contains the kernel demonstration that the whole W5L2 lecture is built around.

Three parts

  1. Binary SVM on versicolor vs virginica
  2. 3-class SVM on all of Iris
  3. The XOR experiment: linear with varying $C$, then polynomial, then RBF, then a $C\times\gamma$ grid

Part 1 — binary classification

The deliberate subset

X_train, X_test, y_train, y_test = train_test_split(
    X[50:], y[50:], test_size=0.25, random_state=9999)
# (75, 2), (25, 2), (75,), (25,)

X[50:] drops setosa entirely, leaving 100 samples of versicolor (class 1) and virginica (class 2). The class labels stay 1 and 2 — they are not re-encoded to 0/1.

Why this matters for the metrics: f1_score(..., average=None) returns a 2-element array, and the notebook labels them Setosa and Versicolor — both wrong. They are versicolor and virginica. A mislabelled metric output is a named deduction in the graded version.

Why this is a good binary problem: versicolor and virginica overlap in petal length/width, so a linear boundary is genuinely being tested rather than handed a separable case.

Fit

from sklearn.svm import SVC
SVM_Model = SVC(kernel='linear')
SVM_Model.fit(X_train, y_train)
y_pred = SVM_Model.predict(X_test)

C is left at the default 1.0. kernel='linear' is the only choice being varied here.

The support-vector plot — the key figure

DecisionBoundaryDisplay.from_estimator(SVM_Model, X_train, response_method="predict", ...)
plt.scatter(X_train[:,0], X_train[:,1], c=y_train)
plt.scatter(SVM_Model.support_vectors_[:,0], SVM_Model.support_vectors_[:,1],
            marker='+', c='r', label='Support vectors')

This is the single most important figure in the notebook. The red + marks sit exactly on the margin — the two hyperplanes at $w^Tx+w_0=\pm1$. Everything else is irrelevant to the fitted boundary.

How to explain it: if you delete any non-support-vector point and refit, the boundary does not move. If you move a support vector by ε, the boundary moves. That is what "support vector" means, and SVM_Model.support_vectors_ is the direct read-out.

Results

print('SVM accuracy: ', 100*accuracy_score(y_test, y_pred))   # 100.0
print('Linear SVM:\n', confusion_matrix(y_pred, y_test))
# [[14  0]
#  [ 0 11]]

25/25 correct. In 2-D petal space, versicolor and virginica are linearly separable on this particular split — a useful reminder that "they overlap" is a statement about the full 4-D data, not about every 2-D projection.

Part 2 — 3-class

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=9999)
SVM_Model = SVC(kernel='linear')     # default C, one-vs-one internally

Accuracy drops below 100% because setosa/versicolor/virginica is not linearly separable in a single 2-D plane. The notebook does not print the number, which is a gap worth noting.

What to say about multiclass SVM: SVC is binary by construction; scikit-learn wraps it in a one-vs-one scheme — $C(C-1)/2 = 3$ binary classifiers for 3 classes — and each pair's vote is aggregated. That is why a "binary" algorithm handles Iris at all.

Part 3 — the XOR experiment

Build the data

np.random.seed(0)
X_xor = np.random.randn(200, 2)
y_xor = np.logical_xor(X_xor[:,0] > 0, X_xor[:,1] > 0)
y_xor = np.where(y_xor, 1, -1)      # +1 / -1 for the SVM

200 Gaussian points, labelled by the sign pattern of the quadrants. This is the canonical non-linearly-separable problem.

Linear SVM with four values of C

C = [0.1, 1.0, 10.0, 100.0]
for c in C:
    svm0 = SVC(kernel='linear', C=c).fit(X_xor, y_xor)
    ...

Four plots, four straight lines. Increasing $C$ from 0.1 to 100 rotates and shifts the line slightly and increases the number of support vectors it is pinned to, but it never bends.

This is the answer to "what does C do?" $C$ is a penalty on margin violations in the current feature space. If no hyperplane can separate the classes, a larger $C$ only chooses the least-bad hyperplane more aggressively — it cannot create a boundary that the hypothesis class does not contain. $C$ controls regularisation, not model complexity. Model complexity comes from the kernel.

Polynomial kernel

svm = SVC(kernel='poly', random_state=0, degree=2).fit(X_xor, y_xor)

A visibly curved boundary that separates the quadrants. Degree 2 supplies the $x_1x_2$ and $x_i^2$ terms needed to express XOR.

RBF kernel

svm = SVC(kernel='rbf', random_state=0, gamma=0.1).fit(X_xor, y_xor)

A smooth closed region around each diagonal cluster.

The $C \times \gamma$ grid

C_2d_range = [1e-2, 1, 1e2]
gamma_2d_range = [1e-1, 1, 1e1]
for c in C_2d_range:
    for gamma in gamma_2d_range:
        clf = SVC(kernel='rbf', C=c, gamma=gamma).fit(X_xor, y_xor)
...
Z = clf.decision_function(...)
plt.pcolormesh(xx, yy, -Z, cmap=plt.cm.RdBu, alpha=0.5)
plt.title("$\gamma$=%0.2f, C=%0.2f" % (gamma, C))

A 3×3 panel of decision surfaces. Read it as a grid:

  • Small $\gamma$ (0.1, left column) — every panel looks almost linear, regardless of $C$. The kernel decays so slowly that all points influence everything.
  • Large $\gamma$ (10, right column) — small islands around individual points; the model is fitting noise.
  • Varying $C$ at fixed $\gamma$ changes the smoothness within a column but far less than $\gamma$ changes it across a row.

The conclusion to state: $\gamma$ dominates the shape of the boundary; $C$ tunes how strictly the margin is enforced. That is why tuning $\gamma$ first and $C$ second is the practical order, and it is what the Assignment 2 grid shows numerically ($C{=}0.01,\gamma{=}0.1$ collapsing to ~31% accuracy).

The notebook's cell 51 produces SyntaxWarning: invalid escape sequence '\g' because "$\gamma$..." is a normal string, not a raw one. Harmless, but if asked "what is this warning?", the answer is that \g is not a valid Python escape — use r"$\gamma$=..." or "\\gamma".

Summary table

ExperimentKernelSettingBoundary shapeAccuracy
Iris binarylineardefault $C$straight line100%
Iris 3-classlineardefault $C$three pairwise lines< 100%
XORlinear$C=0.1\ldots100$still straightpoor at every $C$
XORpoly$d=2$curvedgood
XORrbf$\gamma=0.1$smooth closed regionsgood
XOR gridrbf$\gamma$ small→largelinear → islands$\gamma$ dominates