↓ Luncat ka eusi utama
  1. Catetan Rékayasa & Artikel Téknis/

Geometri Decision Boundaries — Support Vector Machines & The Kernel Trick

Daptar eusi
Dasar Machine Learning - Artikel ieu mangrupikeun bagian tina hiji séri.
Bagian 5: Artikel ieu

1. Masalah Inti: Infinite Hyperplanes sareng Non-Linear Geometry
#

Dina Part 2, urang ngelatih linear classifiers sapertos Logistic Regression ku ngamaksimalkeun likelihood tina labels anu diobservasi dina sakabeh dataset. Rengking probabilistik eta jalan kalayan apik, sanajan ninggalkeun dua masalah geometri dasar anu teu karengsekeun:

  1. The Ambiguity of Separable Data: Anggap dua kelas dina $\mathbb{R}^2$ linier separable kalayan bersih. Aya tak hingga akeh hyperplanes anu ngahasilkeun zero training error. Sabaraha nyelusuran katingal nyepak ka training points (dimana noise test-time leutik ngabalukarkeun misclassification), sambil sejen nangtu heureut dina tengah gap. Langkung parah, dina data separable sampurna, Logistic Regression unregularized ngajalankeun norma weight-na $\Vert{}w\Vert{}_2 \to \infty$ salaku eta rek nyorong predicted probabilities ka exact $0$ sareng $1$.
  2. Non-Linearly Separable Structure: Data dunya nyata jarang nyebar dina flat plane—bayangkeun concentric rings, XOR clusters, atawa curved sensor decision regions. Sacara eksplisit ngarancang polynomial interaction terms nepi ka degree $k$ dina $d$ input features ngahasilkeun $\binom{d + k}{k}$ dimensi, muges memory sareng compute sacara exponential.

Support Vector Machines (SVMs), anu dimimitian ku Bernhard Boser, Isabelle Guyon, sareng Vladimir Vapnik (1992) sareng diekspansi ka data noisy ku Corinna Cortes sareng Vladimir Vapnik (1995), ngarengsekeun dua masalah ngalangkungan pure convex geometry:

  • Kahiji, harti unique optimal hyperplane ku ngamaksimalkeun geometric safety margin antara kelas.
  • Kadua, ransformasi optimization ka Lagrangian Dual, nembongkeun data points ngasup dina masalah murni ngalangkungan inner products—ngabuka Kernel Trick pikeun ngitung non-linear boundaries dina infinite-dimensional spaces dina biaya anu lega.

2. Intuisi Konsep: The Widest Road sareng Lifting Dimensions
#

The Widest Road (Maximum Margin)
#

Bayangkeun dua wewengkon saingan—rumah beureum sareng rumah bulao—dipisahkeun ku hiji damar, sareng anjeun kedah ngaspal hiji sorongan lurus antarana. Anjeun tiasa nagur narrow lane anu nyentuh porch rumah anu nepip, atawa ngawangun sorongan panglebarna anu garis tengahna saluyu jauhna ti rumah anu pangdeukeutna dina dua sisi.

Catet hiji property anu luar bias tina sorongan panglebarna ieu: ngan sabaraha rumah anu nangtung langsung dina curb sorongan anu nangtu posisi sareng sudutna. Mindahkeun rumah tilu blok langkung jero ka salah sahiji wewengkon teu ngarobah sorongan ku sekedik. Titik anu nangtu boundary ieu disebut Support Vectors.

Lifting into Higher Dimensions (The Kernel Trick)
#

Ayeuna anggap rumah bulao ngahasilkeun circle heureut anu disaluran sampurna ku ring rumah beureum. Teu aya sorongan lurus dina flat 2D space anu bisa misahkeun.

Alih-alih ngalengkungkeun sorongan, angkat unggal rumah sacara vertikal kaluar ti map nurutkeun kuadrat jarak ti origin: $z = x_1^2 + x_2^2$. Sacara kedah, rumah bulao jero nangtu di dasar 3D bowl sambing rumah beureum luar langkung luhur dina rim. flat horizontal sheet anu sampurna nyelusuran antarana—sareng lamun diproyeksikeun balik ka 2D map, slice datar eta jadi circle.

