Two ways to classify the same points
Picture a scatterplot where blue points represent one class and orange points another. A new point appears. How should a program classify it?
A k-nearest neighbors (KNN) classifier asks: “Which labeled training points are closest to this new point?” It predicts from those nearby examples. The model largely defers computation until a new prediction arrives.
A support vector machine (SVM) asks a different question during training: “Can we find a boundary that separates the classes with a large margin?” In a basic linear SVM, only some training points, called support vectors, determine the final boundary. Kernel methods can create nonlinear boundaries by expressing similarity in a different feature space.
These approaches highlight a practical concern: distance and geometry depend on feature scales. If one variable is measured in thousands and another in fractions, the first may dominate distance calculations unless you scale appropriately. This is particularly important for KNN and many SVM settings.
By the end of the article, distinguish local-neighbor reasoning from margin-based boundary learning, and know when each method may struggle.
Support Vector Machines (SVMs) and k-Nearest Neighbors (k-NN) are two established methods for supervised machine learning. Both can classify observations, but they answer different questions. An SVM asks, What decision boundary separates the classes with a useful margin? k-NN asks, Which labeled training examples are closest to this new observation?
This distinction affects training, prediction speed, memory use, interpretability, and sensitivity to feature scaling. Both methods can be valuable baselines before adopting more complex systems.
1. Classification as a geometric problem
Suppose each observation has two numerical features, such as a device’s temperature and vibration level. Each observation is a point in a two-dimensional feature space. With features, an observation is represented by a vector .
In classification, the model assigns an observation to one of a defined set of classes. A decision boundary separates regions that receive different predictions. Some boundaries are straight lines or hyperplanes; others are curved or irregular.
A classifier must do more than fit the training data. The goal is to predict reliably for new observations drawn from the intended population. This is called generalization.
2. What is a Support Vector Machine?
Definition: A Support Vector Machine is a supervised learning method that constructs a decision boundary using a maximum-margin principle. For classification, it seeks a boundary that separates classes while controlling errors and model complexity.
For a linear SVM, the decision boundary is a hyperplane:
Here:
- is the input feature vector.
- determines the boundary’s orientation.
- shifts the boundary.
- The sign of gives the predicted side of the boundary for binary classification.
In two dimensions, a hyperplane is a line. In three dimensions, it is a plane. The same mathematical concept extends to higher-dimensional feature spaces.
The margin
The margin measures separation around the decision boundary. In the standard linear SVM formulation, the two supporting hyperplanes are
Their perpendicular distance is
The SVM seeks a relatively wide margin, rather than merely finding any boundary that classifies the training examples correctly. Wider margins can help generalization, although performance depends on the data and modeling choices.
Support vectors
Support vectors are training observations that constrain or define the learned decision boundary. In a hard-margin setting, they lie on the margin boundaries; with a soft margin, relevant points can lie inside the margin or be misclassified.
One useful insight is that many distant training observations may have little direct effect on the fitted boundary. Observations near or violating the margin are especially influential.
3. Hard margin, soft margin, and regularization
A hard-margin SVM requires perfectly separable training data. Real datasets often contain overlapping classes, mislabeled observations, or noise, making that requirement impractical.
A soft-margin SVM permits violations using nonnegative slack variables . A standard optimization objective is:
subject to
Each binary label is or . The first term encourages a wide margin; the second penalizes margin violations.
The hyperparameter controls this trade-off:
- Smaller : Stronger regularization and greater tolerance of violations. May produce a simpler boundary but underfit.
- Larger : Greater penalty for violations. May fit the training data more closely but become sensitive to noise.
Important: Larger does not automatically mean better accuracy. It should be selected with validation data, preferably through cross-validation.
4. Kernels and nonlinear classification
Some datasets cannot be separated adequately with a straight line. A kernel SVM can produce nonlinear decision boundaries in the original input space.
A kernel function measures similarity in an implicit feature space:
where is a feature transformation. Suitable kernels let the algorithm work with transformed-feature inner products without explicitly constructing all transformed features. This is often called the kernel trick.
| Kernel | Basic idea | Typical consideration |
|---|---|---|
| Linear | Uses the original feature-space inner product | Often useful for approximately linear boundaries and high-dimensional sparse features |
| Polynomial | Represents polynomial feature interactions | Degree and other parameters affect complexity |
| Radial basis function (RBF) | Similarity decreases with squared distance | Flexible nonlinear boundaries; sensitive to scaling and hyperparameters |
| Sigmoid | Uses a hyperbolic-tangent similarity form | Less commonly a default; parameter choices require care |
The RBF kernel is commonly written:
The hyperparameter controls how quickly similarity decreases with distance. A large creates a highly localized influence; a small produces broader influence. Both extremes can harm generalization.
In scikit-learn, SVC supports kernels including linear, poly, and rbf. For large, high-dimensional, approximately linear problems, LinearSVC can be a practical alternative with different implementation and scaling characteristics.
5. What is k-Nearest Neighbors?
Definition: k-Nearest Neighbors is a supervised learning method that predicts the target for a new observation using the labels or values of its closest training observations under a specified distance measure.
Unlike an SVM, k-NN does not usually learn a compact global decision boundary during fitting. It mainly stores reference examples and performs substantial work when making predictions. For that reason, it is often described as an instance-based or lazy learning method.
The classification procedure
- Represent the new observation using the same features as the training observations.
- Compute its distance from the training examples or search for the nearest candidates using a suitable index.
- Identify the closest examples.
- Assign a class using majority vote or distance-weighted voting.
For k-NN regression, the prediction is commonly the mean or distance-weighted mean of the neighbors’ numerical target values.
A worked voting example
Suppose the five nearest labeled examples are:
| Neighbor | Distance | Class |
|---|---|---|
| 1 | 0.4 | A |
| 2 | 0.6 | B |
| 3 | 0.8 | A |
| 4 | 1.1 | A |
| 5 | 1.3 | B |
With and uniform voting, the nearest three have labels A, B, A. The predicted class is A, with two of the three votes.
With , A also wins, with three of five votes. A different choice of can change the prediction, particularly near a class boundary.
A vote fraction is not necessarily a well-calibrated probability that the predicted class is correct. Probability quality must be assessed separately.
6. Distance metrics and feature scaling
The meaning of nearest depends on the chosen distance metric. For two vectors and :
Euclidean distance (straight-line distance):
Manhattan distance (sum of coordinate-wise absolute differences):
More generally, the Minkowski distance is
Euclidean distance is ; Manhattan distance is . Other measures, such as cosine distance, can be useful depending on the data representation, but a similarity score and a metric are not always interchangeable.
Why scaling matters
Imagine two features:
- Device temperature: values around 20–90.
- Annual operating hours: values around 1,000–10,000.
Without scaling, operating hours may dominate Euclidean distances simply because of their numerical scale. A similar issue affects margin-based SVMs and RBF kernels.
A standard transformation is:
Here, the mean and standard deviation must be estimated from training data only. Apply those stored training statistics to validation, test, and future inputs. Otherwise, information from held-out data can leak into the training process.
Categorical variables, missing values, and very high-dimensional sparse vectors may require different preprocessing decisions. Scaling is important, but it is not a substitute for selecting a meaningful representation.
7. Choosing and weighting neighbors
The parameter controls how local the prediction is.
- Small : Highly local behavior, which may capture fine patterns but be sensitive to noise.
- Large : Smoother predictions using a broader neighborhood, which can overlook local structure.
A value of assigns the class of the single nearest labeled observation. There is no universally optimal , and the familiar suggestion to use is only a heuristic, not a rule.
With uniform weighting, every selected neighbor contributes equally. With distance weighting, closer neighbors contribute more. For example, an inverse-distance rule uses weights approximately proportional to for nonzero distances; software libraries specify how zero-distance cases are handled.
Select , the distance metric, and weights using validation or cross-validation, not the final test set.
8. SVM versus k-NN
| Property | Support Vector Machine | k-Nearest Neighbors |
|---|---|---|
| Main principle | Learn a large-margin boundary | Predict from nearby labeled examples |
| Typical classification strategy | Sign or score from decision function | Vote among selected neighbors |
| Training | Solves an optimization problem | Primarily stores or indexes training data |
| Prediction | Evaluates learned boundary; kernel SVM may use many support vectors | Searches training observations or a neighbor index |
| Important hyperparameters | C, kernel, gamma for RBF | n_neighbors, distance metric, weights |
| Scaling sensitivity | Often high, especially with RBF kernels | Usually high with distance-based features |
| Nonlinear behavior | Through kernels | Naturally yields local, possibly irregular boundaries |
| Memory | Depends on model and support-vector count | Typically retains training examples |
| Strength | Clear margin principle, effective on many moderate-sized datasets | Simple local baseline, flexible with appropriate distances |
| Limitation | Kernel training can be costly on large datasets | Prediction/search can be costly; distance becomes less informative in some high dimensions |
The complexity of either method depends on sample size, feature count, kernel or distance choice, and implementation. Broad claims such as “SVM is always faster” or “k-NN never scales” are misleading.
The curse of dimensionality
As dimensionality increases, points can become sparse and distance differences may become less informative. This can reduce k-NN performance unless features, metrics, or representations are chosen carefully. Feature selection, dimensionality reduction, and domain-specific embeddings can help.
High-dimensionality is not always fatal: methods such as approximate nearest-neighbor indexing can work well with useful representations. The problem is that raw distance may stop corresponding to task-relevant similarity.
9. Build and compare both models in Python
The following example uses scikit-learn’s built-in breast-cancer classification dataset as a software demonstration, not as a medical diagnostic system. It compares a scaled RBF SVM with scaled k-NN using a held-out test set.
from sklearn.datasets import load_breast_cancer
from sklearn.metrics import accuracy_score, classification_report
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
# Public educational dataset; not a clinically validated diagnostic workflow.
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.20, random_state=42, stratify=y
)
models = {
"RBF SVM": make_pipeline(
StandardScaler(), SVC(kernel="rbf", C=1.0, gamma="scale")
),
"k-NN": make_pipeline(
StandardScaler(), KNeighborsClassifier(n_neighbors=5)
),
}
for name, model in models.items():
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print(name, "accuracy:", round(accuracy_score(y_test, y_pred), 3))
print(classification_report(y_test, y_pred, zero_division=0))
This example demonstrates several good practices:
- Stratification: The split approximately preserves class proportions.
- Pipelines:
StandardScalerlearns only from the training portion whenfitis called on the pipeline. - Common evaluation: Both models are assessed on the same held-out observations.
- Multiple metrics: Precision, recall, and F1-score add information beyond accuracy.
Do not choose hyperparameters by repeatedly inspecting the final test results. Use cross-validation on the training set instead. Also consider data collection, class definitions, deployment constraints, and the cost of each kind of error.
Tune without leaking test information
from sklearn.model_selection import GridSearchCV, StratifiedKFold
svm_pipeline = make_pipeline(StandardScaler(), SVC(kernel="rbf"))
search = GridSearchCV(
svm_pipeline,
param_grid={
"svc__C": [0.1, 1.0, 10.0],
"svc__gamma": ["scale", 0.01, 0.1],
},
cv=StratifiedKFold(n_splits=5, shuffle=True, random_state=42),
scoring="balanced_accuracy",
n_jobs=-1,
)
search.fit(X_train, y_train)
print("Selected settings:", search.best_params_)
print("Cross-validation score:", round(search.best_score_, 3))
print("Test balanced accuracy:", round(search.score(X_test, y_test), 3))
In this second block, search.score reports balanced accuracy, the metric configured for model selection. It is not ordinary accuracy.
The grid is deliberately small for learning. A production comparison also needs representative validation data, meaningful class-specific metrics, and an assessment of deployment costs.
10. Other uses and extensions
Support Vector Regression (SVR)
SVM principles also support regression. Support Vector Regression seeks a function that fits target values within a chosen tolerance while controlling model complexity. It is not a classifier with labels renamed; its loss and optimization formulation differ.
k-NN regression
A nearest-neighbor regressor predicts a numerical outcome from nearby examples, often using their average or distance-weighted average. It can model local nonlinear behavior, but it may extrapolate poorly beyond observed target ranges.
Novelty and anomaly detection
One-Class SVM is a distinct formulation used for novelty detection. Neighbor-based distances can also supply anomaly scores, though standard k-NN classification is not automatically an anomaly detector.
Approximate nearest-neighbor search
Very large or high-dimensional collections often use approximate search techniques that trade some retrieval exactness for speed and memory efficiency. These techniques are important in semantic search and embedding-based AI systems, but nearest-neighbor retrieval does not itself imply supervised k-NN classification.
11. Common mistakes
- Skipping scaling: Unequal feature units can distort both distances and margins.
- Using the final test set for tuning: This leads to optimistic performance estimates.
- Assuming RBF always wins: Nonlinear flexibility can overfit or cost too much to serve.
- Choosing by habit: Its best value depends on data, labels, and task-specific costs.
- Trusting vote fractions as probabilities: Calibration needs separate evaluation.
- Using unrelated features in distance calculations: Mathematical proximity is not necessarily meaningful similarity.
- Ignoring latency and memory: k-NN stores many examples; kernel SVM prediction may depend on many support vectors.
- Comparing only training accuracy: A model must work on unseen observations.
12. Check your understanding
- Why does an SVM seek a large margin instead of just a separating boundary?
- What happens when the SVM parameter is made very large?
- What does the RBF kernel’s parameter influence?
- Why might two observations with similar task meaning be far apart under raw Euclidean distance?
- How is k-NN classification different from nearest-neighbor information retrieval?
- Why should preprocessing be inside a cross-validation pipeline?
Show suggested answers
- A margin encourages a boundary less dependent on small variations in the training data, which can support generalization.
- Violations become more costly, potentially yielding a closer training fit at the cost of more sensitivity to noise.
- It controls the spatial reach of similarity in the RBF kernel; larger values make similarity more local.
- Poorly scaled or irrelevant features can dominate distance, and the feature representation may not capture the task’s semantics.
- k-NN classification uses retrieved labels to predict a supervised target. Retrieval returns relevant or similar items, often without a class-voting step.
- It ensures each training fold estimates preprocessing parameters without seeing its validation fold.
13. Related concepts
- Machine Learning Paradigms — placing SVM and k-NN within supervised learning.
- Vectors and Matrices — feature vectors and dimensions.
- Vector and Matrix Operations — inner products and vector norms.
- Optimization and Gradient Descent — the role of optimization and regularization.
- Feature Engineering, Encoding, and Scaling — constructing distance-aware input features.
- Data Splitting, Labeling, and Leakage — validation without leakage.
- Linear and Logistic Regression — alternative linear classifiers.
- Decision Trees, Random Forests, and Boosting — partition-based alternatives.
- Dimensionality Reduction and PCA — reducing dimensions before learning.
- Evaluating Machine Learning Models — selecting useful evaluation metrics.
References and further reading
- scikit-learn User Guide: Support Vector Machines — SVM formulations, kernels, and practical guidance.
- scikit-learn User Guide: Nearest Neighbors — classification, regression, metrics, and search methods.
- scikit-learn: Common pitfalls and recommended practices — pipelines, splitting, and data leakage.
- An Introduction to Statistical Learning — practical foundations for supervised methods.
Related articles in
- Clustering and K-Means — Learn how unsupervised clustering discovers groups in data, how K-Means optimizes cluster centroids, and how to evaluate and use its results responsibly.
- Data, Model, and Experiment Versioning — Learn to trace ML results to exact datasets, code revisions, configurations, and artifacts.
- Decision Trees, Random Forests, and Boosting — Learn how decision trees partition data, how random forests reduce variance through bagging, and how boosting combines sequential learners to improve predictions.