๐ก๏ธ Maximized Margins & High-Dimensional Kernel Transformations
Support Vector Machines (SVMs) are among the most robust and versatile supervised learning models for classification and regression. Unlike models that evaluate all data points equally, SVMs find the optimal decision boundary (hyperplane) that maximizes the margin between different classes, relying strictly on critical boundary instances called Support Vectors. For complex non-linear data, SVMs leverage the Kernel Trick to implicitly project data into higher-dimensional spaces without computational explosion. This guide covers 10 real-world engineering patterns for SVMs and kernels.
import numpy as np
from sklearn.svm import SVC
def run_max_margin():
print("=" * 65)
print("๐ก๏ธ EXAMPLE 1: MAXIMUM MARGIN HYPERPLANE INTUITION")
print("=" * 65)
# Linearly separable features
X = np.array([[1, 2], [2, 3], [3, 3], [6, 5], [7, 8], [8, 8]])
y = np.array([0, 0, 0, 1, 1, 1])
# Linear SVM with large C for hard margin
clf = SVC(kernel='linear', C=1000.0)
clf.fit(X, y)
print(f"Hyperplane Coefficients (Weights w) : {np.round(clf.coef_[0], 4)}")
print(f"Hyperplane Intercept (Bias b) : {clf.intercept_[0]:.4f}")
print("=" * 65)
if __name__ == "__main__":
run_max_margin()
import numpy as np
from sklearn.svm import SVC
def extract_support_vectors():
print("=" * 65)
print("๐ EXAMPLE 2: EXTRACTING SUPPORT VECTORS")
print("=" * 65)
X = np.array([[1, 1], [2, 2], [2, 0], [8, 8], [9, 9], [8, 10]])
y = np.array([0, 0, 0, 1, 1, 1])
clf = SVC(kernel='linear', C=1.0)
clf.fit(X, y)
print(f"Total Training Samples : {len(X)}")
print(f"Support Vectors Count : {len(clf.support_vectors_)}")
print(f"Support Vector Indices : {clf.support_}")
print(f"Support Vector Points :\n{clf.support_vectors_}")
print("=" * 65)
if __name__ == "__main__":
extract_support_vectors()
import numpy as np
from sklearn.svm import SVC
def demonstrate_c_parameter():
print("=" * 65)
print("โ๏ธ EXAMPLE 3: SOFT MARGIN & REGULARIZATION PARAMETER (C)")
print("=" * 65)
# Overlapping noisy dataset
X = np.array([[1, 1], [1.5, 1.5], [2, 2], [2.1, 1.9], [3, 3]])
y = np.array([0, 0, 0, 1, 1]) # Note the overlap around [2.1, 1.9]
# High C = Strict margin (penalizes misclassifications heavily)
clf_strict = SVC(kernel='linear', C=100.0)
clf_strict.fit(X, y)
# Low C = Wide margin (allows more margin violations)
clf_wide = SVC(kernel='linear', C=0.01)
clf_wide.fit(X, y)
print(f"Support Vectors (Strict C=100) : {len(clf_strict.support_vectors_)}")
print(f"Support Vectors (Wide C=0.01) : {len(clf_wide.support_vectors_)}")
print("=" * 65)
if __name__ == "__main__":
demonstrate_c_parameter()
import numpy as np
def simulate_kernel_mapping():
print("=" * 65)
print("๐ฎ EXAMPLE 4: THE KERNEL TRICK FEATURE TRANSFORMATION")
print("=" * 65)
# 2D point [x1, x2] in circular distribution
x1, x2 = 3.0, 4.0
# Kernel mapping function phi(x) = [x1, x2, x1^2 + x2^2]
r_squared = x1**2 + x2**2
mapped_feature = np.array([x1, x2, r_squared])
print(f"Original 2D Feature Vector : [{x1}, {x2}]")
print(f"Mapped 3D Feature Vector : {mapped_feature.tolist()}")
print("Explanation: In 3D space, height (x1^2 + x2^2) separates inner and outer concentric circles.")
print("=" * 65)
if __name__ == "__main__":
simulate_kernel_mapping()
import numpy as np
from sklearn.svm import SVC
def run_rbf_svm():
print("=" * 65)
print("๐ EXAMPLE 5: RADIAL BASIS FUNCTION (RBF) KERNEL")
print("=" * 65)
# Non-linear XOR / concentric dataset
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1], [0.5, 0.5]])
y = np.array([0, 1, 1, 0, 0])
rbf_clf = SVC(kernel='rbf', gamma='scale', C=1.0)
rbf_clf.fit(X, y)
predictions = rbf_clf.predict(X)
print(f"True Labels : {y.tolist()}")
print(f"RBF Predictions : {predictions.tolist()}")
print(f"Support Vectors :\n{rbf_clf.support_vectors_}")
print("=" * 65)
if __name__ == "__main__":
run_rbf_svm()
import numpy as np
from sklearn.svm import SVC
def run_poly_svm():
print("=" * 65)
print("๐ EXAMPLE 6: POLYNOMIAL KERNEL FEATURE INTERACTIONS")
print("=" * 65)
X = np.array([[1, 2], [2, 1], [3, 3], [4, 4]])
y = np.array([0, 0, 1, 1])
poly_clf = SVC(kernel='poly', degree=3, coef0=1.0, C=1.0)
poly_clf.fit(X, y)
print(f"Polynomial Degree 3 SVM Trained Successfully.")
print(f"Number of Support Vectors: {len(poly_clf.support_vectors_)}")
print("=" * 65)
if __name__ == "__main__":
run_poly_svm()
import numpy as np
from sklearn.svm import SVR
def run_svr():
print("=" * 65)
print("๐ EXAMPLE 7: SUPPORT VECTOR REGRESSION (SVR)")
print("=" * 65)
np.random.seed(42)
X = np.sort(5 * np.random.rand(40, 1), axis=0)
y = np.sin(X).ravel() + np.random.normal(0, 0.1, X.shape[0])
svr = SVR(kernel='rbf', C=100.0, gamma=0.1, epsilon=0.1)
svr.fit(X, y)
predictions = svr.predict([[2.5], [4.0]])
print(f"SVR Predictions for x=2.5 and x=4.0 : {np.round(predictions, 4)}")
print(f"Number of Support Vectors in SVR : {len(svr.support_vectors_)}")
print("=" * 65)
if __name__ == "__main__":
run_svr()
import numpy as np
from sklearn.svm import SVC
def demonstrate_gamma():
print("=" * 65)
print("๐ฏ EXAMPLE 8: GAMMA PARAMETER TUNING (OVERFITTING VS UNDERFITTING)")
print("=" * 65)
X = np.array([[1, 1], [2, 2], [5, 5], [6, 6]])
y = np.array([0, 0, 1, 1])
# High Gamma = Complex islands around every point (High Variance / Overfitting)
clf_high_gamma = SVC(kernel='rbf', gamma=50.0)
clf_high_gamma.fit(X, y)
# Low Gamma = Broad smooth boundary (High Bias / Underfitting)
clf_low_gamma = SVC(kernel='rbf', gamma=0.001)
clf_low_gamma.fit(X, y)
print(f"Support Vectors (Gamma=50.0) : {len(clf_high_gamma.support_vectors_)}")
print(f"Support Vectors (Gamma=0.001): {len(clf_low_gamma.support_vectors_)}")
print("=" * 65)
if __name__ == "__main__":
demonstrate_gamma()
StandardScaler with SVC inside an automated hyperparameter search (`GridSearchCV`).
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV
def run_svm_pipeline():
print("=" * 65)
print("๐ค EXAMPLE 9: SVM PIPELINE & GRIDSEARCHCV HYPERPARAMETER TUNING")
print("=" * 65)
np.random.seed(42)
X = np.random.randn(150, 4)
y = np.random.randint(0, 2, 150)
# Construct ML Pipeline
pipeline = Pipeline([
('scaler', StandardScaler()),
('svc', SVC(kernel='rbf'))
])
# Hyperparameter Grid
param_grid = {
'svc__C': [0.1, 1.0, 10.0],
'svc__gamma': ['scale', 0.01, 0.1]
}
grid = GridSearchCV(pipeline, param_grid, cv=3)
grid.fit(X, y)
print(f"Best Hyperparameters Found : {grid.best_params_}")
print(f"Best Cross-Validation Acc : {grid.best_score_ * 100:.2f}%")
print("=" * 65)
if __name__ == "__main__":
run_svm_pipeline()
SUPPORT VECTOR MACHINES & KERNELS REFERENCE MATRIX:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Concept / Parameter โ Mathematical Role โ Primary Machine Learning Application โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Maximum Margin Hyperplane โ w^T * x + b = 0 โ Finding optimal decision boundary with widest margin โ
โ Support Vectors โ Critical boundary instances โ Defining the hyperplane; non-SV points are discarded โ
โ Regularization Parameter (C) โ Margin vs error penalty โ Controlling soft margin tolerance (high C = strict) โ
โ Kernel Trick โ K(x, x') = <ฯ(x), ฯ(x')> โ Implicitly mapping non-linear data to higher dimensions โ
โ RBF (Gaussian) Kernel โ exp(-ฮณ ||x - x'||ยฒ) โ Complex non-linear circular or multi-island boundaries โ
โ Polynomial Kernel โ (ฮณ + r)^d โ Modeling feature interactions up to degree d โ
โ SVR (Support Vector Reg) โ ฮต-insensitive tube fitting โ Continuous target regression tasks โ
โ Gamma Parameter (ฮณ) โ RBF influence radius โ Tuning radius of support vector influence (overfitting) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ ENGINEERING BEST PRACTICES: โ
โ 1. Always apply StandardScaler before training SVMs since distance calculations depend heavily on feature scales. โ
โ 2. Use RBF kernel as a default for non-linear problems, tuning C and gamma via GridSearchCV. โ
โ 3. Be aware that SVM training scales between $O(N^2)$ and $O(N^3)$, making it computationally demanding for massive N.โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