Kernel Trick ngabawa idea eta ka wates matematis: ngitung efek persis ti lifting data ka jutaan—atawa sanajan tak hingga akeh—dimensi tanpa kalaulaweun ngitung lifted coordinates sacara eksplisit.


3. Rumusan Matematis: Primal Hard-Margin & Soft-Margin SVM
#

3.1 Hard-Margin SVM (Linearly Separable Case)
#

Nerapkeun symmetric binary labels $y_i \in \{-1, +1\}$ pikeun $i = 1, \dots, n$, sareng harti hiji linear decision hyperplane:

$$f(x) = w^\top x + b = 0$$

Signed perpendicular Euclidean distance ti unggal titik $x_i$ ka hyperplane nyaeta:

$$d(x_i) = \frac{y_i (w^\top x_i + b)}{\Vert{}w\Vert{}_2}$$

Numerator $\gamma_i = y_i(w^\top x_i + b)$ mangrupikeun functional margin, anu positip nalika $x_i$ klasifikasi kalayan bener. Sabab rescaling $(w, b) \mapsto (cw, cb)$ pikeun unggal $c \gt 0$ ngajelaskeun hyperplane anu sami persis, urang ngeleungitkeun scale ambiguity ku nyetel functional margin tina closest training points ka exactly $1$:

$$y_i (w^\top x_i + b) \ge 1 \qquad \forall i \in \{1, \dots, n\}$$

Dina canonical normalization ieu, dua parallel boundary hyperplanes $w^\top x + b = +1$ sareng $w^\top x + b = -1$ nangtukeun margin corridor total width:

$$\text{Margin Width} = \frac{2}{\Vert{}w\Vert{}_2}$$

Ngamaksimalkeun half-margin $\frac{1}{\Vert{}w\Vert{}_2}$ sacara matematis sami sareng ngaminimalkeun $\frac{1}{2}\Vert{}w\Vert{}_2^2$:

$$\min_{w, b} \; \frac{1}{2} \Vert{}w\Vert{}_2^2 \qquad \text{subject to} \qquad y_i (w^\top x_i + b) \ge 1 \quad \forall i$$

Sabab objective $\frac{1}{2}\Vert{}w\Vert{}_2^2$ strictly convex dina $w$ sareng sadaya constraints linier inequalities, ieu Convex Quadratic Program (QP)—masihan unique global optimum tanpa local-minimum traps.


3.2 Soft-Margin SVM & Hinge Loss (Noisy / Overlapping Data)
#

Hard-margin constraints jadi infeasible sacara instan nalika mungkin salah sahiji noisy point ngalintasi ka kelas beda. Cortes sareng Vapnik (1995) ngaleusikeun constraint ku nyocokkeun slack variables non-negatif $\xi_i \ge 0$ pikeun unggal training sample:

$$\min_{w, b, \xi} \; \frac{1}{2} \Vert{}w\Vert{}_2^2 + C \sum_{i=1}^{n} \xi_i$$$$\text{subject to} \qquad y_i (w^\top x_i + b) \ge 1 - \xi_i, \qquad \xi_i \ge 0 \quad \forall i$$

Slack variable $\xi_i$ ngabogaan harti geometri langsung:

  • $\xi_i = 0$: Titik $i$ nangtung dina atawa di luar sisi anu bener tina margin.
  • $0 \lt \xi_i \le 1$: Titik $i$ ngalanggar margin corridor, sanajan tetep dina sisi anu bener tina decision boundary.
  • $\xi_i \gt 1$: Titik $i$ misclassified.

Regularization hyperparameter $C \gt 0$ langsung ngadalikeun Bias–Variance tradeoff tina Part 4:

  • Large $C$: Ngahukum slack violations kencang—ndeukeut ka hard-margin fit anu heureut (low bias, higher variance, sensitif ka outliers).
  • Small $C$: Ngidinan margin violations dibalikeun ku $\Vert{}w\Vert{}_2$ anu leutik sareng corridor anu leuwih lebar (higher bias, lower variance, robust ka label noise).

