Skip to main content

Support Vector Machine

What is a support vector machine?​

A support vector machine (SVM) is a machine learning classifier that separates two classes with the boundary that leaves the widest possible gap between them. The boundary is a line in 2D and a hyperplane in more dimensions. With a kernel function, the same method draws curved boundaries by working in a higher-dimensional space without ever building it.

Two charts in a dark navy theme. On the left, a ring of blue points surrounds a disc of orange points over a heatmap of the classifier's decision function, with a white closed curve for the boundary, thin margin curves either side and the support vectors ringed in white. On the right, the same points lifted onto a bowl-shaped paraboloid in 3D, cut by a flat green plane whose intersection with the bowl is a white circle

An SVM with an RBF kernel trained on a ring-and-disc dataset (left), and the same points lifted to 3D, where a flat plane separates them (right). Sample data. Try the interactive version.

Key takeaways
  • An SVM picks the boundary that leaves the widest margin between the classes, and only the points nearest the boundary, the support vectors, decide where it goes.
  • The margin is 2/∥w∥2 / \lVert \mathbf{w} \rVert wide, so maximising it means minimising the length of the weight vector.
  • A soft margin, tuned by C, lets some points sit inside the margin or on the wrong side in exchange for a wider gap.
  • The kernel trick swaps every dot product for a kernel function, so a linear method draws curved boundaries.
  • Scale the features first, and tune C and gamma together on held-out data.

How a support vector machine works​

A linear classifier labels a point x\mathbf{x} by the sign of a score:

f(x)=w⊤x+bf(\mathbf{x}) = \mathbf{w}^\top \mathbf{x} + b

Points with f>0f > 0 are class +1 and points with f<0f < 0 are class −1. The hyperplane f=0f = 0 is the decision boundary, w\mathbf{w} is the weight vector at right angles to it, and bb shifts it away from the origin.

When the classes can be separated, infinitely many lines do it. A perceptron stops at whichever one it reaches first. An SVM picks one particular line, the one that stays farthest from the nearest point of either class. Vapnik's statistical learning theory links a wider margin to a smaller risk of error on new data, and in practice a point has to land well away from the training data before this maximum-margin boundary misclassifies it.

An annotated diagram of a support vector machine: orange class +1 points upper right and blue class −1 points lower left, separated by a solid diagonal line labelled 1, the hyperplane where f(x) = 0. Dashed lines either side, labelled 2, are the margins at f(x) = +1 and −1. Three circled points on the dashed lines, labelled 3, are support vectors. A green arrow at right angles to the line, labelled 4, is the weight vector w. A double arrow across the band, labelled 5, is the margin width 2 / ‖w‖. A blue point inside the band and another on the wrong side, labelled 6, each have a dotted slack line to their margin

The margin and the support vectors​

The SVM scales w\mathbf{w} and bb so that the nearest points on each side have f=+1f = +1 or f=−1f = -1. Those two parallel hyperplanes are the margins, and the distance between them is

margin width=2∥w∥\text{margin width} = \frac{2}{\lVert \mathbf{w} \rVert}

A wide margin means a short weight vector. Training a hard-margin SVM therefore solves

min⁡w, b 12∥w∥2subject toyi(w⊤xi+b)≥1 for every training point i\min_{\mathbf{w},\,b}\ \tfrac{1}{2}\lVert \mathbf{w} \rVert^2 \quad \text{subject to} \quad y_i(\mathbf{w}^\top \mathbf{x}_i + b) \ge 1 \ \text{for every training point } i

where yiy_i is the point's label, +1 or −1. The constraint keeps every point on its own side, at least one margin away.

The points that end up exactly on the margins are the support vectors. They hold the boundary in place. Move any other point, or delete it, and the solution doesn't change, as long as it stays outside the margin. In the live demo, the support vectors are ringed in white.

As a check, take two points: (−1, 0) labelled −1 and (1, 0) labelled +1. The widest gap is the vertical line x1=0x_1 = 0. The SVM gives w=(1,0)\mathbf{w} = (1, 0) and b=0b = 0, so f=±1f = \pm 1 at the two points, both are support vectors, and the margin is 2/1=22 / 1 = 2 wide, the distance between them.

Hard margin vs soft margin and the C parameter​

Real classes overlap, so no hyperplane may separate them, and one outlier can drag a hard margin a long way. A soft-margin SVM gives each point a slack value ξi≥0\xi_i \ge 0, how far it is allowed to break the margin, and charges for it:

min⁡w, b, ξ 12∥w∥2+C∑iξisubject toyif(xi)≥1−ξi\min_{\mathbf{w},\,b,\,\xi}\ \tfrac{1}{2}\lVert \mathbf{w} \rVert^2 + C \sum_i \xi_i \quad \text{subject to} \quad y_i f(\mathbf{x}_i) \ge 1 - \xi_i

A point with 0<ξi<10 < \xi_i < 1 is inside the margin but still correctly classified; one with ξi>1\xi_i > 1 is on the wrong side. The C parameter sets the price of slack:

  • A small C (0.01 in the demo) makes slack cheap. The margin widens, more points fall inside it and become support vectors, and single points barely move the boundary.
  • A large C (1,000) makes slack expensive. The margin narrows to fit as many training points as possible, which can chase noise.

On the demo's overlapping linear dataset with a linear kernel, moving C from 0.01 to 1 to 1,000 shrinks the margin from 2.26 to 0.67 to 0.40 units, and the support vectors drop from 144 of the 200 points to 32 and then 22.

Hinge loss​

The soft-margin problem can be written without the slack variables. Each point's slack is its hinge loss:

