Loss function of SVM
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 margin-maximizing regularization term. For labels and raw decision score , the per-sample hinge loss is:
and the unconstrained soft-margin SVM objective is:
Hinge loss equals whenever (on or beyond the correct margin boundary), and increases linearly once an instance violates the margin or is misclassified. Only points with contribute non-zero gradients or dual coefficients—these are the support vectors.
Key Terms
- Hinge Loss: , a convex, piecewise-linear upper bound on – classification loss used for maximum-margin classification.
- Margin: The band around the hyperplane bounded by , of total width .
- Support Vectors: Training points on or inside the margin () that define the decision boundary.
- Regularization Parameter (): Balances margin maximization () against hinge loss penalties; larger penalizes margin violations more heavily.
- Slack Variables (): Equal to at optimality, measuring each sample’s margin violation.
Example
Consider a binary classifier with labels . A positive sample () with decision score lies well past the margin boundary and incurs loss. A correctly classified sample closer to the boundary with violates the margin and incurs . A misclassified sample with incurs . Increasing penalizes those violations more aggressively, producing a narrower margin that risks overfitting noise, whereas smaller 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}")
Related Concepts
- Kernel Trick: In dual form, the -regularized hinge loss depends only on pairwise dot products , allowing substitution of positive semi-definite kernels for non-linear boundaries.
- Dual Problem & Sparsity: Complementary slackness in the KKT conditions implies for all samples strictly outside the margin (), giving sparse support-vector solutions.
- Squared Hinge Loss: Uses , 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.