๐Ÿค–AI/ML

SVM

Support Vector Machine

A classification algorithm that finds the optimal decision boundary (hyperplane). Enables nonlinear classification with the kernel trick. A representative technique of traditional ML.

๐Ÿ“– Detailed Explanation

SVM (Support Vector Machine) is a supervised learning algorithm that finds the optimal hyperplane separating two classes. "Optimal" means maximizing the margin, that is, the distance between the decision boundary and the nearest data points. These nearest points are called Support Vectors, and the decision boundary is determined solely by these support vectors.

Developed in 1992 by Vladimir Vapnik and Corinna Cortes, it reigned as the most powerful classification algorithm in the pre-deep-learning era (2000-2012). It has a solid mathematical foundation based on statistical learning theory (VC dimension) and prevents overfitting through the principle of structural risk minimization (SRM). It works well even on high-dimensional data, which made it the standard for text classification. Even after the emergence of deep learning, it is still used on small datasets and in domains where interpretability is important.

The Kernel Trick is the key extension of SVM. It implicitly maps data that cannot be linearly separated in the original space into a higher (even infinite) dimensional space, making it separable. There are various kernels such as RBF (Radial Basis Function, Gaussian), Polynomial, and Sigmoid, and in practice, instead of performing high-dimensional computation, only the inner product is computed using the kernel function K(x_i, x_j). This trick, which removes the need to explicitly compute phi(x), is the secret to SVM's efficiency.

It is used in text classification (spam filters), image classification (face recognition), bioinformatics (gene expression analysis), and finance (fraud detection, credit scoring). It is particularly effective when the number of features exceeds the number of samples (p >> n, such as gene data). However, on large-scale data the training complexity grows to O(n^2~n^3), so for 100,000 samples or more, using LinearSVC or SGDClassifier is recommended.

๐Ÿ’ป Code Example

from sklearn import svm
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import classification_report