Ngarengsekeun slack anu panghadekna $\xi_i^* = \max(0, 1 - y_i(w^\top x_i + b))$ nulis deui Soft-Margin SVM jadi objective regularized anu teu dibatasi:

$$\min_{w, b} \; \underbrace{\frac{1}{2}\Vert{}w\Vert{}_2^2}_{\text{L2 Regularizer}} + C \sum_{i=1}^{n} \underbrace{\max\big(0,\, 1 - y_i(w^\top x_i + b)\big)}_{\text{Hinge Loss}}$$

Bandingkeun Hinge Loss sareng Logistic (Cross-Entropy) Loss $\log(1 + e^{-y_i f(x_i)})$: Logistic loss positip sampurna dimana wae, hartina sanajan titik anu jauh, anu trivially classified mibanda gradient pull leutik ka decision boundary. Hinge loss identically zero sakali $y_i f(x_i) \ge 1$—masihan sparsity khas SVM.


4. The Lagrangian Dual Problem & KKT Sparsity
#

Pikeun ngabuka non-linear kernels sareng nembongkeun peran matematis persis tina Support Vectors, urang ngawangun Lagrangian make dual multipliers non-negatif $\alpha_i \ge 0$ (pikeun margin constraints) sareng $\mu_i \ge 0$ (pikeun $\xi_i \ge 0$):

$$\mathcal{L}(w, b, \xi, \alpha, \mu) = \frac{1}{2}\Vert{}w\Vert{}_2^2 + C \sum_{i=1}^{n} \xi_i - \sum_{i=1}^{n} \alpha_i \Big[ y_i(w^\top x_i + b) - 1 + \xi_i \Big] - \sum_{i=1}^{n} \mu_i \xi_i$$

Sabab primal problem convex sareng nyumponan Slater’s condition, strong duality leres: ngaminimalkeun dina $(w, b, \xi)$ lajeng ngamaksimalkeun dina $(\alpha, \mu)$ nepi ka nilai optimal anu sami persis.

Step 1: Primal Stationarity Conditions
#

Setel partial derivatives dina primal variables $(w, b, \xi_i)$ ka nol:

  1. With respect to $w$:
$$\nabla_w \mathcal{L} = w - \sum_{i=1}^{n} \alpha_i y_i x_i = 0 \implies w^* = \sum_{i=1}^{n} \alpha_i y_i x_i$$
  1. With respect to $b$:
$$\frac{\partial \mathcal{L}}{\partial b} = -\sum_{i=1}^{n} \alpha_i y_i = 0 \implies \sum_{i=1}^{n} \alpha_i y_i = 0$$
  1. With respect to $\xi_i$:
$$\frac{\partial \mathcal{L}}{\partial \xi_i} = C - \alpha_i - \mu_i = 0 \implies \alpha_i + \mu_i = C$$

Sabab $\alpha_i \ge 0$ sareng $\mu_i \ge 0$, ngeleungitkeun $\mu_i$ ngapaksa box constraint $0 \le \alpha_i \le C$.

Step 2: The Wolfe Dual Objective
#

Substitusikeun tilu identitas ieu balik ka $\mathcal{L}$. $b$ sareng $\xi_i$ duanana leungit sacara identitas, ngahasilkeun Dual Soft-Margin SVM:

$$\max_{\alpha \in \mathbb{R}^n} \; W(\alpha) = \sum_{i=1}^{n} \alpha_i - \frac{1}{2} \sum_{i=1}^{n} \sum_{j=1}^{n} \alpha_i \alpha_j y_i y_j (x_i^\top x_j)$$$$\text{subject to} \qquad 0 \le \alpha_i \le C \quad \forall i, \qquad \sum_{i=1}^{n} \alpha_i y_i = 0$$

Step 3: KKT Complementary Slackness & Support Vectors
#

Dina optimal solution, kaayaan Karush–Kuhn–Tucker (KKT) complementary slackness kedah leres pikeun unggal sample $i$:

