최대 마진 분류기: 서포트 벡터와 초평면
2차원 예제 데이터세트에서 마진 최대화를 시각화하고, 서포트 벡터를 식별하며, 최대 마진이 일반화 성능을 높이는 이유를 이해합니다.
최대 마진 분류기: 서포트 벡터와 초평면은(는) CoddyKit의 무료 Machine Learning Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Machine Learning Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Machine Learning Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
The Core Idea of SVMs
Support Vector Machines (SVMs) are classifiers that find the best separating boundary between two classes. When multiple boundaries can separate the classes, which one should you choose? The SVM's answer is elegant: pick the boundary that is as far as possible from every training example. This maximally distant boundary is called the maximum-margin hyperplane, and SVM's theoretical foundations guarantee that it generalises better to unseen data than arbitrary separating boundaries.
What Is a Hyperplane?
In 2D, a hyperplane is a line (1 dimension less than the data space). In 3D, it is a plane. In general p-dimensional space, it is a (p-1)-dimensional flat surface defined by the equation w·x + b = 0, where w is the normal vector (perpendicular to the surface), x is the input feature vector, and b is the bias term. Points on one side satisfy w·x + b > 0 (predicted positive class) and points on the other satisfy w·x + b < 0 (predicted negative class).
Margin: The Gap Between Classes
The margin is the distance between the decision boundary and the closest training examples from each class. The SVM defines two margin hyperplanes parallel to the decision boundary: w·x + b = +1 for the positive class boundary and w·x + b = -1 for the negative class boundary. The total margin width is 2 / ||w||. To maximise the margin, the SVM minimises ||w|| (equivalently, ||w||²/2 for mathematical convenience) subject to the constraint that all points are correctly classified.
Support Vectors: The Critical Examples
Support vectors are the training examples that lie exactly on the margin hyperplanes (where w·x + b = ±1). They are the only examples that determine the position and orientation of the decision boundary. All other training examples — those farther from the boundary — play no role in defining it. This is a profound insight: the SVM decision boundary is entirely defined by a small subset of the training data, making it robust to the majority of the training set.
from sklearn.svm import SVC
from sklearn.datasets import make_classification
import numpy as np
X, y = make_classification(n_samples=50, n_features=2, n_informative=2,
n_redundant=0, random_state=42)
svm = SVC(kernel='linear', C=1.0)
svm.fit(X, y)
print('Number of support vectors:', svm.n_support_)
print('Support vector indices:', svm.support_[:5])
print('Total training examples:', len(X))Training a Linear SVM with scikit-learn
Use sklearn.svm.SVC with kernel='linear' for a linear maximum-margin classifier. After fitting, the decision function score for a point is its signed distance to the decision boundary — positive for class 1, negative for class 0. The decision_function() method returns these raw scores, while predict() applies the sign threshold to produce class labels.
from sklearn.svm import SVC
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# StandardScaler is essential — SVM is sensitive to feature scales
model = make_pipeline(StandardScaler(), SVC(kernel='linear', C=1.0))
model.fit(X_train, y_train)
print('Test accuracy:', model.score(X_test, y_test))Why Scale Features Before SVM
SVMs compute distances between points and the hyperplane using the dot product w·x. If one feature ranges from 0 to 1 and another from 0 to 1,000,000, the large-scale feature will dominate the distance calculation, causing the SVM to almost ignore the small-scale feature. Always apply StandardScaler (or MinMaxScaler) before training an SVM. This is one of the most common mistakes beginners make — even a perfect hyperplane can fail if features are not scaled.
Geometric Intuition for Maximum Margin
Imagine placing a road between two rows of trees (classes). The road's center is the decision boundary, and its width is the margin. You want to build the widest road that still fits between the trees without hitting any of them. The trees closest to the road are the support vectors. A wider road is better because it has more tolerance — a new tree can be placed anywhere within the road's width and still be on the correct side of the boundary.
The Dual Formulation and Kernel Trick Preview
SVMs can be trained in two equivalent ways: the primal form (optimise over w and b directly) and the dual form (optimise over a set of Lagrange multipliers, one per training example). The dual form is significant because the optimisation only involves dot products between training examples. Replacing these dot products with a kernel function implicitly maps data to a higher-dimensional space without computing the coordinates explicitly — this is the famous kernel trick that enables non-linear SVMs.
Decision Function and Distance to Boundary
The SVM decision_function() returns the signed distance from each point to the decision hyperplane. Points with large positive scores are confidently in the positive class; large negative scores indicate the negative class. Points near zero are close to the boundary and represent the most uncertain predictions. Monitoring the distribution of decision function scores on a new dataset is a useful diagnostic — if most scores cluster near zero, the model may be poorly suited to the data.
from sklearn.svm import SVC
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
import numpy as np
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = make_pipeline(StandardScaler(), SVC(kernel='linear', C=1.0))
model.fit(X_train, y_train)
scores = model.decision_function(X_test)
print('Decision function range:', np.round([scores.min(), scores.max()], 3))
print('Near-boundary (|score|<1):', np.sum(np.abs(scores) < 1))Hard Margin vs Real Data
The maximum-margin formulation described so far is the hard margin SVM, which requires perfect linear separability — no training point can violate the margin. Real-world data is almost never perfectly linearly separable due to noise and overlapping class distributions. Applying a hard-margin SVM to such data will fail (the optimisation has no feasible solution). The practical solution is the soft-margin SVM, introduced in the next lesson, which allows some margin violations controlled by a penalty parameter C.
Multi-Class SVMs: One-vs-One
The basic SVM formulation handles binary classification. For multi-class problems, scikit-learn's SVC uses a one-vs-one strategy by default: it trains k(k-1)/2 binary classifiers, one for each pair of classes, and predicts the class that wins the most pairwise votes. For 10 classes, this means 45 binary classifiers. An alternative is one-vs-rest (via LinearSVC), which trains k binary classifiers, each distinguishing one class from all others. One-vs-one is generally more accurate but slower for many classes.
from sklearn.svm import SVC
from sklearn.datasets import load_iris
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
X, y = load_iris(return_X_y=True) # 3 classes
model = make_pipeline(StandardScaler(), SVC(kernel='linear', decision_function_shape='ovo'))
scores = cross_val_score(model, X, y, cv=5)
print('Multi-class SVM (OVO) CV:', scores.mean().round(4))Quick Check
Test your understanding of the Maximum Margin Classifier from this lesson.
Lesson Recap
In this lesson you learned: SVMs find the maximum-margin hyperplane separating two classes, support vectors are the critical examples on the margin that define the boundary, and feature scaling is essential before training an SVM. Next up we explore the soft-margin SVM and the C parameter that allows controlled margin violations.
자주 묻는 질문
“최대 마진 분류기: 서포트 벡터와 초평면” 강의는 무료인가요?
네 — “최대 마진 분류기: 서포트 벡터와 초평면” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Machine Learning Academy 강의 전체를 잠금 해제할 수 있습니다. Machine Learning Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“최대 마진 분류기: 서포트 벡터와 초평면”에서 뭘 배우나요?
2차원 예제 데이터세트에서 마진 최대화를 시각화하고, 서포트 벡터를 식별하며, 최대 마진이 일반화 성능을 높이는 이유를 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 Machine Learning Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Machine Learning Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Machine Learning Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“최대 마진 분류기: 서포트 벡터와 초평면” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Machine Learning Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Machine Learning Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 최대 마진 분류기: 서포트 벡터와 초평면
- 소프트 마진 SVM과 C 매개변수
- 커널 기법: RBF, 다항식, 시그모이드 커널
- 그리드 검색으로 C와 감마 조정