# ๋ฐ์ดํ„ฐ ์ƒ์„ฑ ๋ฐ ์ „์ฒ˜๋ฆฌ
X, y = make_classification(n_samples=1000, n_features=20, n_classes=2, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# ์Šค์ผ€์ผ๋ง (SVM์— ํ•„์ˆ˜!)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

# ๊ธฐ๋ณธ SVM (RBF ์ปค๋„)
svm_rbf = svm.SVC(kernel='rbf', C=1.0, gamma='scale')
svm_rbf.fit(X_train_scaled, y_train)

# ์„ ํ˜• SVM (๋Œ€๊ทœ๋ชจ ๋ฐ์ดํ„ฐ์— ์ ํ•ฉ)
svm_linear = svm.LinearSVC(C=1.0, max_iter=10000)
svm_linear.fit(X_train_scaled, y_train)

# ํ•˜์ดํผํŒŒ๋ผ๋ฏธํ„ฐ ํŠœ๋‹
param_grid = {
    'C': [0.1, 1, 10, 100],
    'gamma': ['scale', 'auto', 0.01, 0.1],
    'kernel': ['rbf', 'poly']
}

grid_search = GridSearchCV(
    svm.SVC(),
    param_grid,
    cv=5,
    scoring='accuracy',
    n_jobs=-1
)
grid_search.fit(X_train_scaled, y_train)

print(f"์ตœ์  ํŒŒ๋ผ๋ฏธํ„ฐ: {grid_search.best_params_}")
print(f"์ตœ์  ์ ์ˆ˜: {grid_search.best_score_:.4f}")

# ํ‰๊ฐ€
best_model = grid_search.best_estimator_
y_pred = best_model.predict(X_test_scaled)
print(classification_report(y_test, y_pred))

# ์„œํฌํŠธ ๋ฒกํ„ฐ ํ™•์ธ
print(f"์„œํฌํŠธ ๋ฒกํ„ฐ ์ˆ˜: {len(best_model.support_)}")
# ์„œํฌํŠธ ๋ฒกํ„ฐ๊ฐ€ ์ ์„์ˆ˜๋ก ์ผ๋ฐ˜ํ™” ์„ฑ๋Šฅ์ด ์ข‹์Œ

# === ๋Œ€๊ทœ๋ชจ ๋ฐ์ดํ„ฐ์šฉ SGD ๊ธฐ๋ฐ˜ SVM ===
from sklearn.linear_model import SGDClassifier

# hinge loss = ์„ ํ˜• SVM๊ณผ ๋™์ผ
sgd_svm = SGDClassifier(
    loss='hinge',           # SVM๊ณผ ๋™์ผํ•œ ์†์‹ค ํ•จ์ˆ˜
    penalty='l2',           # L2 ์ •๊ทœํ™”
    alpha=1e-4,             # ์ •๊ทœํ™” ๊ฐ•๋„ (1/C)
    max_iter=1000,
    tol=1e-3,
    random_state=42
)
sgd_svm.fit(X_train_scaled, y_train)

# 100๋งŒ ์ƒ˜ํ”Œ๋„ ๋น ๋ฅด๊ฒŒ ํ•™์Šต ๊ฐ€๋Šฅ!
print(f"SGD SVM ์ •ํ™•๋„: {sgd_svm.score(X_test_scaled, y_test):.4f}")

# === ๋‹ค์ค‘ ํด๋ž˜์Šค SVM ===
from sklearn.multiclass import OneVsRestClassifier

# SVM์€ ๊ธฐ๋ณธ์ ์œผ๋กœ ์ด์ง„ ๋ถ„๋ฅ˜์ด๋ฏ€๋กœ ๋‹ค์ค‘ ํด๋ž˜์Šค๋Š” One-vs-Rest ์‚ฌ์šฉ
multi_svm = OneVsRestClassifier(
    svm.SVC(kernel='rbf', C=1.0, gamma='scale')
)
# OneVsOneClassifier๋„ ๊ฐ€๋Šฅ (ํด๋ž˜์Šค ์Œ๋งˆ๋‹ค ๋ถ„๋ฅ˜๊ธฐ)

# === SVM ํšŒ๊ท€ (SVR) ===
from sklearn.svm import SVR

svr = SVR(kernel='rbf', C=100, gamma=0.1, epsilon=0.1)
# epsilon: ์˜ค์ฐจ ํ—ˆ์šฉ ๋ฒ”์œ„ (epsilon-tube)
svr.fit(X_train_scaled, y_train_regression)

# === ์ปค๋„ ํ•จ์ˆ˜ ์‹œ๊ฐํ™” ์ดํ•ด ===
# RBF ์ปค๋„: K(x,y) = exp(-gamma * ||x-y||^2)
# - gamma ๋†’์Œ: ๊ฒฐ์ • ๊ฒฝ๊ณ„ ๋ณต์žก (๊ณผ์ ํ•ฉ ์œ„ํ—˜)
# - gamma ๋‚ฎ์Œ: ๊ฒฐ์ • ๊ฒฝ๊ณ„ ๋ถ€๋“œ๋Ÿฌ์›€ (๊ณผ์†Œ์ ํ•ฉ ์œ„ํ—˜)

# Polynomial ์ปค๋„: K(x,y) = (gamma * x^T y + coef0)^degree
poly_svm = svm.SVC(kernel='poly', degree=3, coef0=1)

# === ๋ถˆ๊ท ํ˜• ๋ฐ์ดํ„ฐ ์ฒ˜๋ฆฌ ===
from sklearn.svm import SVC

# class_weight='balanced'๋กœ ์ž๋™ ๊ฐ€์ค‘์น˜ ์ ์šฉ
imbalanced_svm = SVC(
    kernel='rbf',
    class_weight='balanced',  # ์†Œ์ˆ˜ ํด๋ž˜์Šค์— ๋†’์€ ๊ฐ€์ค‘์น˜
    C=1.0
)
# ๋˜๋Š” ์ˆ˜๋™ ์„ค์ •: class_weight={0: 1, 1: 10}

# === ํ™•๋ฅ  ์ถœ๋ ฅ (probability=True) ===
prob_svm = SVC(kernel='rbf', probability=True)
prob_svm.fit(X_train_scaled, y_train)

# ์˜ˆ์ธก ํ™•๋ฅ  ์ถœ๋ ฅ (Platt scaling ์ ์šฉ)
probs = prob_svm.predict_proba(X_test_scaled)
print(f"ํด๋ž˜์Šค 0 ํ™•๋ฅ : {probs[0, 0]:.2f}")
print(f"ํด๋ž˜์Šค 1 ํ™•๋ฅ : {probs[0, 1]:.2f}")

# === ๊ฒฐ์ • ๊ฒฝ๊ณ„ ์‹œ๊ฐํ™” (2D) ===
import matplotlib.pyplot as plt
import numpy as np

def plot_decision_boundary(model, X, y):
    """SVM ๊ฒฐ์ • ๊ฒฝ๊ณ„ ์‹œ๊ฐํ™”"""
    h = 0.02
    x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                         np.arange(y_min, y_max, h))
    Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    plt.contourf(xx, yy, Z, alpha=0.4)
    plt.scatter(X[:, 0], X[:, 1], c=y, alpha=0.8)
    plt.title("SVM Decision Boundary")