$$\alpha_i \Big[ y_i(w^{*\top} x_i + b^*) - 1 + \xi_i^* \Big] = 0 \qquad \text{and} \qquad (C - \alpha_i)\,\xi_i^* = 0$$

Dua persamaan ieu misahkeun sakabeh training set jadi tilu kategori geometri anu persis:

Multiplier Value Slack Variable Geometric Location Role in the Model
$\alpha_i = 0$ $\xi_i^* = 0$ $y_i f(x_i) \ge 1$ (safely outside margin) Non-Support Vector — contributes zero to $w^*$; removing it leaves the model unchanged.
$0 \lt \alpha_i \lt C$ $\xi_i^* = 0$ $y_i f(x_i) = 1$ (exact margin boundary) Free Support Vector — pins the margin and uniquely determines the intercept $b^*$.
$\alpha_i = C$ $\xi_i^* \ge 0$ $y_i f(x_i) \le 1$ (inside margin or misclassified) Bounded Support Vector — actively pulls the hyperplane, capped at maximum influence $C$.

Make unggal free support vector $x_k$ (sareng $0 \lt \alpha_k \lt C$), urang ngawangun deui exact bias term langsung ti $y_k(w^{*\top} x_k + b^*) = 1$ (atawa rata-ratakeun dina sadaya free support vectors pikeun numerical stability):

$$b^* = y_k - \sum_{i \in \text{SV}} \alpha_i y_i (x_i^\top x_k)$$

5. The Kernel Trick & Mercer’s Theorem
#

Tingali Dual objective $W(\alpha)$ sareng final prediction function pikeun unggal test point $x$ anu can kakintun kalayan sakedik:

$$f(x) = w^{*\top} x + b^* = \sum_{i \in \text{SV}} \alpha_i y_i (x_i^\top x) + b^*$$

Input vectors $x_i$ teu katingal sendiri—ngan di jero inner products $(x_i^\top x_j)$.

Ayeuna bayangkeun mapping unggal input ngalangkungan non-linear feature transformation $\phi: \mathcal{X} \to \mathcal{F}$ ka high-dimensional (atawa infinite-dimensional) inner product space $\mathcal{F}$. Alih-alih sacara eksplisit ngitung $\phi(x_i)$ sareng $\phi(x_j)$, urang nangtukeun hiji kernel function $K: \mathcal{X} \times \mathcal{X} \to \mathbb{R}$ anu ngitung inner product-na langsung dina input space:

$$K(x, z) = \langle \phi(x), \phi(z) \rangle_{\mathcal{F}}$$

Ngaganti unggal $(x_i^\top x_j)$ sareng $K(x_i, x_j)$ ngarobah linear maximum-margin classifier jadi non-linear classifier anu arbitrarily flexible:

$$f(x) = \sum_{i \in \text{SV}} \alpha_i y_i K(x_i, x) + b^*$$

Concrete Example 1: Finite Explicit Expansion (Polynomial Kernel)
#

Biar $x, z \in \mathbb{R}^2$ sareng harti $K(x, z) = (x^\top z + 1)^2$. Ngabuka sacara aljabar:

$$(x_1 z_1 + x_2 z_2 + 1)^2 = 1 + 2 x_1 z_1 + 2 x_2 z_2 + x_1^2 z_1^2 + 2 x_1 x_2 z_1 z_2 + x_2^2 z_2^2$$

Ieu dot product $\phi(x)^\top \phi(z)$ anu persis dina $\mathbb{R}^6$ pikeun:

$$\phi(x) = \begin{bmatrix} 1, & \sqrt{2}\,x_1, & \sqrt{2}\,x_2, & x_1^2, & \sqrt{2}\,x_1 x_2, & x_2^2 \end{bmatrix}^\top$$

Ngitung $(x^\top z + 1)^2$ nyandak $O(d)$ operations teu gumantung kana degree—sambing sacara eksplisit materialize $\phi(x)$ pikeun degree $p$ nyandak $O(d^p)$.

Concrete Example 2: Infinite Dimensions (RBF / Gaussian Kernel)
#

Radial Basis Function (RBF) kernel mangrupikeun workhorse tina non-linear SVMs:

