Machine Learning • Machine Learning Algorithms • 15 min read

Support Vector Machines and Nearest Neighbors

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 dd features, an observation is represented by a vector x∈Rd\mathbf{x}\in\mathbb{R}^d.

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.

Comparison of a straight support vector machine decision boundary and a nearest-neighbor local classification
Conceptual comparison. The left model learns a decision boundary; the right predicts from nearby examples. The drawings are illustrative rather than fitted results from a dataset.

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:

wTx+b=0\mathbf{w}^{\mathsf T}\mathbf{x}+b=0

Here:

  • x\mathbf{x} is the input feature vector.
  • w\mathbf{w} determines the boundary’s orientation.
  • bb shifts the boundary.
  • The sign of wTx+b\mathbf{w}^{\mathsf T}\mathbf{x}+b 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

wTx+b=1andwTx+b=−1.\mathbf{w}^{\mathsf T}\mathbf{x}+b=1 \quad\text{and}\quad \mathbf{w}^{\mathsf T}\mathbf{x}+b=-1.

Their perpendicular distance is

Margin width=2∥w∥2.\text{Margin width}=\frac{2}{\lVert\mathbf{w}\rVert_2}.

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 ξi\xi_i. A standard optimization objective is:

min⁡w,b,ξ12∥w∥22+C∑i=1nξi\min_{\mathbf{w},b,\boldsymbol\xi} \frac{1}{2}\lVert\mathbf{w}\rVert_2^2 +C\sum_{i=1}^{n}\xi_i

subject to

yi(wTxi+b)≥1−ξi,ξi≥0.y_i(\mathbf{w}^{\mathsf T}\mathbf{x}_i+b)\ge 1-\xi_i, \qquad \xi_i\ge 0.

Each binary label yiy_i is −1-1 or +1+1. The first term encourages a wide margin; the second penalizes margin violations.

The hyperparameter CC controls this trade-off:

  • Smaller CC: Stronger regularization and greater tolerance of violations. May produce a simpler boundary but underfit.
  • Larger CC: Greater penalty for violations. May fit the training data more closely but become sensitive to noise.

Important: Larger CC 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:

K(x,z)=ϕ(x)Tϕ(z),K(\mathbf{x},\mathbf{z})= \phi(\mathbf{x})^{\mathsf T}\phi(\mathbf{z}),

where ϕ\phi 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.

KernelBasic ideaTypical consideration
LinearUses the original feature-space inner productOften useful for approximately linear boundaries and high-dimensional sparse features
PolynomialRepresents polynomial feature interactionsDegree and other parameters affect complexity
Radial basis function (RBF)Similarity decreases with squared distanceFlexible nonlinear boundaries; sensitive to scaling and hyperparameters
SigmoidUses a hyperbolic-tangent similarity formLess commonly a default; parameter choices require care

The RBF kernel is commonly written:

K(x,z)=exp⁡(−γ∥x−z∥22).K(\mathbf{x},\mathbf{z})= \exp\left(-\gamma\lVert\mathbf{x}-\mathbf{z}\rVert_2^2\right).

The hyperparameter γ\gamma controls how quickly similarity decreases with distance. A large γ\gamma creates a highly localized influence; a small γ\gamma 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 kk 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

  1. Represent the new observation using the same features as the training observations.
  2. Compute its distance from the training examples or search for the nearest candidates using a suitable index.
  3. Identify the kk closest examples.
  4. 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:

NeighborDistanceClass
10.4A
20.6B
30.8A
41.1A
51.3B

With k=3k=3 and uniform voting, the nearest three have labels A, B, A. The predicted class is A, with two of the three votes.

With k=5k=5, A also wins, with three of five votes. A different choice of kk 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 x\mathbf{x} and z\mathbf{z}:

Euclidean distance (straight-line distance):

d2(x,z)=∑j=1d(xj−zj)2.d_2(\mathbf{x},\mathbf{z})= \sqrt{\sum_{j=1}^{d}(x_j-z_j)^2}.

Manhattan distance (sum of coordinate-wise absolute differences):

d1(x,z)=∑j=1d∣xj−zj∣.d_1(\mathbf{x},\mathbf{z})= \sum_{j=1}^{d}|x_j-z_j|.

More generally, the Minkowski distance is

dp(x,z)=(∑j=1d∣xj−zj∣p)1/p,p≥1.d_p(\mathbf{x},\mathbf{z})= \left(\sum_{j=1}^{d}|x_j-z_j|^p\right)^{1/p},\quad p\ge1.

Euclidean distance is p=2p=2; Manhattan distance is p=1p=1. 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:

z=x−μtrainσtrain.z=\frac{x-\mu_{\text{train}}}{\sigma_{\text{train}}}.

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 kk and weighting neighbors

The parameter kk controls how local the prediction is.

  • Small kk: Highly local behavior, which may capture fine patterns but be sensitive to noise.
  • Large kk: Smoother predictions using a broader neighborhood, which can overlook local structure.

A value of k=1k=1 assigns the class of the single nearest labeled observation. There is no universally optimal kk, and the familiar suggestion to use n\sqrt{n} 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 1/d1/d for nonzero distances; software libraries specify how zero-distance cases are handled.

Select kk, the distance metric, and weights using validation or cross-validation, not the final test set.

8. SVM versus k-NN

PropertySupport Vector Machinek-Nearest Neighbors
Main principleLearn a large-margin boundaryPredict from nearby labeled examples
Typical classification strategySign or score from decision functionVote among selected neighbors
TrainingSolves an optimization problemPrimarily stores or indexes training data
PredictionEvaluates learned boundary; kernel SVM may use many support vectorsSearches training observations or a neighbor index
Important hyperparametersC, kernel, gamma for RBFn_neighbors, distance metric, weights
Scaling sensitivityOften high, especially with RBF kernelsUsually high with distance-based features
Nonlinear behaviorThrough kernelsNaturally yields local, possibly irregular boundaries
MemoryDepends on model and support-vector countTypically retains training examples
StrengthClear margin principle, effective on many moderate-sized datasetsSimple local baseline, flexible with appropriate distances
LimitationKernel training can be costly on large datasetsPrediction/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:

  1. Stratification: The split approximately preserves class proportions.
  2. Pipelines: StandardScaler learns only from the training portion when fit is called on the pipeline.
  3. Common evaluation: Both models are assessed on the same held-out observations.
  4. 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.

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 kk 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

  1. Why does an SVM seek a large margin instead of just a separating boundary?
  2. What happens when the SVM parameter CC is made very large?
  3. What does the RBF kernel’s γ\gamma parameter influence?
  4. Why might two observations with similar task meaning be far apart under raw Euclidean distance?
  5. How is k-NN classification different from nearest-neighbor information retrieval?
  6. Why should preprocessing be inside a cross-validation pipeline?
Show suggested answers
  1. A margin encourages a boundary less dependent on small variations in the training data, which can support generalization.
  2. Violations become more costly, potentially yielding a closer training fit at the cost of more sensitivity to noise.
  3. It controls the spatial reach of similarity in the RBF kernel; larger values make similarity more local.
  4. Poorly scaled or irrelevant features can dominate distance, and the feature representation may not capture the task’s semantics.
  5. k-NN classification uses retrieved labels to predict a supervised target. Retrieval returns relevant or similar items, often without a class-voting step.
  6. It ensures each training fold estimates preprocessing parameters without seeing its validation fold.

References and further reading

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.

Image preview

Fit