# === ์ตœ์‹  ํ™œ์šฉ ์‚ฌ๋ก€ ===
# ๋”ฅ๋Ÿฌ๋‹ ์‹œ๋Œ€์—๋„ SVM์€ ์—ฌ์ „ํžˆ ์‚ฌ์šฉ๋จ:
# 1. ์ƒ๋ฌผ์ •๋ณดํ•™: ์œ ์ „์ž ๋ฐœํ˜„ ๋ฐ์ดํ„ฐ (ํ”ผ์ฒ˜ > ์ƒ˜ํ”Œ)
# 2. ํ…์ŠคํŠธ ๋ถ„๋ฅ˜: ์ŠคํŒธ ํ•„ํ„ฐ, ๊ฐ์„ฑ ๋ถ„์„ (TF-IDF + SVM)
# 3. ์ด์ƒ ํƒ์ง€: One-class SVM
# 4. ์•™์ƒ๋ธ”: SVM์„ base learner๋กœ ์‚ฌ์šฉ

# One-class SVM (์ด์ƒ ํƒ์ง€)
from sklearn.svm import OneClassSVM

anomaly_detector = OneClassSVM(nu=0.1, kernel='rbf')
anomaly_detector.fit(X_normal)  # ์ •์ƒ ๋ฐ์ดํ„ฐ๋งŒ์œผ๋กœ ํ•™์Šต
predictions = anomaly_detector.predict(X_test)  # -1: ์ด์ƒ, 1: ์ •์ƒ

# === SVM vs ๋”ฅ๋Ÿฌ๋‹ ์–ธ์ œ ์„ ํƒ? ===
# SVM์ด ์ข‹์€ ๊ฒฝ์šฐ:
# - ๋ฐ์ดํ„ฐ < 10,000 ์ƒ˜ํ”Œ
# - ํ”ผ์ฒ˜ > ์ƒ˜ํ”Œ ์ˆ˜ (๊ณ ์ฐจ์›)
# - ํ•ด์„ ๊ฐ€๋Šฅ์„ฑ ํ•„์š”
# - GPU ์—†๋Š” ํ™˜๊ฒฝ

# ๋”ฅ๋Ÿฌ๋‹์ด ์ข‹์€ ๊ฒฝ์šฐ:
# - ๋ฐ์ดํ„ฐ > 100,000 ์ƒ˜ํ”Œ
# - ์ด๋ฏธ์ง€, ํ…์ŠคํŠธ, ์‹œํ€€์Šค ๋ฐ์ดํ„ฐ
# - ๋ณต์žกํ•œ ๋น„์„ ํ˜• ํŒจํ„ด

๐Ÿ—ฃ๏ธ Say It Like This in Practice

๐Ÿ’ฌ In a Model Selection Discussion
"If you have fewer than 1,000 data points and lots of features, try SVM. Deep learning is likely to overfit, and SVM theoretically offers better generalization guarantees than Random Forest. Just run a grid search over C and gamma with an RBF kernel."
๐Ÿ’ฌ In an Interview
"SVM is an algorithm that finds the hyperplane that maximizes the margin. The kernel trick makes nonlinear classification possible, and in practice it doesn't perform the high-dimensional mapping but only computes the inner product of the kernel function. The gamma of the RBF kernel controls the flexibility of the decision boundary, and C controls the trade-off between margin errors and margin size."
๐Ÿ’ฌ In Solving Performance Problems
"If SVM training takes too long, switch to LinearSVC or use SGDClassifier with hinge loss. With 100,000 samples or more, a kernel SVM is realistically difficult, and approximate kernels (Nystrom, Random Fourier Features) or deep learning are better."

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

โš ๏ธ Common Mistakes & Cautions

โŒ
Skipping feature scaling

SVM is distance-based, so it is sensitive to feature scale. Be sure to normalize with StandardScaler or MinMaxScaler.

โŒ
Using a kernel SVM on large-scale data

The training complexity of a kernel SVM is O(n^2~n^3). With 100,000 samples or more, use LinearSVC or SGDClassifier.

โœ…
The right way

Be sure to tune C and gamma with cross-validation. If C is too large, it overfits; if gamma is too large, the decision boundary becomes complex and overfits.

๐Ÿ”— Related Terms

๐Ÿ“š Learn More