Solve the soft-margin SVM dual for labels yn∈{−1,+1} and a precomputed kernel matrix K:
maxα∑nαn−21∑n,mαnαmynymKnms.t.∑nαnyn=0, 0≤αn≤C
with sequential minimal optimisation: repeatedly pick two multipliers and optimise them analytically. Let ut=∑nαnynKnt and gt=yt−ut. Implement smo_train(K, y, C, tol=1e-6, max_iter=100000) starting from α=0:
- Iup={t:(yt=+1,αt<C) or (yt=−1,αt>0)}, Ilow={t:(yt=+1,αt>0) or (yt=−1,αt<C)}.
- Pick i=argmaxt∈Iupgt and j=argmint∈Ilowgt (lowest index on ties). Stop when gi−gj<
tol or after max_iter updates.
- Update the pair with η=Kii+Kjj−2Kij: αjnew=αj−yj(gi−gj)/η, clipped to [L,H] where L=max(0,αj−αi), H=min(C,C+αj−αi) if yi=yj and L=max(0,αi+αj−C), H=min(C,αi+αj) otherwise; then αi←αi+yiyj(αj−αjnew).
- Bias: the mean of gt over free support vectors (10−8<αt<C−10−8); if there are none, the midpoint of maxIupg and minIlowg.
Return (alpha, b, n_iter). Also implement decision_function(alpha, y, K_test, b) (Ktest of shape (m, N), returns Ktest(α⊙y)+b) and kkt_violations(alpha, K, y, b, C, tol=1e-3), the number of training points whose margin ytf(xt) breaks its KKT condition: ≥1− tol if αt≤10−8, ≤1+ tol if αt≥C−10−8, and within tol of 1 otherwise.