Skip to content
E
Educatum

Loss function of SVM

Curated by Educatum AI teamLast updated:
Model EvaluationLoss
Direct Answer

Support Vector Machines optimize an L2-regularized hinge loss objective. Hinge loss is zero for any sample classified on the correct side of the margin with functional margin at least 1, and grows linearly for points inside the margin or on the wrong side of the decision boundary, focusing optimization on the support vectors.

Study Card: Loss Function of SVM

Direct Answer

The loss function of a soft-margin Support Vector Machine (SVM) is hinge loss combined with an L2L_2 margin-maximizing regularization term. For labels yi∈{−1,+1}y_i \in \{-1, +1\} and raw decision score f(xi)=wTxi+bf(x_i) = w^T x_i + b, the per-sample hinge loss is:

ℓhinge(yi,f(xi))=max⁡(0,1−yif(xi))\ell_{\text{hinge}}(y_i, f(x_i)) = \max\big(0, 1 - y_i f(x_i)\big)

and the unconstrained soft-margin SVM objective is:

min⁡w,b12∥w∥22+C∑i=1nmax⁡(0,1−yi(wTxi+b))\min_{w, b} \frac{1}{2}\|w\|_2^2 + C \sum_{i=1}^{n} \max\big(0, 1 - y_i(w^T x_i + b)\big)

Hinge loss equals 00 whenever yif(xi)≥1y_i f(x_i) \ge 1 (on or beyond the correct margin boundary), and increases linearly once an instance violates the margin or is misclassified. Only points with yif(xi)≤1y_i f(x_i) \le 1 contribute non-zero gradients or dual coefficients—these are the support vectors.

Key Terms

  • Hinge Loss: max⁡(0,1−yf(x))\max(0, 1 - y f(x)), a convex, piecewise-linear upper bound on 00–11 classification loss used for maximum-margin classification.
  • Margin: The band around the hyperplane wTx+b=0w^T x + b = 0 bounded by wTx+b=±1w^T x + b = \pm 1, of total width 2∥w∥2\frac{2}{\|w\|_2}.
  • Support Vectors: Training points on or inside the margin (yif(xi)≤1y_i f(x_i) \le 1) that define the decision boundary.
  • Regularization Parameter (CC): Balances margin maximization (12∥w∥22\frac{1}{2}\|w\|_2^2) against hinge loss penalties; larger CC penalizes margin violations more heavily.
  • Slack Variables (ξi\xi_i): Equal to max⁡(0,1−yi(wTxi+b))\max(0, 1 - y_i(w^T x_i + b)) at optimality, measuring each sample’s margin violation.

Example

Consider a binary classifier with labels {−1,+1}\{-1, +1\}. A positive sample (y=+1y = +1) with decision score f(x)=+1.5f(x) = +1.5 lies well past the margin boundary and incurs max⁡(0,1−1.5)=0\max(0, 1 - 1.5) = 0 loss. A correctly classified sample closer to the boundary with f(x)=+0.6f(x) = +0.6 violates the margin and incurs max⁡(0,1−0.6)=0.4\max(0, 1 - 0.6) = 0.4. A misclassified sample with f(x)=−1.2f(x) = -1.2 incurs max⁡(0,1−(−1.2))=2.2\max(0, 1 - (-1.2)) = 2.2. Increasing CC penalizes those violations more aggressively, producing a narrower margin that risks overfitting noise, whereas smaller CC permits a wider margin.

Code Implementation

import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
from sklearn.datasets import make_blobs

# Generate sample classification data
X, y = make_blobs(n_samples=100, centers=2, random_state=6)

# Fit linear SVMs with different regularization parameters
clf1 = svm.SVC(kernel='linear', C=1)    # Smaller C: wider margin, tolerates violations
clf1.fit(X, y)

clf2 = svm.SVC(kernel='linear', C=100)  # Larger C: narrower margin, stricter penalty
clf2.fit(X, y)

def plot_decision_boundary(clf, X, y):
    ax = plt.gca()
    # Scatter data first so axis limits cover the data points
    ax.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Paired)
    xlim = ax.get_xlim()
    ylim = ax.get_ylim()

    # Evaluate decision function over grid
    xx = np.linspace(xlim[0], xlim[1], 30)
    yy = np.linspace(ylim[0], ylim[1], 30)
    YY, XX = np.meshgrid(yy, xx)
    xy = np.vstack([XX.ravel(), YY.ravel()]).T
    Z = clf.decision_function(xy).reshape(XX.shape)

    # Plot decision boundary and margins
    ax.contour(XX, YY, Z, colors='k', levels=[-1, 0, 1], alpha=0.5, linestyles=['--', '-', '--'])
    ax.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=100,
               facecolors='none', edgecolors='k', label='Support Vectors')

plt.figure(figsize=(10, 5))

plt.subplot(1, 2, 1)
plot_decision_boundary(clf1, X, y)
plt.title("SVM with C = 1")

plt.subplot(1, 2, 2)
plot_decision_boundary(clf2, X, y)
plt.title("SVM with C = 100")

plt.tight_layout()
plt.show()

def hinge_loss(y_true, y_scores):
    """
    Calculates mean hinge loss.

    Args:
      y_true: True binary labels (-1 or +1).
      y_scores: Raw decision function scores w^T x + b (not binary class labels).

    Returns:
      Mean hinge loss.
    """
    return np.mean(np.maximum(0, 1 - y_true * y_scores))

# Example usage with dummy decision scores
y_true_example = np.array([-1, 1, 1, -1])
y_scores_example = np.array([-0.5, 1.5, 0.8, -1.2])

loss = hinge_loss(y_true_example, y_scores_example)
print(f"Hinge Loss Example: {loss:.4f}")
  • Kernel Trick: In dual form, the L2L_2-regularized hinge loss depends only on pairwise dot products ⟨xi,xj⟩\langle x_i, x_j \rangle, allowing substitution of positive semi-definite kernels K(xi,xj)K(x_i, x_j) for non-linear boundaries.
  • Dual Problem & Sparsity: Complementary slackness in the KKT conditions implies αi=0\alpha_i = 0 for all samples strictly outside the margin (yif(xi)>1y_i f(x_i) > 1), giving sparse support-vector solutions.
  • Squared Hinge Loss: Uses max⁡(0,1−yf(x))2\max(0, 1 - y f(x))^2, which is continuously differentiable (smooth) and penalizes large margin errors quadratically.
  • Comparison with Log Loss & Exponential Loss: Log loss (logistic regression) never reaches zero even for correctly classified points far from the boundary and yields calibrated probabilities; exponential loss (AdaBoost) grows exponentially for negative margins and is much more sensitive to label noise/outliers.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.