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
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
