Python / Python Mathematical Intuition and Scikit Learn Interview Questions
What is the mathematical concept of the margin in Support Vector Machines, and why does maximizing it improve generalization?
A linear SVM finds the hyperplane wᵀx + b = 0 that separates two classes while maximising the margin — the distance between the hyperplane and the nearest points from either class. This distance for a normalised hyperplane is 2/‖w‖, so maximising the margin is equivalent to minimising ‖w‖² subject to the constraint that all points are correctly classified with a margin of at least 1: yᵢ(wᵀxᵢ + b) ≥ 1.
The points that lie exactly on the margin boundary are called support vectors — they are the only points that determine the position of the decision boundary; all other points could be moved or removed without changing the solution. Maximising the margin is a form of structural risk minimisation: a wider margin means the decision boundary has more room before misclassifying nearby unseen points, which translates to better generalisation (related to VC-dimension theory bounding generalisation error by margin size).
from sklearn.svm import SVC import numpy as np svm = SVC(kernel='linear', C=1.0) svm.fit(X_train, y_train) # Support vectors â the points that define the margin print('Number of support vectors:', len(svm.support_vectors_)) print('Support vector indices:', svm.support_) # The decision boundary: w.x + b = 0 w = svm.coef_[0] b = svm.intercept_[0] margin_width = 2 / np.linalg.norm(w) print(f'Margin width: {margin_width:.4f}') # C controls the tradeoff between margin width and misclassification: # Small C: wider margin, more tolerance for misclassified points (soft margin) # Large C: narrower margin, less tolerance â can overfit
More Related questions...