Python / Python Mathematical Intuition and Scikit Learn Interview Questions
What is the kernel trick in SVMs and why does it avoid explicitly computing high-dimensional feature mappings?
Many datasets are not linearly separable in their original feature space but become separable after mapping to a higher-dimensional space via some function φ(x). Computing this mapping explicitly (especially for infinite-dimensional mappings like the RBF kernel implies) would be computationally infeasible. The kernel trick exploits the fact that SVM's optimisation and prediction only ever require the dot product φ(xᵢ)ᵀφ(xⱼ) between mapped points — never the mapped vectors themselves.
A kernel function K(xᵢ, xⱼ) computes this dot product directly in the original space, without ever materialising φ(x). The RBF (Gaussian) kernel K(xᵢ, xⱼ) = exp(-γ‖xᵢ - xⱼ‖²) implicitly corresponds to an infinite-dimensional feature mapping, yet evaluating it costs the same as a simple distance computation — this is the mathematical magic of the kernel trick.
from sklearn.svm import SVC
from sklearn.datasets import make_circles
# Data that is NOT linearly separable in 2D
X, y = make_circles(n_samples=200, noise=0.05, factor=0.3)
# Linear kernel fails on this data
linear_svm = SVC(kernel='linear').fit(X, y)
print('Linear SVM accuracy:', linear_svm.score(X, y)) # poor
# RBF kernel implicitly maps to higher dimensions, separates easily
rbf_svm = SVC(kernel='rbf', gamma='scale').fit(X, y)
print('RBF SVM accuracy:', rbf_svm.score(X, y)) # much better
# gamma controls the 'reach' of each training example's influence
# Small gamma: smoother decision boundary (far-reaching influence)
# Large gamma: tighter decision boundary around each point (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...
