0Pricing
Machine Learning Academy · Aula

Classificador de margem máxima: vetores de suporte e hiperplano

Visualize a maximização da margem em um conjunto de dados 2D simples, identifique os vetores de suporte e entenda por que a margem máxima melhora a generalização.

Classificador de margem máxima: vetores de suporte e hiperplano é uma aula grátis de Machine Learning Academy no CoddyKit. Esta é a aula 1 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Machine Learning Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Machine Learning Academy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

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.

Perguntas Frequentes

A aula “Classificador de margem máxima: vetores de suporte e hiperplano” é grátis?

Sim — o texto completo de “Classificador de margem máxima: vetores de suporte e hiperplano” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Machine Learning Academy, atualize para CoddyKit PRO. O curso de Machine Learning Academy inclui 4 aulas no total.

O que vou aprender em “Classificador de margem máxima: vetores de suporte e hiperplano”?

Visualize a maximização da margem em um conjunto de dados 2D simples, identifique os vetores de suporte e entenda por que a margem máxima melhora a generalização. Você pratica Machine Learning Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Machine Learning Academy?

Nenhuma experiência prévia é necessária. Machine Learning Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 1 de 4.

Quanto tempo leva a aula “Classificador de margem máxima: vetores de suporte e hiperplano”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Machine Learning Academy?

Sim. Cada aula de Machine Learning Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Classificador de margem máxima: vetores de suporte e hiperplano
  2. SVM de margem suave e o parâmetro C
  3. O truque do kernel: kernels RBF, polinomial e sigmoide
  4. Ajuste de C e gamma com uma busca em grade
← Voltar para Machine Learning Academy