ξi=max⁡(0, 1−yif(xi))\xi_i = \max\bigl(0,\ 1 - y_i f(\mathbf{x}_i)\bigr)

It is zero for points safely outside the margin and grows in a straight line as a point moves into the margin and across the boundary. So a linear SVM minimises hinge loss plus an L2 penalty on the weights, with C setting the balance. Logistic regression minimises log loss plus the same kind of penalty, so the two often give similar lines. The regularization guide covers L2 penalties in more detail.

The kernel trick​

Some classes can't be split by any straight line. In the circles dataset, one class is a disc of radius 0.5 and the other a ring of radius 1 around it. The demo's linear kernel scores 58% on the training points and 50% on a held-out test set, no better than a coin.

The fix is to add a coordinate. Lift each point (x1,x2)(x_1, x_2) to

(x1, x2, z)withz=x12+x22(x_1,\ x_2,\ z) \quad \text{with} \quad z = x_1^2 + x_2^2

which puts every point on a bowl-shaped paraboloid. Points near the centre stay low and points far out rise high, so a flat plane can now pass between the disc and the ring. Where that plane cuts the bowl, it traces a circle, and that circle is the boundary back in 2D.

A worked example​

Take four class +1 points at radius 0.5, at (±0.5, 0) and (0, ±0.5), and four class −1 points at radius 1, at (±1, 0) and (0, ±1).

Two panels. On the left, in 2D, four orange points at radius 0.5 sit inside four blue points at radius 1, with a dashed green circle of radius 0.79 between them. An arrow labelled lift, z = x1² + x2², leads to the right panel, a side view of the lifted points on a parabola: the orange points at height 0.25, the blue points at height 1, a green separating plane at z = 0.625 with margins at 0.25 and 1, a width of 0.75, and the plane meeting the parabola at x1 = −0.79 and 0.79

  1. Lift them. The inner points all get z=0.52=0.25z = 0.5^2 = 0.25 and the outer points z=12=1z = 1^2 = 1.
  2. In 3D the classes sit on two horizontal layers, so a linear SVM separates them with the horizontal plane halfway between, z=0.625z = 0.625. Its weight vector is w=(0,0,−2.67)\mathbf{w} = (0, 0, -2.67) with b=1.67b = 1.67, which gives f=+1f = +1 at z=0.25z = 0.25 and f=−1f = -1 at z=1z = 1.
  3. The margin is 2/2.67=0.752 / 2.67 = 0.75 wide, the gap from 0.25 to 1.
  4. Project back. The plane meets the bowl where x12+x22=0.625x_1^2 + x_2^2 = 0.625, a circle of radius 0.625=0.79\sqrt{0.625} = 0.79, between the disc at 0.5 and the ring at 1.

Training an SVM on the eight lifted points gives exactly these numbers. In the demo, the 3D chart does the same on 200 noisy points and finds a circle of radius 0.75.

Why it is called a trick​

Training an SVM never needs the coordinates themselves, only the dot products between pairs of points. The dual form of the problem, which solvers such as SMO work on, gives each training point a weight αi\alpha_i, and the trained model is

f(x)=∑iαi yi K(xi,x)+bf(\mathbf{x}) = \sum_i \alpha_i\, y_i\, K(\mathbf{x}_i, \mathbf{x}) + b

where K(xi,x)K(\mathbf{x}_i, \mathbf{x}) is a kernel function: the dot product of the two points after mapping them to the new space. Only support vectors have αi>0\alpha_i > 0, so only they appear in the sum. For the paraboloid lift, K(a,b)=a⊤b+∥a∥2∥b∥2K(\mathbf{a}, \mathbf{b}) = \mathbf{a}^\top \mathbf{b} + \lVert \mathbf{a} \rVert^2 \lVert \mathbf{b} \rVert^2, which works on the 2D points and never builds the third coordinate.

The saving grows with the number of dimensions. For the polynomial kernel K(a,b)=(a⊤b)2K(\mathbf{a}, \mathbf{b}) = (\mathbf{a}^\top \mathbf{b})^2 with a=(1,2)\mathbf{a} = (1, 2) and b=(3,1)\mathbf{b} = (3, 1), the kernel is (3+2)2=25(3 + 2)^2 = 25. The explicit map ϕ(x)=(x12, 2 x1x2, x22)\phi(\mathbf{x}) = (x_1^2,\ \sqrt{2}\,x_1 x_2,\ x_2^2) gives ϕ(a)=(1, 22, 4)\phi(\mathbf{a}) = (1,\ 2\sqrt{2},\ 4) and ϕ(b)=(9, 32, 1)\phi(\mathbf{b}) = (9,\ 3\sqrt{2},\ 1), whose dot product is 9+12+4=259 + 12 + 4 = 25. The kernel got there with one 2D dot product and a square. A degree-5 polynomial on 100 features would need about 92 million coordinates, and the kernel still needs one dot product and a power. A function can serve as a kernel when it is a dot product in some space, which Mercer's theorem characterises.

SVM kernels: linear, polynomial and RBF​

The kernel sets the shape of the boundary: a straight line for the linear kernel, curves of a chosen degree for the polynomial kernel, and almost any shape for the RBF kernel, the usual first choice.