$$K_{\text{RBF}}(x, z) = \exp\!\left(-\gamma \Vert{}x - z\Vert{}_2^2\right), \qquad \gamma \gt 0$$

Ngabuka $\Vert{}x - z\Vert{}_2^2 = \Vert{}x\Vert{}_2^2 + \Vert{}z\Vert{}_2^2 - 2 x^\top z$ sareng nerapkeun Taylor series $e^u = \sum_{k=0}^{\infty} \frac{u^k}{k!}$:

$$K_{\text{RBF}}(x, z) = e^{-\gamma \Vert{}x\Vert{}_2^2} \, e^{-\gamma \Vert{}z\Vert{}_2^2} \sum_{k=0}^{\infty} \frac{(2\gamma)^k}{k!} (x^\top z)^k$$

Sabab unggal istilah $(x^\top z)^k$ pakait sareng sadaya degree-$k$ monomials sareng sum nepi ka $k = \infty$, RBF kernel ngitung exact inner product di jero infinite-dimensional Hilbert space dina ngan $O(d)$ arithmetic! Sacara intuitif, unggal support vector nyieun Gaussian bump localized kalayan radius $\sim 1/\sqrt{2\gamma}$ sabudeureun eta, sareng $f(x)$ ngahijikeun bumps eta jadi non-linear decision boundary smooth.

Naon Fungsi Anu Mangrupikeun Valid Kernels? (Mercer’s Theorem)
#

Teu unggal similarity function $K(x, z)$ pakait sareng inner product legitimate dina sabaraha feature space $\mathcal{F}$—upami teu, Dual objective $W(\alpha)$ jadi non-concave sareng optimization bisa diverge ka $+\infty$.

Ngawangun kana Mercer’s Theorem (1909) sareng Reproducing Kernel Hilbert Space (RKHS) theory (Aronszajn, 1950; Schölkopf & Smola, 2002), symmetric continuous function $K(x, z)$ mangrupikeun valid positive-definite kernel upami sareng ngan upami, pikeun unggal hijian titik $\{x_1, \dots, x_n\} \subset \mathcal{X}$, resulting $n \times n$ Gram matrix $K_{ij} = K(x_i, x_j)$ Positive Semi-Definite (PSD):

$$c^\top K c = \sum_{i=1}^{n} \sum_{j=1}^{n} c_i c_j K(x_i, x_j) \ge 0 \qquad \forall c \in \mathbb{R}^n$$

Common Mercer Kernels Compared
#

Kernel Formula $K(x, z)$ Induced Feature Space $\mathcal{F}$ Key Hyperparameters & Behavior
Linear $x^\top z$ Original input space $\mathbb{R}^d$ Fast; preferred when $d$ is already huge (e.g., TF-IDF text, genomics).
Polynomial $(\gamma x^\top z + r)^p$ All monomials up to degree $p$ ($\binom{d+p}{p}$ dims) Captures fixed-order feature interactions; numerically unstable for large $p$.
RBF (Gaussian) $\exp(-\gamma \Vert{}x - z\Vert{}_2^2)$ Infinite-dimensional RKHS Universal approximator; small $\gamma$ yields smooth boundaries, large $\gamma$ overfits tightly around points.
Laplacian $\exp(-\gamma \Vert{}x - z\Vert{}_1)$ Infinite-dimensional RKHS Sharper, less smooth boundaries than RBF; more robust to coordinate outliers.

Maximum-margin hyperplane with support vectors and RBF kernel separation

Figure 5. Kenca: maximum-margin hyperplane nangtu sampurna ku support vectors. Katuhu: RBF kernel misahkeun concentric classes anu teu bisa ku linear boundary.

6. Minimal Implementation: Dual Kernel SVM via SMO dina NumPy
#

Alih-alih ngahirupan black-box solver, urang nerapkeun algoritma Sequential Minimal Optimization (SMO) anu bersih (Platt, 1998) ti nol dina pure NumPy. Sabab equality constraint $\sum_{i=1}^{n} \alpha_i y_i = 0$ nyegah ngapdetkeun hiji $\alpha_i$ sorangan, SMO ngapdetkeun dua multipliers $(\alpha_i, \alpha_j)$ sacara babarengan unggal langkah—ngidinan exact analytical update tanpa matrix inversions.

