Binary and multiclass SVMs implemented from first principles — kernels, solver, evaluation — then benchmarked against scikit-learn to find exactly where hand-rolled optimization wins and where it doesn't.
Arya AmarnathBuilt Python · NumPy · from scratch
Try the project
Abstract. Most SVM workflows hide the optimization behind a library call. This project builds the kernel matrix, the weight solver, and a One-vs-All multiclass extension by hand, then compares them to scikit-learn on the UCI E. coli dataset. The from-scratch polynomial kernel beats sklearn's default on binary classification (0.85 vs 0.53); on tuned multiclass, sklearn wins — and that gap is the real finding.
§ 1 · Problem
Understand the machine, don't import it
Calling SVC().fit() teaches you nothing about margins, kernels, or the dual problem. The
goal here was to implement the mathematics end to end so the abstraction is earned — the
same instinct I now bring to trading models.
§ 2 · Data
UCI E. coli localization
336 samples, seven numeric features, eight protein-localization classes — small enough to
reason about, imbalanced enough to be honest about. A binary subset drives the kernel
comparison; the full eight classes drive the multiclass extension.
§ 3 · Method
Kernels and a hand-rolled solver
Linear, polynomial, RBF and sigmoid kernels were built as explicit matrix constructions,
paired with an algebraic weight solver rather than the standard quadratic-programming path,
then extended to eight classes with One-vs-All.
svm/kernels.py
# Custom polynomial kernel matrixdefpolynomial_kernel(X1, X2, degree=3, coef0=1):
return (np.dot(X1, X2.T) + coef0) ** degree
defcompute_kernel_matrix(X, kernel_fn):
n = X.shape[0]
K = np.zeros((n, n))
for i in range(n):
for j in range(i, n):
K[i, j] = kernel_fn(X[i:i+1], X[j:j+1])
K[j, i] = K[i, j]
return K
§ 4 · Results
Where from-scratch wins, and where it loses
Binary (poly)
0.85
0.53
Multiclass
0.92
0.75
■ from scratch ■ scikit-learn
Fig. 1 — the hand-built polynomial kernel beats sklearn's default on the binary task; tuned sklearn wins multiclass.
On the binary polynomial task the custom classifier reached 0.85 vs sklearn’s default
0.53. On multiclass the custom implementation landed at 0.75 against a tuned
sklearn’s 0.91–0.93. The gap is the point: it shows precisely where SMO-style
support-vector optimization earns its keep.
§ 5 · Discussion
What the gap taught
A naive algebraic solver matches libraries on simple, separable problems and falls behind as class count and overlap grow.
Proper SMO optimization — not more kernels — is what closes the multiclass gap.
Building it by hand made the sklearn result legible instead of magical: I know why it wins now.