← back

Calculate SVM Margin Width

#282 · Machine Learning · Easy

⊣ Solve on deep-ml.com

Problem

Calculate the margin width of a Support Vector Machine given the weight vector w. The SVM margin width is defined as 2 / ||w||, where ||w|| is the L2 norm of the weight vector.

Solution

1
2
3
4
5
import numpy as np

def svm_margin_width(w: np.ndarray) -> float:
    norm_w = np.linalg.norm(w)
    return 2.0 / norm_w

Explanation

  1. Compute the L2 (Euclidean) norm of the weight vector w: ||w|| = sqrt(sum(w_i^2)).
  2. The margin width is 2 / ||w||. A larger margin means better generalization. SVMs maximize this margin during training.

Complexity

  • Time: O(n) where n is the dimensionality of w
  • Space: O(1)