Urang nguji solver urang dina non-linearly separable concentric-rings dataset, langsung ngabandingkeun Linear Kernel sareng RBF Kernel sareng nga-audit exact KKT support-vector partition.

import numpy as np


def linear_kernel(X1: np.ndarray, X2: np.ndarray) -> np.ndarray:
    return X1 @ X2.T


def rbf_kernel(X1: np.ndarray, X2: np.ndarray, gamma: float = 1.0) -> np.ndarray:
    # ||x - z||^2 = ||x||^2 + ||z||^2 - 2 x^T z
    sq_dists = (
        np.sum(X1 ** 2, axis=1, keepdims=True)
        + np.sum(X2 ** 2, axis=1)[None, :]
        - 2.0 * (X1 @ X2.T)
    )
    return np.exp(-gamma * np.maximum(sq_dists, 0.0))


class DualKernelSVM:
    """Soft-Margin Dual Kernel SVM trained via Simplified SMO (Platt, 1998)."""

    def __init__(self, C: float = 2.0, kernel_fn=linear_kernel, tol: float = 1e-3, max_passes: int = 30):
        self.C = C
        self.kernel_fn = kernel_fn
        self.tol = tol
        self.max_passes = max_passes
        self.alpha = None
        self.b = 0.0
        self.X_sv = None
        self.y_sv = None
        self.alpha_sv = None

    def fit(self, X: np.ndarray, y: np.ndarray, seed: int = 42):
        rng = np.random.default_rng(seed)
        n = X.shape[0]
        K = self.kernel_fn(X, X)  # Precomputed n x n Mercer Gram matrix

        alpha = np.zeros(n, dtype=float)
        b = 0.0
        passes = 0

        while passes < self.max_passes:
            num_changed = 0
            for i in range(n):
                f_i = float(np.dot(alpha * y, K[:, i]) + b)
                E_i = f_i - y[i]

                # Check if sample i violates KKT optimality conditions
                kkt_violated = (
                    (y[i] * E_i < -self.tol and alpha[i] < self.C)
                    or (y[i] * E_i > self.tol and alpha[i] > 0.0)
                )
                if not kkt_violated:
                    continue

                # Pick partner index j != i
                j = int(rng.integers(0, n - 1))
                if j >= i:
                    j += 1

                f_j = float(np.dot(alpha * y, K[:, j]) + b)
                E_j = f_j - y[j]

                ai_old, aj_old = alpha[i], alpha[j]

                # Compute feasible box bounds [L, H] preserving sum(alpha_k y_k) = 0
                if y[i] != y[j]:
                    L = max(0.0, aj_old - ai_old)
                    H = min(self.C, self.C + aj_old - ai_old)
                else:
                    L = max(0.0, ai_old + aj_old - self.C)
                    H = min(self.C, ai_old + aj_old)

                if L == H:
                    continue

                # Second derivative along the 2-variable constraint line
                eta = 2.0 * K[i, j] - K[i, i] - K[j, j]
                if eta >= 0.0:
                    continue

                # Analytical update for alpha_j, clipped to [L, H]
                aj_new = np.clip(aj_old - y[j] * (E_i - E_j) / eta, L, H)
                if abs(aj_new - aj_old) < 1e-5:
                    continue

                # Coupled update for alpha_i
                ai_new = ai_old + y[i] * y[j] * (aj_old - aj_new)

                # Update bias b to satisfy margin condition on free support vectors
                b1 = (
                    b - E_i
                    - y[i] * (ai_new - ai_old) * K[i, i]
                    - y[j] * (aj_new - aj_old) * K[i, j]
                )
                b2 = (
                    b - E_j
                    - y[i] * (ai_new - ai_old) * K[i, j]
                    - y[j] * (aj_new - aj_old) * K[j, j]
                )

                if 0.0 < ai_new < self.C:
                    b = b1
                elif 0.0 < aj_new < self.C:
                    b = b2
                else:
                    b = 0.5 * (b1 + b2)

                alpha[i], alpha[j] = ai_new, aj_new
                num_changed += 1

            passes = passes + 1 if num_changed == 0 else 0

        # Store only the sparse Support Vectors (alpha_i > 1e-5)
        self.alpha = alpha
        self.b = b
        sv_mask = alpha > 1e-5
        self.X_sv = X[sv_mask]
        self.y_sv = y[sv_mask]
        self.alpha_sv = alpha[sv_mask]
        return self

    def decision_function(self, X: np.ndarray) -> np.ndarray:
        K_test = self.kernel_fn(X, self.X_sv)
        return K_test @ (self.alpha_sv * self.y_sv) + self.b

    def predict(self, X: np.ndarray) -> np.ndarray:
        return np.where(self.decision_function(X) >= 0.0, 1.0, -1.0)