KernelFormulaBoundary in 2DParametersUse it when
Linearx⊤x′\mathbf{x}^\top \mathbf{x}'Straight lineCMany features, such as text, or a straight boundary is enough
Polynomial(γ x⊤x′+r)d(\gamma\, \mathbf{x}^\top \mathbf{x}' + r)^dConic sections at degree 2, more complex curves aboveC, degree d, gamma, rProducts of features matter, as in the circles dataset at degree 2
RBF (Gaussian)exp⁡(−γ∥x−x′∥2)\exp(-\gamma \lVert \mathbf{x} - \mathbf{x}' \rVert^2)Any smooth shape, including islandsC, gammaA good first choice when you don't know the shape
Sigmoidtanh⁡(γ x⊤x′+r)\tanh(\gamma\, \mathbf{x}^\top \mathbf{x}' + r)VariesC, gamma, rRarely; it isn't a valid kernel for every setting

The RBF kernel (radial basis function, or Gaussian kernel) measures similarity by distance: 1 for identical points, falling towards 0 as they move apart. Its feature space has infinitely many dimensions, so it can only be used through the kernel trick. The f(x) it learns is a sum of bumps, one centred on each support vector.

What gamma does​

Gamma sets how quickly an RBF bump falls off. The kernel drops to about a third (1/e) at a distance of 1/γ1/\sqrt{\gamma} in the units of the features:

  • A small gamma (0.01) gives wide bumps that blur into a smooth, almost linear boundary. On the moons dataset with C = 1, training accuracy is 81.5%, so the model underfits.
  • At gamma = 1, the boundary follows the two crescents: 98.5% on the training points and 99% on the test points.
  • A large gamma (100) gives a narrow bump around each point. On the overlapping linear dataset with C = 1,000, gamma = 100 scores 100% on the training points, with 185 of the 200 as support vectors, but 92% on the test set, against 95.5% at gamma = 1.

scikit-learn's SVC defaults to C = 1 and sets gamma from the data, as 1 divided by the number of features times the variance of the data. The libsvm guide by Hsu, Chang and Lin recommends a grid search over C and gamma on a log scale with cross-validation, which is why both demo sliders move in powers of ten.

How to read an SVM decision boundary plot​

An SVM decision boundary plot colours each point of the plane by the SVM's score and draws the boundary and margins as contours. The 2D chart in the demo is laid out like this:

  1. The background colour is f(x), the SVM's score, at every point. Orange means class +1 and blue means class −1; the deeper the colour, the further from the boundary.
  2. The thick white contour is the decision boundary, f = 0. Every point on one side gets the same label.
  3. The thin contours are the margins, f = +1 and f = −1. Training points between them pay a hinge-loss penalty.
  4. White rings mark the support vectors. If almost every point is ringed, C is small or the classes overlap. If the rings sit only along the boundary, the model is compact.
  5. Islands of colour around single points mean gamma is too high.

The score is proportional to the signed distance from the boundary, not a probability. To turn it into one, fit a logistic curve to the scores on held-out data (Platt scaling), and judge the ranking with a ROC curve. With more than two features, plot two at a time, or project the data first. The decision boundary guide compares how different classifiers carve up the same plane.

Multi-class SVM​

An SVM separates two classes, so for more it is run several times. One-vs-rest trains one SVM per class against all the others and picks the class whose SVM gives the highest score: k classifiers for k classes. One-vs-one trains an SVM for every pair of classes, k(k − 1)/2 in all, and takes a vote; each one trains on only two classes' points, so it is often quicker overall. scikit-learn's SVC uses one-vs-one, and its LinearSVC uses one-vs-rest.

SVM vs logistic regression vs k-nearest neighbours​

Choose an SVM for a clear margin on small to medium data, logistic regression when you need probabilities or explainable coefficients, and k-NN for a quick baseline in few dimensions.

MethodBoundaryUses which training pointsGives probabilitiesTraining costBest for
Linear SVMStraight (hyperplane)Support vectors onlyNo, scores (add Platt scaling)Fast, even with millions of rowsHigh-dimensional sparse data such as text
Kernel SVM (RBF, polynomial)Curved, any smooth shapeSupport vectors onlyNo, scoresBetween quadratic and cubic in the rows, so slow beyond tens of thousandsSmall to medium datasets with a non-linear boundary
Logistic regressionStraight unless you add featuresAll pointsYesFastWhen you need probabilities or coefficients to explain
k-nearest neighboursAny shape, jaggedAll points, kept for predictionVote sharesNone to train; slow to predict on large setsLow dimensions, plenty of data, a quick baseline

A kernel SVM and k-NN both draw curved boundaries. The SVM keeps only its support vectors and smooths the boundary through C and gamma; k-NN keeps every point and follows local noise unless k is large.

Feature scaling for SVMs​

SVMs measure distance. An RBF kernel compares ∥x−x′∥\lVert \mathbf{x} - \mathbf{x}' \rVert, and the margin is measured in the units of the features. If one feature is in metres and runs from 0 to 1,000 and another is a ratio from 0 to 1, the first decides almost everything and gamma has no sensible value. Standardise each feature to mean 0 and standard deviation 1, or scale it to [−1, 1], using statistics from the training set only, and apply the same transform to new data. The demo's datasets are already on comparable scales, so one gamma suits both features.

Where support vector machines are used​

Support vector machines are used most where there are many features and fairly few labelled examples.

  • Text classification: spam filtering and topic labelling, where a linear SVM handles tens of thousands of word features.
  • Handwritten digit recognition. Cortes and Vapnik's 1995 paper tested soft-margin SVMs with polynomial kernels on handwritten digits.
  • Bioinformatics: classifying samples from gene-expression or protein data, where there are far more features than samples.
  • Image and signal classification, from face detection to fault detection in vibration and sensor data.
  • Industrial inspection, such as classifying defect patterns in semiconductor test and wafer data.
  • Anomaly detection with a one-class SVM, which learns a boundary around normal data only. See the anomaly detection guide.
  • Regression. Support vector regression fits a tube that runs ε either side of the curve and ignores errors inside it.

Common SVM mistakes​

Most SVM mistakes come from unscaled features and from settings of C and gamma that let the model memorise its training points.

  • Not scaling the features. The largest feature dominates the distances and the margin. Fit the scaler on training data only.
  • Gamma too high. The model memorises the training points and scores 100% on them. Compare training and test accuracy, as the demo does, and pick C and gamma by cross-validation.
  • Tuning C and gamma one at a time. The best gamma depends on C and the reverse, so search them together on a log grid.
  • Reading the score as a probability. f(x) is proportional to the signed distance from the boundary in the kernel's feature space. Calibrate it before you use it as a risk.
  • Using a kernel SVM on a very large dataset. The kernel matrix grows with the square of the number of rows. Use a linear SVM, a kernel approximation or a sample.
  • Ignoring class imbalance. With 1% positives, the boundary can cut into the minority class. Weight C per class, and judge the model with a precision-recall curve rather than accuracy.
  • Pairing the polynomial kernel with a large gamma and degree. The kernel values explode and training fails to converge, which the demo reports as "stopped at the step limit". Start with RBF.

How to visualise a support vector machine in JavaScript, React or Angular​

The demo retrains the SVM in the browser each time you move a slider, with a compact SMO solver in plain JavaScript from the same family of algorithms as libsvm, then redraws the 2D heatmap and contours and the 3D lift that shows the kernel trick at work.

Choose a Dataset (linear, circles or moons) and a Kernel (linear, polynomial or RBF), with its Degree for the polynomial kernel. C and Gamma move in powers of ten, and the results line shows the support-vector count and the training and test accuracy, so you can watch overfitting happen. On the right, the 3D chart lifts the same points onto the paraboloid and trains a linear SVM there. Drag Lift from 0 to 1, or press Animate lift, to raise the points off the floor and watch the plane and its white intersection circle rise with them. Drag the 3D chart to rotate it. On the 2D chart, the wheel zooms, a drag pans, a double-click resets and hovering shows values.

Here is the code for both charts. The SVM, the kernels and the lift are plain JavaScript; SciChart.js draws the decision function as a heatmap with contour lines, and the kernel trick as a 3D surface mesh, a second mesh for the plane, a 3D scatter series and a 3D line.

// A support vector machine trained in the browser: its decision function as a heatmap with the boundary and
// margins as contours (2D), and the kernel trick as points lifted onto a paraboloid cut by a plane (3D)
const {
SciChartSurface,
SciChart3DSurface,
NumericAxis,
NumericAxis3D,
NumberRange,
EAxisAlignment,
Vector3,
XyDataSeries,
XyzDataSeries3D,
UniformHeatmapDataSeries,
UniformGridDataSeries3D,
UniformHeatmapRenderableSeries,
UniformContoursRenderableSeries,
HeatmapColorMap,
XyScatterRenderableSeries,
EllipsePointMarker,
ScatterRenderableSeries3D,
SpherePointMarker3D,
SurfaceMeshRenderableSeries3D,
PointLineRenderableSeries3D,
GradientColorPalette,
EDrawMeshAs,
LegendModifier,
ELegendPlacement,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier,
OrbitModifier3D,
MouseWheelZoomModifier3D,
ResetCamera3DModifier
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"

// --- SVM maths (plain JavaScript, no library needed) ---

// Kernels: each one returns the dot product of two points in some feature space, without building that space.
// Points are arrays of numbers, so the same code works for 2D points and for the lifted 3D points.
const dot = (a, b) => a.reduce((sum, v, k) => sum + v * b[k], 0);
function makeKernel(kind, gamma, degree) {
if (kind === "linear") return dot;
if (kind === "polynomial") return (a, b) => Math.pow(gamma * dot(a, b) + 1, degree);
return (a, b) => Math.exp(-gamma * a.reduce((sum, v, k) => sum + (v - b[k]) * (v - b[k]), 0)); // RBF
}

// Train a soft-margin SVM with sequential minimal optimisation (SMO), as in LIBSVM: solve the dual problem
// minimise ½ Σ Σ αi αj yi yj K(xi, xj) − Σ αi, subject to 0 ≤ αi ≤ C and Σ αi yi = 0,
// by repeatedly picking the pair of α values that most violates the optimality conditions (second-order
// working-set selection, Fan, Chen and Lin 2005) and solving for that pair exactly.
function trainSvm(points, y, kernel, C, tolerance = 1e-3, maxSteps = 50000) {
const n = points.length;
const K = new Float64Array(n * n); // the kernel matrix, computed once
for (let i = 0; i < n; i++) {
for (let j = i; j < n; j++) K[i * n + j] = K[j * n + i] = kernel(points[i], points[j]);
}
const alpha = new Float64Array(n);
const grad = new Float64Array(n).fill(-1); // gradient of the dual objective; at α = 0 every entry is −1
const inUp = (t) => (y[t] > 0 ? alpha[t] < C : alpha[t] > 0);
const inLow = (t) => (y[t] > 0 ? alpha[t] > 0 : alpha[t] < C);
let steps = 0;
for (; steps < maxSteps; steps++) {
let i = -1;
let gMax = -Infinity;
for (let t = 0; t < n; t++) {
if (inUp(t) && -y[t] * grad[t] >= gMax) {
gMax = -y[t] * grad[t];
i = t;
}
}
let j = -1;
let gMin = Infinity;
let best = Infinity;
for (let t = 0; t < n && i >= 0; t++) {
if (!inLow(t)) continue;
const v = -y[t] * grad[t];
gMin = Math.min(gMin, v);
const b = gMax - v;
if (b > 0) {
const a = Math.max(K[i * n + i] + K[t * n + t] - 2 * K[i * n + t], 1e-12);
if (-(b * b) / a <= best) {
best = -(b * b) / a;
j = t;
}
}
}
if (i < 0 || j < 0 || gMax - gMin < tolerance) break; // optimal, to within the tolerance
const oldI = alpha[i];
const oldJ = alpha[j];
const a = Math.max(K[i * n + i] + K[j * n + j] - 2 * K[i * n + j], 1e-12);
if (y[i] !== y[j]) {
const delta = (-grad[i] - grad[j]) / a;
const diff = alpha[i] - alpha[j]; // stays constant, so Σ αi yi stays 0
alpha[i] += delta;
alpha[j] += delta;
if (diff > 0 && alpha[j] < 0) [alpha[j], alpha[i]] = [0, diff];
if (diff <= 0 && alpha[i] < 0) [alpha[i], alpha[j]] = [0, -diff];
if (diff > 0 && alpha[i] > C) [alpha[i], alpha[j]] = [C, C - diff];
if (diff <= 0 && alpha[j] > C) [alpha[j], alpha[i]] = [C, C + diff];
} else {
const delta = (grad[i] - grad[j]) / a;
const sum = alpha[i] + alpha[j]; // stays constant
alpha[i] -= delta;
alpha[j] += delta;
if (sum > C && alpha[i] > C) [alpha[i], alpha[j]] = [C, sum - C];
if (sum <= C && alpha[j] < 0) [alpha[j], alpha[i]] = [0, sum];
if (sum > C && alpha[j] > C) [alpha[j], alpha[i]] = [C, sum - C];
if (sum <= C && alpha[i] < 0) [alpha[i], alpha[j]] = [0, sum];
}
const dI = alpha[i] - oldI;
const dJ = alpha[j] - oldJ;
for (let t = 0; t < n; t++) grad[t] += y[t] * (y[i] * K[t * n + i] * dI + y[j] * K[t * n + j] * dJ);
}
// The offset: averaged over the "free" support vectors (0 < α < C), which lie exactly on the margin
let sum = 0;
let free = 0;
let upper = Infinity;
let lower = -Infinity;
for (let t = 0; t < n; t++) {
const yg = y[t] * grad[t];
if (alpha[t] > 0 && alpha[t] < C) {
sum += yg;
free++;
} else if ((alpha[t] >= C) === (y[t] < 0)) upper = Math.min(upper, yg);
else lower = Math.max(lower, yg);
}
const rho = free > 0 ? sum / free : (upper + lower) / 2;
const support = [];
for (let t = 0; t < n; t++) if (alpha[t] > 1e-8) support.push(t);
// f(x) = Σ αi yi K(xi, x) − ρ: positive on the +1 side, 0 on the boundary, ±1 on the margins
const decision = (p) => support.reduce((s, t) => s + alpha[t] * y[t] * kernel(points[t], p), 0) - rho;
return { alpha, rho, support, steps, converged: steps < maxSteps, decision };
}

// For a linear kernel the weights can be written out: w = Σ αi yi xi, and the margin is 2 / ‖w‖ wide
const weights = (model, points, y) =>
points[0].map((_, k) => model.support.reduce((s, t) => s + model.alpha[t] * y[t] * points[t][k], 0));

// The kernel trick made explicit: lift (x1, x2) to (x1, x2, x1² + x2²)
const lift = (p) => [p[0], p[1], p[0] * p[0] + p[1] * p[1]];

// Where a plane w1 x1 + w2 x2 + w3 z = ρ meets the paraboloid z = x1² + x2²: completing the square gives
// a circle in 2D. Returns null when there is no such circle inside the view.
function planeCircle(w, rho, extent) {
if (Math.abs(w[2]) < 1e-9) return null;
const cx = -w[0] / (2 * w[2]);
const cy = -w[1] / (2 * w[2]);
const r2 = rho / w[2] + cx * cx + cy * cy;
if (r2 <= 0) return null;
const r = Math.sqrt(r2);
return Math.abs(cx) + r <= extent && Math.abs(cy) + r <= extent ? { cx, cy, r } : null;
}

// --- The charts ---
const theme = new SciChartJsNavyTheme();
const COLOUR_NEG = "#50C7E0";
const COLOUR_POS = "#F48420";
const GRID = 121; // heatmap cells per side
const MESH = 41; // 3D surface cells per side

// 1. The 2D chart: decision-function heatmap, boundary and margin contours, training points, support vectors
const { sciChartSurface, wasmContext } = await SciChartSurface.create(ui.chart2dDiv, { theme });
const xAxis = new NumericAxis(wasmContext, { axisTitle: "Feature 1", labelPrecision: 1 });
const yAxis = new NumericAxis(wasmContext, { axisTitle: "Feature 2", axisAlignment: EAxisAlignment.Left, labelPrecision: 1 });
sciChartSurface.xAxes.add(xAxis);
sciChartSurface.yAxes.add(yAxis);
const zEmpty = () => Array.from({ length: GRID }, () => new Array(GRID).fill(0));
const heatmapData = new UniformHeatmapDataSeries(wasmContext, { xStart: 0, xStep: 1, yStart: 0, yStep: 1, zValues: zEmpty() });
const contourData = new UniformHeatmapDataSeries(wasmContext, { xStart: 0, xStep: 1, yStart: 0, yStep: 1, zValues: zEmpty() });
const heatmap = new UniformHeatmapRenderableSeries(wasmContext, {
dataSeries: heatmapData,
opacity: 0.85,
// f(x) from −2 (deep blue, the −1 side) through 0 (navy) to +2 (deep orange, the +1 side)
colorMap: new HeatmapColorMap({
minimum: -2,
maximum: 2,
gradientStops: [
{ offset: 0, color: "#156B87" },
{ offset: 0.5, color: "#253556" },
{ offset: 1, color: "#B8601A" }
]
})
});
const contour = (levels, color, strokeThickness) =>
new UniformContoursRenderableSeries(wasmContext, {
dataSeries: contourData,
zLevels: levels,
majorLineStyle: { color, strokeThickness },
minorLineStyle: { color, strokeThickness },
stroke: color,
strokeThickness
});
const boundary = contour([0], "#FFFFFF", 3);
const margins = contour([-1, 1], "#FFFFFFAA", 1.5);
const negativeData = new XyDataSeries(wasmContext, { dataSeriesName: "Class −1" });
const positiveData = new XyDataSeries(wasmContext, { dataSeriesName: "Class +1" });
const supportData = new XyDataSeries(wasmContext, { dataSeriesName: "Support vectors" });
const scatter = (dataSeries, fill) =>
new XyScatterRenderableSeries(wasmContext, {
dataSeries,
stroke: fill, // the legend shows this colour
pointMarker: new EllipsePointMarker(wasmContext, { width: 8, height: 8, fill, stroke: "#0B1A33", strokeThickness: 1 })
});
const negatives = scatter(negativeData, COLOUR_NEG);
const positives = scatter(positiveData, COLOUR_POS);
const supportRings = new XyScatterRenderableSeries(wasmContext, {
dataSeries: supportData,
stroke: "#FFFFFF",
pointMarker: new EllipsePointMarker(wasmContext, { width: 15, height: 15, fill: "#00000000", stroke: "#FFFFFF", strokeThickness: 2 })
});
sciChartSurface.renderableSeries.add(heatmap, margins, boundary, negatives, positives, supportRings);
const legend = new LegendModifier({ showCheckboxes: false, placement: ELegendPlacement.TopLeft });
const cursor = new CursorModifier({ showTooltip: true, showAxisLabels: false });
sciChartSurface.chartModifiers.add(legend, cursor, new MouseWheelZoomModifier(), new ZoomPanModifier(), new ZoomExtentsModifier());
for (const series of [heatmap, boundary, margins]) legend.includeSeries(series, false);
for (const series of [boundary, margins, supportRings]) cursor.includeSeries(series, false);

// 2. The 3D chart: points lifted onto the paraboloid z = x1² + x2², and the plane a linear SVM finds there.
// In SciChart.js 3D, Y is up, so the lifted value z goes on the Y axis and Feature 2 on the Z axis.
const chart3d = await SciChart3DSurface.create(ui.chart3dDiv, {
theme,
worldDimensions: new Vector3(300, 200, 300),
cameraOptions: { position: new Vector3(-400, 300, -460), target: new Vector3(0, 30, 0) }
});
const surface3d = chart3d.sciChart3DSurface;
const wasm3d = chart3d.wasmContext;
surface3d.xAxis = new NumericAxis3D(wasm3d, { axisTitle: "Feature 1", labelPrecision: 1 });
surface3d.yAxis = new NumericAxis3D(wasm3d, { axisTitle: "z = x1² + x2²", labelPrecision: 1 });
surface3d.zAxis = new NumericAxis3D(wasm3d, { axisTitle: "Feature 2", labelPrecision: 1 });
const gridSeries = () => new UniformGridDataSeries3D(wasm3d, { yValues: [[0, 0], [0, 0]], xStart: 0, xStep: 1, zStart: 0, zStep: 1 });
const paraboloidData = gridSeries();
const planeData = gridSeries();
const paraboloid = new SurfaceMeshRenderableSeries3D(wasm3d, {
dataSeries: paraboloidData,
drawMeshAs: EDrawMeshAs.SOLID_WIREFRAME,
stroke: "#C8D3E8",
strokeThickness: 1,
opacity: 0.35,
drawSkirt: false,
meshColorPalette: new GradientColorPalette(wasm3d, {
gradientStops: [
{ offset: 0, color: "#264B93" },
{ offset: 1, color: "#8E6CD8" }
]
})
});
const plane = new SurfaceMeshRenderableSeries3D(wasm3d, {
dataSeries: planeData,
drawMeshAs: EDrawMeshAs.SOLID_MESH,
opacity: 0.6,
drawSkirt: false,
meshColorPalette: new GradientColorPalette(wasm3d, {
gradientStops: [
{ offset: 0, color: "#3BD16F" },
{ offset: 1, color: "#3BD16F" }
]
})
});
const liftedData = new XyzDataSeries3D(wasm3d, { dataSeriesName: "Lifted points" });
const circleData = new XyzDataSeries3D(wasm3d, { dataSeriesName: "Plane meets paraboloid" });
const lifted = new ScatterRenderableSeries3D(wasm3d, {
dataSeries: liftedData,
pointMarker: new SpherePointMarker3D(wasm3d, { size: 7, fill: "#FFFFFF" })
});
const circle = new PointLineRenderableSeries3D(wasm3d, {
dataSeries: circleData,
stroke: "#FFFFFF",
strokeThickness: 4
});
surface3d.renderableSeries.add(paraboloid, plane, lifted, circle);
surface3d.chartModifiers.add(new OrbitModifier3D(), new MouseWheelZoomModifier3D(), new ResetCamera3DModifier());

// --- Training and redrawing ---
const argb = (hex) => (0xff000000 | parseInt(hex.slice(1), 16)) >>> 0; // vertex colours are ARGB numbers
let data;
let points;
let liftedModel;
let liftedW;

// Retrain both models and redraw: runs when the dataset, kernel, degree, C or gamma changes
function onModelChanged() {
const C = Math.pow(10, Number(ui.cInput.value));
const gamma = Math.pow(10, Number(ui.gammaInput.value));
const kind = ui.kernelSelect.value;
const degree = Number(ui.degreeSelect.value);
ui.cOutput.textContent = C < 1 ? C.toFixed(2) : C.toPrecision(2).replace(/\.0$/, "");
ui.gammaOutput.textContent = gamma < 1 ? gamma.toFixed(2) : gamma.toPrecision(2).replace(/\.0$/, "");
ui.gammaInput.disabled = kind === "linear";
ui.degreeSelect.disabled = kind !== "polynomial";

const name = ui.datasetSelect.value;
data = makeDataset(name, 11);
const test = makeDataset(name, 4242);
points = data.x.map((x, i) => [x, data.y[i]]);
const kernel = makeKernel(kind, gamma, degree);
const model = trainSvm(points, data.label, kernel, C);

// Decision function on a grid, for the heatmap and the contours
const e = data.extent;
const step = (2 * e) / GRID;
const z = [];
for (let r = 0; r < GRID; r++) {
const row = new Array(GRID);
for (let c = 0; c < GRID; c++) row[c] = model.decision([-e + (c + 0.5) * step, -e + (r + 0.5) * step]);
z.push(row);
}
for (const series of [heatmapData, contourData]) {
series.xStart = -e;
series.yStart = -e;
series.xStep = step;
series.yStep = step;
series.setZValues(z);
}
xAxis.visibleRange = new NumberRange(-e, e);
yAxis.visibleRange = new NumberRange(-e, e);

for (const { dataSeries, c } of [{ dataSeries: negativeData, c: -1 }, { dataSeries: positiveData, c: 1 }]) {
const idx = data.label.map((l, i) => (l === c ? i : -1)).filter((i) => i >= 0);
dataSeries.clear();
dataSeries.appendRange(idx.map((i) => data.x[i]), idx.map((i) => data.y[i]));
}
supportData.clear();
supportData.appendRange(model.support.map((i) => data.x[i]), model.support.map((i) => data.y[i]));

const accuracy = (set) => {
let right = 0;
for (let i = 0; i < set.x.length; i++) if (Math.sign(model.decision([set.x[i], set.y[i]])) === set.label[i]) right++;
return (100 * right) / set.x.length;
};
let marginText = "";
if (kind === "linear") {
const w = weights(model, points, data.label);
marginText = ` · margin width 2/‖w‖ = ${(2 / Math.hypot(w[0], w[1])).toFixed(2)}`;
}

// The 3D view: a linear SVM on the lifted points (x1, x2, x1² + x2²), with the same C
const liftedPoints = points.map(lift);
liftedModel = trainSvm(liftedPoints, data.label, dot, C);
liftedW = weights(liftedModel, liftedPoints, data.label);
const liftedRight = liftedPoints.filter((p, i) => Math.sign(liftedModel.decision(p)) === data.label[i]).length;

const kernelName = { linear: "Linear", polynomial: `Polynomial (degree ${degree})`, rbf: "RBF" }[kind];
const ring = planeCircle(liftedW, liftedModel.rho, data.extent);
ui.panel.innerHTML =
`<div>2D: ${kernelName} kernel · ${model.support.length} support vectors · training accuracy ` +
`${accuracy(data).toFixed(1)}% · test accuracy ${accuracy(test).toFixed(1)}%${marginText}` +
(model.converged ? "" : " · stopped at the step limit (try a smaller gamma)") +
`</div>` +
`<div>3D: linear SVM on (x1, x2, x1² + x2²) · accuracy ${((100 * liftedRight) / points.length).toFixed(1)}%` +
(ring
? ` · back in 2D, a circle of radius ${ring.r.toFixed(2)} centred at (${ring.cx.toFixed(2)}, ${ring.cy.toFixed(2)})`
: " · no circle inside the view separates these classes") +
`</div>`;
onLiftChanged();
}

// Move the points, the paraboloid, the plane and their intersection: runs when the lift slider moves.
// At lift 0 everything lies flat on the floor; at lift 1, z = x1² + x2².
function onLiftChanged() {
const t = Number(ui.liftInput.value);
ui.liftOutput.textContent = t.toFixed(2);
const e = data.extent;
const top = e * e * 1.05; // the paraboloid is cut off at radius e
surface3d.xAxis.visibleRange = new NumberRange(-e, e);
surface3d.zAxis.visibleRange = new NumberRange(-e, e);
surface3d.yAxis.visibleRange = new NumberRange(0, top);
const clamp = (v) => Math.max(0, Math.min(top, v));
const step = (2 * e) / (MESH - 1);
const [w1, w2, w3] = liftedW;
const bowl = [];
const flat = [];
for (let r = 0; r < MESH; r++) {
const b = [];
const f = [];
for (let c = 0; c < MESH; c++) {
const x1 = -e + c * step;
const x2 = -e + r * step;
b.push(clamp(t * (x1 * x1 + x2 * x2)));
// The plane w·(x1, x2, z) = ρ, solved for z, and scaled by the lift like everything else
f.push(clamp((t * (liftedModel.rho - w1 * x1 - w2 * x2)) / w3));
}
bowl.push(b);
flat.push(f);
}
for (const { series, values } of [{ series: paraboloidData, values: bowl }, { series: planeData, values: flat }]) {
series.xStart = -e;
series.zStart = -e;
series.xStep = step;
series.zStep = step;
series.setYValues(values);
}
const xs = [];
const ys = [];
const zs = [];
const meta = [];
points.forEach((p, i) => {
xs.push(p[0]);
ys.push(t * (p[0] * p[0] + p[1] * p[1]));
zs.push(p[1]);
meta.push({ vertexColor: argb(data.label[i] < 0 ? COLOUR_NEG : COLOUR_POS) });
});
liftedData.clear();
liftedData.appendRange(xs, ys, zs, meta);

// Where the plane meets the paraboloid: x1² + x2² = (ρ − w1 x1 − w2 x2) / w3, a circle in 2D
circleData.clear();
const ring = planeCircle(liftedW, liftedModel.rho, e);
if (ring) {
const cxs = [];
const cys = [];
const czs = [];
for (let k = 0; k <= 120; k++) {
const a = (2 * Math.PI * k) / 120;
const x1 = ring.cx + ring.r * Math.cos(a);
const x2 = ring.cy + ring.r * Math.sin(a);
cxs.push(x1);
cys.push(t * (x1 * x1 + x2 * x2));
czs.push(x2);
}
circleData.appendRange(cxs, cys, czs);
}
}

// Retrain at most once per frame while a slider is dragged
let pending = false;
const retrain = () => {
if (pending) return;
pending = true;
requestAnimationFrame(() => {
pending = false;
onModelChanged();
});
};
for (const element of [ui.datasetSelect, ui.kernelSelect, ui.degreeSelect]) element.addEventListener("change", retrain);
for (const element of [ui.cInput, ui.gammaInput]) element.addEventListener("input", retrain);
ui.liftInput.addEventListener("input", onLiftChanged);
ui.animateButton.addEventListener("click", () => {
const start = performance.now();
const frame = (now) => {
const t = Math.min(1, (now - start) / 2500);
ui.liftInput.value = String(t);
onLiftChanged();
if (t < 1) requestAnimationFrame(frame);
};
requestAnimationFrame(frame);
});
onModelChanged();

Key points:

  • The decision function is sampled on a grid into a UniformHeatmapDataSeries, drawn by a UniformHeatmapRenderableSeries with a three-stop HeatmapColorMap centred on 0. The same data feeds two UniformContoursRenderableSeries, with zLevels: [0] for the boundary and zLevels: [-1, 1] for the margins.
  • Support vectors are a second XyScatterRenderableSeries with a larger, hollow EllipsePointMarker (a transparent fill and a white stroke) drawn over the class points.
  • The 3D view is a SciChart3DSurface. The paraboloid and the plane are two SurfaceMeshRenderableSeries3D over UniformGridDataSeries3D grids, with opacity so the points show through; the points are a ScatterRenderableSeries3D with per-point vertexColor metadata, and the intersection circle is a PointLineRenderableSeries3D. Y is the vertical axis in SciChart.js 3D, so the lift goes on Y.
  • Each slider move retrains and redraws, at most once per animation frame. Updating a data series with setZValues, setYValues or appendRange redraws the chart.

See it in the demo app: JavaScript 3D surface mesh chart · React 3D surface mesh chart · Angular 3D surface mesh chart, and for the 2D view, JavaScript heatmap chart · React heatmap chart · Angular heatmap chart.

Go deeper: SciChart.js 3D surface mesh documentation, the 3D scatter chart documentation, the uniform heatmap documentation and contours documentation, and the guides to the heatmap and contour plot. For how inspection and test software uses SciChart, see SciChart for semiconductors.

Frequently asked questions​

What is a support vector machine in simple terms?​

A support vector machine is a classifier that separates two groups of points with the widest possible gap. It draws a line (in 2D), a plane (in 3D) or a hyperplane (in more dimensions) so that the nearest points of each class are as far from it as they can be. Those nearest points are the support vectors, and they alone fix where the boundary goes. With a kernel, the same method draws curved boundaries.

What are support vectors?​

Support vectors are the training points that lie on the edge of the margin, inside it, or on the wrong side of the boundary. They are the only points with a non-zero weight in the trained model, so the boundary depends on them alone: delete every other training point and you get the same classifier. A model with few support vectors is compact and fast to evaluate; when most points are support vectors, C is small or the classes overlap heavily.

What is the kernel trick?​

The kernel trick lets a linear method draw curved boundaries. Data that no straight line can split often becomes separable after mapping each point into more dimensions, for example lifting (x1, x2) to (x1, x2, x1² + x2²). An SVM only ever needs dot products between points, so instead of building the new coordinates it calls a kernel function that returns their dot product directly. The RBF kernel corresponds to an infinite number of dimensions, which could never be built explicitly.

What do C and gamma do in an SVM?​

C sets how much a soft-margin SVM is penalised for each point inside the margin or on the wrong side. A small C gives a wide margin that ignores some points; a large C bends the boundary to fit almost every training point. Gamma belongs to the RBF and polynomial kernels and sets how far each point's influence reaches. A small gamma gives smooth, nearly linear boundaries; a large gamma gives tight islands around single points, which overfits. Tune the two together with cross-validation.

Is an SVM better than logistic regression?​

Neither is better in general. A linear SVM and logistic regression both draw a straight boundary and often score within a point or two of each other; the SVM uses only the points near the boundary, while logistic regression uses every point and gives probabilities. A kernel SVM can draw curved boundaries that logistic regression cannot without hand-made features, but it trains slowly on hundreds of thousands of rows. Try both on held-out data.

How do I visualise an SVM decision boundary in JavaScript?​

Train the SVM, then evaluate its decision function f(x) on a regular grid across the feature space. Draw the grid as a heatmap, with one colour for negative values and another for positive, and draw contour lines at f = 0 for the boundary and f = -1 and +1 for the margins. Plot the training points on top as a scatter series and ring the support vectors. SciChart.js provides UniformHeatmapRenderableSeries, UniformContoursRenderableSeries and XyScatterRenderableSeries for these layers, in JavaScript, React and Angular alike.

Sources​