Clasificador de margen máximo: vectores de soporte e hiperplano
Visualice la maximización del margen en un conjunto de datos bidimensional sencillo, identifique los vectores de soporte y comprenda por qué el margen máximo mejora la generalización.
Clasificador de margen máximo: vectores de soporte e hiperplano es una lección gratuita de Machine Learning Academy en CoddyKit. Esta es la lección 1 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Machine Learning Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Machine Learning Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en 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.
Preguntas frecuentes
¿La lección «Clasificador de margen máximo: vectores de soporte e hiperplano» es gratis?
Sí — el texto completo de «Clasificador de margen máximo: vectores de soporte e hiperplano» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Machine Learning Academy, actualiza a CoddyKit PRO. El curso de Machine Learning Academy incluye 4 lecciones en total.
¿Qué aprenderé en «Clasificador de margen máximo: vectores de soporte e hiperplano»?
Visualice la maximización del margen en un conjunto de datos bidimensional sencillo, identifique los vectores de soporte y comprenda por qué el margen máximo mejora la generalización. Practicas Machine Learning Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Machine Learning Academy?
No se requiere experiencia previa. Machine Learning Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 1 de 4.
¿Cuánto tiempo toma la lección «Clasificador de margen máximo: vectores de soporte e hiperplano»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Machine Learning Academy?
Sí. Cada lección de Machine Learning Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Clasificador de margen máximo: vectores de soporte e hiperplano
- SVM de margen blando y parámetro C
- El truco del kernel: kernels RBF, polinómico y sigmoide
- Ajuste de C y gamma mediante búsqueda en cuadrícula