# =====================================================================
# Benchmark: Concentric Rings (Non-Linearly Separable in R^2)
# =====================================================================
def make_concentric_rings(n_per_class: int = 80, seed: int = 7):
    rng = np.random.default_rng(seed)
    theta_in = rng.uniform(0.0, 2.0 * np.pi, size=n_per_class)
    r_in = 0.6 + rng.normal(0.0, 0.12, size=n_per_class)
    X_in = np.column_stack([r_in * np.cos(theta_in), r_in * np.sin(theta_in)])

    theta_out = rng.uniform(0.0, 2.0 * np.pi, size=n_per_class)
    r_out = 1.6 + rng.normal(0.0, 0.15, size=n_per_class)
    X_out = np.column_stack([r_out * np.cos(theta_out), r_out * np.sin(theta_out)])

    X = np.vstack([X_in, X_out])
    y = np.hstack([-np.ones(n_per_class), np.ones(n_per_class)])
    perm = rng.permutation(len(y))
    return X[perm], y[perm]


X_train, y_train = make_concentric_rings(n_per_class=80, seed=7)
X_test, y_test = make_concentric_rings(n_per_class=100, seed=99)

models = [
    ("Linear Kernel SVM", DualKernelSVM(C=2.0, kernel_fn=linear_kernel)),
    ("RBF Kernel SVM (gamma=1.0)", DualKernelSVM(C=2.0, kernel_fn=lambda A, B: rbf_kernel(A, B, gamma=1.0))),
]

print(f"Dataset: {len(y_train)} training points, {len(y_test)} test points (concentric rings)\n")
for name, svm in models:
    svm.fit(X_train, y_train)
    tr_acc = float(np.mean(svm.predict(X_train) == y_train)) * 100.0
    te_acc = float(np.mean(svm.predict(X_test) == y_test)) * 100.0

    # KKT Support Vector Partition Audit
    n_non_sv = int(np.sum(svm.alpha <= 1e-5))
    n_free_sv = int(np.sum((svm.alpha > 1e-5) & (svm.alpha < svm.C - 1e-5)))
    n_bound_sv = int(np.sum(svm.alpha >= svm.C - 1e-5))

    print(f"=== {name} ===")
    print(f"  Train Accuracy : {tr_acc:.1f}% | Test Accuracy: {te_acc:.1f}%")
    print(
        f"  KKT Partition  : {n_non_sv} Non-SV (alpha=0) | "
        f"{n_free_sv} Free SV (0<alpha<C) | {n_bound_sv} Bounded SV (alpha=C)"
    )
    print(f"  Constraint sum(alpha_i y_i) = {np.dot(svm.alpha, y_train):+.2e}\n")

Ngajelaskeun Kiarana
#

Ngajalankeun ieu eksperimen ngahencangan tilu hasil teoretis inti sacara babarengan:

  1. Linear Failure vs. RBF Separation: Linear Kernel SVM nepi ka random chance (~50%) sabab teu aya garis lurus dina $\mathbb{R}^2$ anu bisa misahkeun concentric circles—maksa hampir unggal sampel ka bounded slack set ($\alpha_i = C$). Ngaganti ngan inner product ka RBF Kernel langsung nyorong training sareng test accuracy near 100% tanpa ngarobah hiji baris optimizer.
  2. Sparsity Verified Directly: Tina 160 training points, RBF SVM nembongkeun $\alpha_i = 0$ ka mayoritas overwhelming titik interior—ngajaga ngan sabaraha boundary points salaku Support Vectors pikeun ngagambarkeun sakabeh circular decision boundary.
  3. Exact Dual Feasibility: Dina sadaya coupled SMO update, equality constraint $\sum_{i=1}^{n} \alpha_i y_i = 0$ leres ka floating-point machine precision (~1e-16).

7. Wates & Jembatan ka Part 6
#

Kernel SVMs ngagambarkeun pinnacle tina convex geometric machine learning, sanajan dual formulation ngabogaan dua bottleneck struktural anu parah dina engineering tabular sareng skala ageung modern:

  1. Super-Linear Scaling in Sample Size $n$: Ngawangun sareng querying $n \times n$ Gram matrix peryogi $O(n^2)$ memory sareng waktos latihan $O(n^2)$ ka $O(n^3)$. Dina 10,000 sampel, RBF SVM gampang pisan; dina 10 miliun tabular records, Gram matrix sorangan meryogi ratusan terabytes.
  2. Sensitivity to Heterogeneous Tabular Features: Sabab Euclidean kernels sapertos RBF ngandelan isotropic distance $\Vert{}x - z\Vert{}_2^2$, ngagabung continuous sensors anu teu kaskala, skewed financial amounts, missing values, sareng high-cardinality categorical variables ngaruksak kernel geometry kecuali kalayan pamrosesan awal anu saksama.

Pikeun ngakawasan massive, messy, heterogeneous tabular datasets sareng fast axis-aligned splits sareng additive error correction, machine learning ngalangkungan inductive bias anu beda sampurna: recursive space partitioning sareng collaborative committees of weak learners.

Dina Part 6: Decision Trees & The Dominance of Ensemble Learning on Tabular Data, urang bakal mbedah Gini Impurity vs. Information Gain, ngajelaskeun sacara matematis naonkeun single trees ngalacak high variance, ngabuktikeun kumaha Bagging (Random Forests) nyumputkeun variance sambing Boosting (AdaBoost & Gradient Boosting) nyumputkeun bias, sareng nurunkeun second-order Hessian objective persis anu ngahasilkeun XGBoost juara tabular ML anu teu kalawan.


Rujukan
#

  1. Mercer, J. (1909). “Functions of Positive and Negative Type, and their Connection with the Theory of Integral Equations.” Philosophical Transactions of the Royal Society of London. Series A, 209(441–458), 415–446. (Characterization of positive-definite kernels).
  2. Aronszajn, N. (1950). “Theory of Reproducing Kernels.” Transactions of the American Mathematical Society, 68(3), 337–404. (Mathematical foundation of Reproducing Kernel Hilbert Spaces).
  3. Boser, B. E., Guyon, I. M., & Vapnik, V. N. (1992). “A Training Algorithm for Optimal Margin Classifiers.” Proceedings of the Fifth Annual Workshop on Computational Learning Theory (COLT 1992), 144–152. (Original introduction of the Kernel Trick in optimal-margin classifiers).
  4. Cortes, C., & Vapnik, V. (1995). “Support-Vector Networks.” Machine Learning, 20(3), 273–297. (Soft-margin SVM and slack-variable formulation).
  5. Platt, J. C. (1998). “Sequential Minimal Optimization: A Fast Algorithm for Training Support Vector Machines.” Microsoft Research Technical Report MSR-TR-98-14. (Exact two-variable analytical solver for Dual SVMs).
  6. Schölkopf, B., & Smola, A. J. (2002). Learning with Kernels: Support Vector Machines, Regularization, Optimization, and Beyond. MIT Press. (Comprehensive treatment of RKHS theory, Representer Theorem, and kernel design).
Dasar Machine Learning - Artikel ieu mangrupikeun bagian tina hiji séri.
Bagian 5: Artikel ieu