Skip to main content

Decision Boundary

What is a decision boundary?​

A decision boundary is the line or surface that separates the regions where a classifier predicts different classes. On one side the model says "class A", on the other "class B". For a model that outputs probabilities, it is the contour where the two classes are equally likely, usually a probability of 0.5.

A grid of eighteen small charts in a dark navy theme: three rows of datasets (two interleaved moons, a ring around a smaller ring, and two overlapping clusters) and six columns of classifiers (nearest neighbours, logistic regression, decision tree, random forest, naive Bayes and an RBF support vector machine). Each panel is a red-to-blue probability heatmap with a white boundary line, red and blue training points and paler test points, and the test accuracy in the bottom-right corner

Decision boundaries of six classifiers on three synthetic datasets, each trained in the browser, with test accuracy in the corner (sample data). Try the interactive version.

Key takeaways
  • A decision boundary is where a classifier's predicted class changes; with probabilities, it is the 0.5 contour.
  • Every family of model draws its own kind of boundary: straight lines, smooth curves, axis-aligned steps or jagged edges.
  • A boundary that bends around single training points is overfitting; one too simple to follow the classes is underfitting.
  • Judge a boundary by its accuracy on held-out test points, not on the points it was trained on.
  • To draw one, evaluate the model on a fine grid, colour the grid by probability and overlay the data.

How a decision boundary works​

A classifier is a model that assigns each input to one of a fixed set of classes: spam or not spam, defective or good, one species of iris or another. The inputs are its features, the measured values for each case. With two features, every case is a point on a flat plane, and the classifier's job is to colour the whole plane by the class it would predict there.

Most classifiers don't jump straight to a class. They compute a score or probability for each class, and then pick the largest. For two classes that means predicting class B wherever P(B) is above 0.5. The decision boundary is the set of points where P(B) is exactly 0.5, so it is a contour line of the probability surface, in the same way a contour on a map joins points of equal height.

A few properties follow from that:

  • Linear and non-linear boundaries. A boundary is linear when it is a straight line in two dimensions, a flat plane in three, or a hyperplane in more. Logistic regression and linear discriminant analysis always draw linear boundaries in the features they are given. Anything else is a non-linear boundary.
  • Confidence. The probability changes gradually near the boundary for most models. Points deep inside a region are predicted with confidence; points near the boundary are close calls. A plot of the probability shows both; a plot of the predicted class alone hides the difference.
  • More than two classes. Each pair of neighbouring regions has its own stretch of boundary. The plane is split into one region per class, and a region can be in several pieces.
  • The Bayes decision boundary. If you knew the true probability of each class at every point, the best possible boundary would be where those true probabilities are equal. Its error rate, the Bayes error, is the floor no classifier can beat. Synthetic datasets are useful for teaching because that boundary is known.

The boundary is a property of the trained model, not of the data alone. The same points give a different boundary with a different model, a different setting or a different training sample, which is what makes boundary plots such a good way to compare models.

How to read a decision boundary plot​

An annotated decision boundary plot of two features. A dark curved line splits a red region on the left from a blue region on the right. Dashed curves either side mark probabilities of 0.25 and 0.75, with a paler band between them. Solid dots are training points and pale outlined dots are test points. One pale blue test point on the red side is circled. A box in the corner reads Test: 92%. Numbered badges 1 to 6 match a list beside the plot

  1. The boundary. The line where the colour changes is where the predicted class flips. Check whether its shape is plausible for the problem: smooth, stepped, straight or ragged.
  2. The colour depth. Deep red or deep blue means the model is confident. A good model is confident where the training data is dense and one-sided, and less sure elsewhere.
  3. The pale band. The strip where the probability is between about 0.25 and 0.75 is the uncertain zone. A wide band means the model hedges near the boundary; a razor-thin band means it is certain everywhere, which is often a sign of overfitting.
  4. The points. Solid dots are the training data the model learnt from; paler dots are held-out test points it has never seen. A model can draw around every training point and still misplace test points.
  5. Points on the wrong side. Each test point inside the other class's colour is a misclassification. A few are expected where the classes overlap.
  6. The accuracy figure. The share of test points that land on the correct side, which is the number that predicts how the model will do on new data.

Also look at the edges of the plot, far from any data. Models extrapolate very differently there: logistic regression keeps its straight line going for ever, a tree keeps its last step, and an RBF support vector machine falls back to a constant offset, so the colour there says more about the model than about the data.

How each classifier shapes the decision boundary​

The shape of the boundary comes from the model's assumptions. This is the main reason the same dataset looks so different across the panels of a classifier comparison grid, such as the scikit-learn classifier comparison, the best-known version of the picture, and the live demo on this page.

Six schematic panels, each split into a red region and a blue region. Logistic regression and LDA: a straight line. RBF SVM: a smooth closed curve. Decision tree: a staircase of horizontal and vertical steps. Random forest: a finer staircase that follows a curve, with faint copies for the averaged trees. k-nearest neighbours with k = 1: a jagged line with small islands of the other class. Naive Bayes and QDA: an ellipse

ClassifierBoundary shapeWhat controls itProbability output
k-nearest neighbours (k-NN)Local and jagged at small k; smoother as k growsk, the number of neighbours that vote; the distance measureShare of the k neighbours in each class, so it moves in steps of 1/k
Logistic regressionA straight line (hyperplane)Regularization strength C; the features you feed itSmooth S-shaped rise across the line
Linear SVMA straight line, placed to maximise the marginCA signed distance from the line, not a probability
RBF SVMSmooth curves of almost any shape, including closed loopsgamma (how local each point's influence is) and CA signed distance; needs calibrating to become a probability
Decision treeAxis-aligned steps (rectangles)Maximum depth, minimum points per leafShare of each class in the leaf, so flat within each rectangle
Random forestMany fine steps, averaged into a rougher curveNumber of trees, depth, features tried per splitAverage of the trees, so it changes in small steps
Gaussian naive BayesA quadratic curve (line, ellipse, parabola or hyperbola)Fitted mean and variance of each feature in each classBayes' rule on two bell-shaped densities
LDAA straight lineShared covariance of the classesSmooth, as for logistic regression
QDAA quadratic curveA separate covariance for each classSmooth

k-nearest neighbours (KNN)​

k-nearest neighbours classifies a new point by finding the k training points closest to it and taking a vote. It learns nothing in advance: the "model" is the training set itself. The boundary runs halfway between nearby points of different classes, so with k = 1 it follows every training point and can wrap islands around single outliers. Raising k averages over more neighbours and smooths the boundary, until at very large k it ignores the local shape altogether.

Distances depend on the scale of each feature, so standardise the features first, or a feature measured in thousands will dominate one measured in fractions. And with two classes, an odd k avoids tied votes. Cover and Hart showed in 1967 that, with enough data, the error of the 1-nearest-neighbour rule is at most twice the Bayes error.

Logistic regression and linear SVMs​

Logistic regression fits a weighted sum of the features, w₀ + w₁x₁ + w₂x₂, and passes it through the logistic (sigmoid) function to get a probability. The boundary is where the weighted sum is zero, which is a straight line. However much data you give it, the boundary stays straight; to get a curve you must add curved features yourself, such as x₁², x₂² or x₁x₂. Regularization, set by C, shrinks the weights: a small C gives a wide, gentle transition and a large C a sharp one.

A linear support vector machine also draws a straight line, but it places it as far as possible from the nearest points of each class, the margin. On cleanly separated data the two lines are often close; they differ in how much attention they pay to points far from the boundary.

RBF support vector machines​

A support vector machine with a radial basis function (RBF) kernel builds its decision function from bumps centred on a few training points, the support vectors. The result is a smooth boundary that can curve, bend back and enclose regions, which is why it handles the circles dataset that defeats every straight line. Its setting gamma controls how wide each bump is: a small gamma gives broad, gentle curves; a large gamma gives tight bumps around individual points. C trades a wide margin against classifying every training point correctly. The support vector machine guide explains the kernel trick behind it.

Decision trees​

A decision tree asks a sequence of yes-or-no questions, each about one feature: "is feature 1 below 0.3?", then "is feature 2 above 1.2?", and so on until it reaches a leaf that predicts a class. Every question cuts the plane with a vertical or horizontal line, so the boundary is a staircase of axis-aligned steps. A diagonal boundary needs many small steps to approximate. Depth is the main control: a depth-1 tree (a "stump") makes one cut, while a deep tree can carve a rectangle around every training point.

Random forests​

A random forest grows many decision trees, each on a bootstrap sample of the training data (drawn with replacement) and with a random choice of features at each split, then averages their predictions. Each tree's staircase sits in a slightly different place, so the average has many small steps and follows a curved boundary much better than one tree. More trees make the average steadier, but they don't make each tree simpler, so a forest of deep trees can still hug the training points.

Naive Bayes​

Gaussian naive Bayes models each class as a bell-shaped (normal) distribution along each feature, and assumes the features are independent within a class. Bayes' rule then turns the two densities and the share of each class into a probability. Because each class has its own variances, the boundary is a quadratic curve. When one class is tightly clustered and the other spread around it, as in the circles dataset, the boundary closes into an ellipse, which is why naive Bayes does surprisingly well there. When the classes form curved shapes such as the moons, it can't follow them.

LDA and QDA​

Linear discriminant analysis (LDA) also fits a normal distribution to each class, but with one covariance shared by both classes, which makes the boundary a straight line. Quadratic discriminant analysis (QDA) gives each class its own covariance and draws a quadratic boundary, like naive Bayes without the independence assumption, so its ellipses can tilt to follow correlated features.

Overfitting and underfitting in decision boundaries​

A decision boundary plot shows the trade-off between overfitting and underfitting directly.

  • Overfitting (high variance) is a boundary that bends to fit noise: islands around single points, a thin band of uncertainty, and near-perfect training accuracy that doesn't carry over to test points.
  • Underfitting (high bias) is a boundary too simple for the data: a straight line across rings, or a tree stopped at one split. Training and test accuracy are both low.

Some examples from the live demo, at its default noise and sample, show the pattern (with 40 test points, one point is 2.5 percentage points, so small differences are noise):

SettingDatasetTraining accuracyTest accuracyWhat the boundary looks like
RBF SVM, gamma = 100Moons98%43%Tight blobs around each training point; most of the plane falls back to one class
RBF SVM, gamma = 2Moons93%85%A smooth S-curve between the moons
Decision tree, depth 12Linear100%78%Small rectangles around stray points
Decision tree, depth 1Linear88%93%One straight cut
k-NN, k = 30Circles50%50%Half the training set votes every time, so the whole plane is one colour
k-NN, k = 5Circles87%88%A rough ring
Logistic regressionCircles52%53%A straight line through two rings

The gap between training and test accuracy is the clearest single sign of overfitting. The settings that control it are the ones in the table above: k for k-NN, depth for trees, gamma and C for RBF SVMs, and C for logistic regression. Choose them by cross-validation on the training data, not by looking at the test score.

Training points, test points and accuracy​

A boundary always looks good on the points it was fitted to: a 1-nearest-neighbour model scores 100% on its own training data by construction. To measure how a model will do on new cases, hold some data back. The usual split keeps 20 to 40% as a test set, which the model never sees during training.

Accuracy is the share of test points on the correct side of the boundary. It is easy to read off a plot, but it hides which kind of mistake is made and assumes a 0.5 threshold. When classes are unbalanced or one error costs more than the other, use the probability output and look at a ROC curve and precision-recall curve as well.

With small test sets, accuracy is noisy. In the demo, 40 test points per dataset means each misclassified point costs 2.5 percentage points, and the New sample button shows how much the figures move between samples of the same distribution.

Classification vs regression​

Decision boundaries belong to classification, which predicts a category. Regression predicts a number, and has no boundary to draw: its equivalent picture is the fitted curve or surface, checked with a residual plot.

ClassificationRegression
PredictsA class label (spam / not spam) and often its probabilityA continuous value (price, temperature)
Typical modelsk-NN, logistic regression, trees, forests, SVMs, naive BayesLinear regression, trees, forests, k-NN, SVR
Measured byAccuracy, precision and recall, ROC AUC, log lossMean squared error, mean absolute error, R²
PictureDecision boundary over a probability heatmapFitted line or surface, residual plot

Many algorithms come in both forms. A k-NN regressor averages its neighbours' values instead of voting, and a regression tree predicts the mean value in each leaf. Logistic regression, despite its name, is mostly used for classification: it models the probability of each class, and a threshold turns that into a label.

How to draw a decision boundary​

To draw a decision boundary, ask the model for a class probability at every point of a fine grid, colour the grid by it and trace where it crosses 0.5. This works for any model that can make a prediction, in any language:

  1. Pick two features to plot, and train the model (on those two features, or on all of them).
  2. Build a fine grid covering the range of the data plus a margin, for example 100 × 100 points.
  3. Ask the model for the probability of one class at every grid point.
  4. Draw the grid as a heatmap with a diverging colour map, so the two classes have two colours and the boundary is pale.
  5. Draw the 0.5 contour of the same grid as a line: that line is the decision boundary.
  6. Overlay the training points and, in a lighter style, the test points, coloured by their true class.

A 100 × 100 grid is 10,000 predictions per model, so a grid of 18 panels is 180,000. That's quick for k-NN, trees and small SVMs, but for a slow model use a coarser grid and let the heatmap's interpolation smooth it.

With more than two features, the plot is a slice: fix the other features at typical values (such as their medians) and vary the two you plot. Or project the data to two dimensions first with a method such as PCA, and keep in mind that the boundary you see is then the boundary of a model trained on the projection, not of the original model.

Which classifier to use​

No classifier is best on every dataset, as the grid shows. Some starting points:

If your data…Try firstWhy
Is roughly linearly separable, or you need an explainable modelLogistic regressionStraight boundary, readable weights, calibrated probabilities
Has curved class shapes and a few thousand pointsRBF SVM or k-NNFlexible, smooth boundaries; both need scaled features
Mixes units and categories, or needs rules people can readDecision tree (shallow)Axis-aligned rules that can be written down
Is tabular with many features and you want strong accuracyRandom forest or gradient-boosted treesRobust defaults, little feature scaling needed
Has very many features and little data, such as textNaive BayesFast, needs few examples, often a strong baseline
Has classes that are roughly normal with different spreadsQDA or naive BayesQuadratic boundaries match that shape

Common decision boundary mistakes​

Most misleading boundary plots come from unscaled features, scores measured on the training points, or colour read as more certain than the model is.

  • Not scaling the features. k-NN and RBF SVMs measure distance, so a feature with a larger range dominates and the boundary turns into vertical or horizontal bands. Standardise first, using the training set's mean and standard deviation.
  • Judging a model by its training accuracy. Every flexible model can draw around its own training points. Plot and score held-out points.
  • Choosing settings from the test score. Tuning k, depth or gamma until the test accuracy peaks leaks the test set into training. Tune with cross-validation and keep the test set for the final check.
  • Reading an SVM's shading as a probability. An SVM outputs a signed distance from the boundary. Its colour scale is a choice of the plot, and probabilities need a calibration step such as Platt scaling.
  • Trusting the colour far from the data. Every model extrapolates its own way, and confident colour in an empty corner reflects the model's form, not evidence.
  • Plotting a 2D slice of a many-feature model as if it were the whole model. The boundary moves when the hidden features change. Say which values they were fixed at.
  • Drawing only the predicted class. A two-colour plot hides how confident the model is. Show the probability as a heatmap and the boundary as a contour.
  • Comparing models on one small sample. With 40 test points, a 5-point difference in accuracy is two points. Repeat over several samples or use cross-validation.

How to plot a decision boundary in JavaScript, React or Angular​

Each change of noise, sample or setting in the demo retrains the models and redraws all 18 panels, each a 100 × 100 heatmap with its contour and points. Every model is trained in the browser in plain JavaScript; nothing is precomputed.

Choose a Dataset to show all three rows or one larger set of panels, and drag Noise to blur the classes. New sample draws fresh points from the same distributions. Tune picks a setting (k, C, tree depth, number of trees or the RBF SVM's gamma and C), and the slider beside it changes that setting; the panels it affects are outlined. Click adds chooses the class of the point added when you click a panel. Hover a panel to read the model's probability; the mouse wheel zooms a panel, dragging pans it and a double-click resets it.

Here is the code for this chart. The six classifiers are short, commented functions; each returns a function that gives the probability of the blue class at any point. SciChart.js draws each panel as a uniform heatmap of that probability, a contour at 0.5 and scatter series for the points. The models are simplified teaching versions: the random forest uses depth-5 trees, naive Bayes is the Gaussian form, and the RBF SVM is trained with a basic SMO solver and shades its decision function through a logistic curve rather than a calibrated probability.

// Decision boundaries of six classifiers on three datasets, trained in the browser and charted with SciChart.js
const {
SciChartSurface,
NumericAxis,
NumberRange,
Thickness,
UniformHeatmapDataSeries,
UniformHeatmapRenderableSeries,
UniformContoursRenderableSeries,
HeatmapColorMap,
XyDataSeries,
XyScatterRenderableSeries,
EllipsePointMarker,
TextAnnotation,
ECoordinateMode,
EHorizontalAnchorPoint,
EVerticalAnchorPoint,
CustomChartModifier2D,
translateFromCanvasToSeriesViewRect,
SciChartJsNavyTheme,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"

// --- Classifiers (plain JavaScript, no library needed) ---
// Each one trains on points {x, y, label} and returns predict(x, y): the probability of class 1 (blue).

// k-nearest neighbours: the share of the k closest training points that are blue
function trainKnn(train, k) {
const kk = Math.max(1, Math.min(k, train.length));
return (x, y) => {
const best = []; // the kk smallest squared distances so far, in order, with their labels
for (const p of train) {
const d = (p.x - x) ** 2 + (p.y - y) ** 2;
if (best.length === kk && d >= best[kk - 1].d) continue;
let j = best.length < kk ? best.length : kk - 1;
while (j > 0 && best[j - 1].d > d) {
best[j] = best[j - 1];
j--;
}
best[j] = { d, label: p.label };
}
return best.reduce((sum, b) => sum + b.label, 0) / kk;
};
}

// Logistic regression with an L2 penalty: minimise ½|w|² + C × (log loss), fitted with Newton's method.
// The boundary w0 + w1·x + w2·y = 0 is always a straight line.
function trainLogistic(train, C) {
let w = [0, 0, 0];
for (let iteration = 0; iteration < 50; iteration++) {
const gradient = [0, w[1], w[2]]; // the penalty's gradient (the intercept w0 isn't penalised)
const hessian = [[1e-9, 0, 0], [0, 1, 0], [0, 0, 1]];
for (const p of train) {
const f = [1, p.x, p.y];
const prob = 1 / (1 + Math.exp(-(w[0] + w[1] * p.x + w[2] * p.y)));
for (let a = 0; a < 3; a++) {
gradient[a] += C * (prob - p.label) * f[a];
for (let b = 0; b < 3; b++) hessian[a][b] += C * prob * (1 - prob) * f[a] * f[b];
}
}
const step = solve3(hessian, gradient);
w = w.map((value, a) => value - step[a]);
if (Math.max(...step.map(Math.abs)) < 1e-10) break;
}
return (x, y) => 1 / (1 + Math.exp(-(w[0] + w[1] * x + w[2] * y)));
}

// Solve a 3 × 3 linear system by Gaussian elimination with partial pivoting
function solve3(A, b) {
const m = A.map((row, i) => [...row, b[i]]);
for (let c = 0; c < 3; c++) {
let pivot = c;
for (let r = c + 1; r < 3; r++) if (Math.abs(m[r][c]) > Math.abs(m[pivot][c])) pivot = r;
[m[c], m[pivot]] = [m[pivot], m[c]];
for (let r = c + 1; r < 3; r++) {
const factor = m[r][c] / m[c][c];
for (let k = c; k < 4; k++) m[r][k] -= factor * m[c][k];
}
}
const out = [0, 0, 0];
for (let r = 2; r >= 0; r--) {
let sum = m[r][3];
for (let k = r + 1; k < 3; k++) sum -= m[r][k] * out[k];
out[r] = sum / m[r][r];
}
return out;
}

// Decision tree (CART): split on x or y at the threshold that minimises the Gini impurity of the two halves,
// until maxDepth or until a node is pure. Each leaf predicts the share of blue training points in it.
// With random (a random forest), each split tries one feature chosen at random, and the other only if
// the first can't split the node.
function buildTree(points, depth, maxDepth, random) {
const ones = points.reduce((sum, p) => sum + p.label, 0);
const leaf = { p: ones / points.length };
if (depth >= maxDepth || ones === 0 || ones === points.length) return leaf;
const features = random && random() < 0.5 ? ["y", "x"] : ["x", "y"];
const gini = (n, k) => (n === 0 ? 0 : n * (1 - (k / n) ** 2 - (1 - k / n) ** 2)); // n × impurity
let best;
for (const feature of features) {
if (random && best) break;
const sorted = points.slice().sort((a, b) => a[feature] - b[feature]);
let leftN = 0;
let leftOnes = 0;
for (let i = 0; i < sorted.length - 1; i++) {
leftN++;
leftOnes += sorted[i].label;
if (sorted[i][feature] === sorted[i + 1][feature]) continue; // can't split between equal values
const score = gini(leftN, leftOnes) + gini(sorted.length - leftN, ones - leftOnes);
if (!best || score < best.score) best = { feature, threshold: (sorted[i][feature] + sorted[i + 1][feature]) / 2, score };
}
}
if (!best) return leaf;
const left = points.filter((p) => p[best.feature] <= best.threshold);
const right = points.filter((p) => p[best.feature] > best.threshold);
return {
feature: best.feature,
threshold: best.threshold,
left: buildTree(left, depth + 1, maxDepth, random),
right: buildTree(right, depth + 1, maxDepth, random)
};
}
function predictTree(node, point) {
while (node.feature) node = point[node.feature] <= node.threshold ? node.left : node.right;
return node.p;
}
function trainTree(train, maxDepth) {
const tree = buildTree(train, 0, maxDepth, undefined); // no random: every split tries both features
return (x, y) => predictTree(tree, { x, y });
}

// Random forest: nTrees trees of depth 5, each grown on a bootstrap sample (n points drawn with replacement)
// with a random feature per split. The prediction is the average of the trees' leaf probabilities.
// Tree t always uses the same seed, so adding trees keeps the earlier ones.
function trainForest(train, nTrees) {
const trees = [];
for (let t = 0; t < nTrees; t++) {
const random = seededRandom(1000 + 7919 * t);
const sample = train.map(() => train[Math.floor(random() * train.length)]);
trees.push(buildTree(sample, 0, 5, random));
}
return (x, y) => trees.reduce((sum, tree) => sum + predictTree(tree, { x, y }), 0) / trees.length;
}

// Gaussian naive Bayes: each class is modelled as a normal distribution per feature, with the features
// assumed independent. Bayes' rule turns the two likelihoods and the class shares into a probability.
function trainNaiveBayes(train) {
const stats = [0, 1].map((label) => {
const pts = train.filter((p) => p.label === label);
const mean = (key) => pts.reduce((sum, p) => sum + p[key], 0) / pts.length;
const mx = mean("x");
const my = mean("y");
const vx = pts.reduce((sum, p) => sum + (p.x - mx) ** 2, 0) / pts.length + 1e-9;
const vy = pts.reduce((sum, p) => sum + (p.y - my) ** 2, 0) / pts.length + 1e-9;
return { mx, my, vx, vy, logPrior: Math.log(pts.length / train.length) };
});
const logLikelihood = (s, x, y) =>
s.logPrior - 0.5 * (Math.log(2 * Math.PI * s.vx) + (x - s.mx) ** 2 / s.vx + Math.log(2 * Math.PI * s.vy) + (y - s.my) ** 2 / s.vy);
return (x, y) => 1 / (1 + Math.exp(logLikelihood(stats[0], x, y) - logLikelihood(stats[1], x, y)));
}

// Support vector machine with an RBF kernel K(a, b) = exp(−gamma × |a − b|²), trained with SMO
// (sequential minimal optimisation: repeatedly optimise the pair of points that most violates the
// optimality conditions, as LIBSVM does). The decision function is f = Σ αᵢ yᵢ K(xᵢ, x) − ρ.
// An SVM gives a signed distance, not a probability: the shading is 1 / (1 + e^(−2f)), so the margins
// (f = ±1) are at 0.12 and 0.88.
function trainRbfSvm(train, C, gamma) {
const n = train.length;
const y = train.map((p) => (p.label === 1 ? 1 : -1));
const K = new Float64Array(n * n);
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) K[i * n + j] = Math.exp(-gamma * ((train[i].x - train[j].x) ** 2 + (train[i].y - train[j].y) ** 2));
}
const alpha = new Float64Array(n);
const G = new Float64Array(n).fill(-1); // gradient of the dual objective
for (let iteration = 0; iteration < 100000; iteration++) {
// The maximal violating pair: i can move up, j can move down
let i = -1;
let j = -1;
let gMax = -Infinity;
let gMin = Infinity;
for (let t = 0; t < n; t++) {
const v = -y[t] * G[t];
if ((y[t] === 1 && alpha[t] < C) || (y[t] === -1 && alpha[t] > 0)) {
if (v > gMax) [gMax, i] = [v, t];
}
if ((y[t] === 1 && alpha[t] > 0) || (y[t] === -1 && alpha[t] < C)) {
if (v < gMin) [gMin, j] = [v, t];
}
}
if (gMax - gMin < 1e-3) break; // optimal to within the tolerance
const quad = Math.max(K[i * n + i] + K[j * n + j] - 2 * K[i * n + j], 1e-12);
const oldI = alpha[i];
const oldJ = alpha[j];
if (y[i] !== y[j]) {
const delta = (-G[i] - G[j]) / quad;
const diff = alpha[i] - alpha[j];
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 = (G[i] - G[j]) / quad;
const sum = alpha[i] + alpha[j];
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 k = 0; k < n; k++) G[k] += y[k] * (y[i] * K[i * n + k] * dI + y[j] * K[j * n + k] * dJ);
}
// The offset ρ: the average of yᵢGᵢ over the free support vectors (0 < α < C)
let nFree = 0;
let sumFree = 0;
let upper = Infinity;
let lower = -Infinity;
for (let t = 0; t < n; t++) {
const yG = y[t] * G[t];
if (alpha[t] > 0 && alpha[t] < C) {
nFree++;
sumFree += yG;
} else if ((alpha[t] >= C) === (y[t] === -1)) upper = Math.min(upper, yG);
else lower = Math.max(lower, yG);
}
const rho = nFree > 0 ? sumFree / nFree : (upper + lower) / 2;
const supportVectors = train.map((p, t) => ({ p, coef: alpha[t] * y[t] })).filter((s) => s.coef !== 0);
return (x, yValue) => {
let f = -rho;
for (const s of supportVectors) f += s.coef * Math.exp(-gamma * ((s.p.x - x) ** 2 + (s.p.y - yValue) ** 2));
return 1 / (1 + Math.exp(-2 * f));
};
}

// The classifiers, in panel order, with their tunable settings
const settings = { k: 5, lrC: 1, depth: 5, trees: 30, gamma: 2, svmC: 1 };
const CLASSIFIERS = [
{ name: "Nearest neighbours", tunes: ["k"], caption: () => `k-NN, k = ${settings.k}`, train: (t) => trainKnn(t, settings.k) },
{ name: "Logistic regression", tunes: ["lrC"], caption: () => `Logistic, C = ${fmt(settings.lrC)}`, train: (t) => trainLogistic(t, settings.lrC) },
{ name: "Decision tree", tunes: ["depth"], caption: () => `Tree, depth ${settings.depth}`, train: (t) => trainTree(t, settings.depth) },
{ name: "Random forest", tunes: ["trees"], caption: () => `Forest, ${settings.trees} trees`, train: (t) => trainForest(t, settings.trees) },
{ name: "Naive Bayes", tunes: [], caption: () => "Naive Bayes", train: (t) => trainNaiveBayes(t) },
{
name: "RBF SVM",
tunes: ["gamma", "svmC"],
caption: () => `RBF SVM, γ ${fmt(settings.gamma)}, C ${fmt(settings.svmC)}`,
train: (t) => trainRbfSvm(t, settings.svmC, settings.gamma)
}
];
// Slider ranges for each setting; C and gamma use a log scale
const TUNING = {
k: { min: 1, max: 30, step: 1, log: false },
lrC: { min: -2, max: 2, step: 0.1, log: true },
depth: { min: 1, max: 12, step: 1, log: false },
trees: { min: 1, max: 100, step: 1, log: false },
gamma: { min: -1, max: 2, step: 0.1, log: true },
svmC: { min: -2, max: 3, step: 0.1, log: true }
};
function fmt(v) {
return v >= 10 ? v.toFixed(0) : v >= 1 ? String(Number(v.toFixed(1))) : String(Number(v.toPrecision(2)));
}

const ui = createLayout(divElementId, CLASSIFIERS.map((c) => c.name));

// --- The charts: one SciChartSurface per panel, holding a probability heatmap, the 0.5 contour and the points ---
const GRID = 100; // the model is evaluated on a 100 × 100 grid per panel
const RED = "#FF5A5F";
const BLUE = "#4FA3FF";
const theme = new SciChartJsNavyTheme();
// Diverging colour map: red (P = 0) through pale grey at the boundary (P = 0.5) to blue (P = 1)
const colorMap = new HeatmapColorMap({
minimum: -0.01, // a little beyond 0 to 1, so cells at exactly 0 or 1 always get the end colours
maximum: 1.01,
gradientStops: [
{ offset: 0, color: "#7A1424" },
{ offset: 0.3, color: "#C2505A" },
{ offset: 0.5, color: "#E6E6EA" },
{ offset: 0.7, color: "#4C86C6" },
{ offset: 1, color: "#123A7A" }
]
});

let noise = 0.3;
let sampleSeed = 1;
const datasets = DATASETS.map((d, row) => ({ ...makeDataset(d.key, noise, sampleSeed + 10 * row), added: [] }));
const panels = [];

// Click on a panel to add a training point; hover to read the model's probability
class PanelModifier extends CustomChartModifier2D {
row = 0;
col = 0;
downPoint = undefined;
toData(args) {
const surface = this.parentSurface;
const p = translateFromCanvasToSeriesViewRect(args.mousePoint, surface.seriesViewRect);
if (!p) return undefined;
return {
x: surface.xAxes.get(0).getCurrentCoordinateCalculator().getDataValue(p.x),
y: surface.yAxes.get(0).getCurrentCoordinateCalculator().getDataValue(p.y)
};
}
modifierMouseDown(args) {
super.modifierMouseDown(args);
this.downPoint = args.mousePoint;
}
modifierMouseUp(args) {
super.modifierMouseUp(args);
const down = this.downPoint;
this.downPoint = undefined;
if (!down || Math.hypot(args.mousePoint.x - down.x, args.mousePoint.y - down.y) > 5) return; // a drag, not a click
const point = this.toData(args);
if (!point) return;
datasets[this.row].added.push({ x: point.x, y: point.y, label: Number(ui.clickClassSelect.value) });
for (let col = 0; col < CLASSIFIERS.length; col++) updatePanel(this.row, col);
}
modifierMouseMove(args) {
super.modifierMouseMove(args);
const point = this.toData(args);
const panel = panels[this.row][this.col];
if (!point || !panel.predict) return;
const p = panel.predict(point.x, point.y);
ui.status.textContent =
`${DATASETS[this.row].name}, ${CLASSIFIERS[this.col].name}: P(blue) = ${p.toFixed(2)} at ` +
`(${point.x.toFixed(2)}, ${point.y.toFixed(2)}), predicted ${p >= 0.5 ? "blue" : "red"}`;
}
}

async function createPanel(row, col) {
const { sciChartSurface, wasmContext } = await SciChartSurface.create(ui.cells[row][col].chartDiv, {
theme,
padding: new Thickness(0, 0, 0, 0)
});
const axisOptions = { isVisible: false, drawMajorGridLines: false, drawMinorGridLines: false, drawMajorBands: false };
const xAxis = new NumericAxis(wasmContext, axisOptions);
const yAxis = new NumericAxis(wasmContext, axisOptions);
sciChartSurface.xAxes.add(xAxis);
sciChartSurface.yAxes.add(yAxis);
const heatmapData = new UniformHeatmapDataSeries(wasmContext, { xStart: 0, xStep: 1, yStart: 0, yStep: 1, zValues: [[0.5]] });
// The decision boundary itself: the contour where the probability crosses 0.5
const contour = new UniformContoursRenderableSeries(wasmContext, {
dataSeries: heatmapData,
zLevels: [0.5], // a single contour at P = 0.5
majorLineStyle: { color: "#FFFFFF", strokeThickness: 1.5 }
});
sciChartSurface.renderableSeries.add(
new UniformHeatmapRenderableSeries(wasmContext, { dataSeries: heatmapData, colorMap, opacity: 0.9, fillValuesOutOfRange: true }),
contour
);
// Training points are solid with a white edge; held-out test points are paler
const scatter = (fill, stroke, size) => {
const dataSeries = new XyDataSeries(wasmContext);
sciChartSurface.renderableSeries.add(
new XyScatterRenderableSeries(wasmContext, {
dataSeries,
pointMarker: new EllipsePointMarker(wasmContext, { width: size, height: size, fill, stroke, strokeThickness: 1 })
})
);
return dataSeries;
};
const points = {
train: [scatter(RED, "#FFFFFF", 8), scatter(BLUE, "#FFFFFF", 8)],
test: [scatter(RED + "80", RED, 7), scatter(BLUE + "80", BLUE, 7)]
};
// Accuracy on the held-out test points, in the corner as in the classic comparison grid
const accuracy = new TextAnnotation({
xCoordinateMode: ECoordinateMode.Relative,
yCoordinateMode: ECoordinateMode.Relative,
x1: 0.98,
y1: 0.98,
horizontalAnchorPoint: EHorizontalAnchorPoint.Right,
verticalAnchorPoint: EVerticalAnchorPoint.Bottom,
text: "",
fontSize: 13,
textColor: "#FFFFFF",
background: "#14233CCC",
padding: new Thickness(1, 4, 1, 4)
});
sciChartSurface.annotations.add(accuracy);
const modifier = new PanelModifier();
modifier.row = row;
modifier.col = col;
sciChartSurface.chartModifiers.add(modifier, new MouseWheelZoomModifier(), new ZoomPanModifier(), new ZoomExtentsModifier());
return { sciChartSurface, xAxis, yAxis, heatmapData, contour, points, accuracy, predict: undefined };
}

// Train one classifier on one dataset, evaluate it on the grid, and redraw its panel
function updatePanel(row, col) {
const panel = panels[row][col];
const data = datasets[row];
const train = data.train.concat(data.added);
const predict = CLASSIFIERS[col].train(train);
panel.predict = predict;
const { xMin, xMax, yMin, yMax } = data.range;
const xStep = (xMax - xMin) / GRID;
const yStep = (yMax - yMin) / GRID;
const zValues = [];
for (let j = 0; j < GRID; j++) {
const line = new Array(GRID);
// The 1e-5 × i slope (at most 0.001) is invisible, but keeps flat regions (k-NN, trees) from being exactly flat,
// which software (non-GPU) WebGL renderers can otherwise draw as contour line
for (let i = 0; i < GRID; i++) line[i] = predict(xMin + (i + 0.5) * xStep, yMin + (j + 0.5) * yStep) + 1e-5 * i;
zValues.push(line);
}
panel.heatmapData.xStart = xMin;
panel.heatmapData.xStep = xStep;
panel.heatmapData.yStart = yMin;
panel.heatmapData.yStep = yStep;
panel.heatmapData.setZValues(zValues);
panel.contour.dataSeries = panel.heatmapData; // re-attach so the contour is traced again on the new values
panel.xAxis.visibleRange = new NumberRange(xMin, xMax);
panel.yAxis.visibleRange = new NumberRange(yMin, yMax);
for (const label of [0, 1]) {
const own = (list) => list.filter((p) => p.label === label);
panel.points.train[label].clear();
panel.points.train[label].appendRange(own(train).map((p) => p.x), own(train).map((p) => p.y));
panel.points.test[label].clear();
panel.points.test[label].appendRange(own(data.test).map((p) => p.x), own(data.test).map((p) => p.y));
}
const correct = data.test.filter((p) => (predict(p.x, p.y) >= 0.5 ? 1 : 0) === p.label).length;
panel.accuracy.text = `${Math.round((100 * correct) / data.test.length)}%`;
ui.cells[row][col].caption.textContent = CLASSIFIERS[col].caption();
}

for (let row = 0; row < DATASETS.length; row++) {
panels.push([]);
for (let col = 0; col < CLASSIFIERS.length; col++) panels[row].push(await createPanel(row, col));
}

// --- The controls ---
function showLayout() {
const choice = ui.datasetSelect.value;
const all = choice === "all";
ui.grid.style.gridTemplateColumns = all ? `auto repeat(${CLASSIFIERS.length}, minmax(96px, 1fr))` : "repeat(3, minmax(120px, 1fr))";
ui.grid.style.gridTemplateRows = all ? `repeat(${DATASETS.length}, 1fr)` : "repeat(2, 1fr)";
DATASETS.forEach((d, row) => {
ui.rowLabels[row].style.display = all ? "" : "none";
ui.rowLabels[row].style.gridArea = `${row + 1} / 1`;
ui.cells[row].forEach(({ cell }, col) => {
const shown = all || d.key === choice;
cell.style.display = shown ? "flex" : "none";
cell.style.gridArea = all ? `${row + 1} / ${col + 2}` : `${Math.floor(col / 3) + 1} / ${(col % 3) + 1}`;
});
});
}
function showTuning() {
const key = ui.tuneSelect.value;
const t = TUNING[key];
ui.valueInput.min = String(t.min);
ui.valueInput.max = String(t.max);
ui.valueInput.step = String(t.step);
ui.valueInput.value = String(t.log ? Math.log10(settings[key]) : settings[key]);
ui.valueInput.setAttribute("aria-label", ui.tuneSelect.selectedOptions[0].textContent);
ui.valueOutput.textContent = fmt(settings[key]);
// Outline the panels of the classifier being tuned
CLASSIFIERS.forEach((c, col) => {
for (const cells of ui.cells) cells[col].cell.style.outline = c.tunes.includes(key) ? "2px solid #FFD54F" : "none";
});
}
function updateAll() {
for (let row = 0; row < DATASETS.length; row++) for (let col = 0; col < CLASSIFIERS.length; col++) updatePanel(row, col);
}
function regenerate() {
noise = Number(ui.noiseInput.value);
ui.noiseOutput.textContent = noise.toFixed(2);
DATASETS.forEach((d, row) => (datasets[row] = { ...makeDataset(d.key, noise, sampleSeed + 10 * row), added: [] }));
updateAll();
}

ui.datasetSelect.addEventListener("change", showLayout);
ui.noiseInput.addEventListener("input", regenerate);
ui.sampleButton.addEventListener("click", () => {
sampleSeed += 1;
regenerate();
});
ui.tuneSelect.addEventListener("change", showTuning);
ui.valueInput.addEventListener("input", () => {
const key = ui.tuneSelect.value;
const raw = Number(ui.valueInput.value);
settings[key] = TUNING[key].log ? Number((10 ** raw).toPrecision(2)) : raw;
ui.valueOutput.textContent = fmt(settings[key]);
const col = CLASSIFIERS.findIndex((c) => c.tunes.includes(key));
for (let row = 0; row < DATASETS.length; row++) updatePanel(row, col);
});
showLayout();
showTuning();
regenerate();
ui.status.textContent = "Hover over a panel to read the probability; click to add a training point.";

Key points:

  • The probability grid is a UniformHeatmapDataSeries: zValues[row][column] with xStart, xStep, yStart and yStep placing the cells. setZValues replaces the grid when the model is retrained, without rebuilding the chart.
  • The boundary is a UniformContoursRenderableSeries on the same data series, with zLevels: [0.5], so SciChart.js traces the 0.5 contour for you.
  • A HeatmapColorMap from 0 to 1 with a pale middle stop makes the uncertain zone pale and the confident regions saturated.
  • Clicks and hover use a CustomChartModifier2D: translateFromCanvasToSeriesViewRect and each axis's coordinate calculator turn the mouse position into feature values.

See it in the demo app: JavaScript heatmap chart · React heatmap chart · Angular heatmap chart.

Go deeper: SciChart.js heatmap documentation, the heatmap guide for colour maps, and the scatter plot guide for drawing the points. The ROC curve guide covers evaluating a classifier beyond accuracy.

Frequently asked questions​

What is a decision boundary in machine learning?​

A decision boundary is the line, curve or surface that separates the regions where a classifier predicts different classes. For a model that outputs probabilities, it is where two classes are equally likely, usually a probability of 0.5. Its shape depends on the model: logistic regression draws a straight line, a decision tree draws axis-aligned steps, and k-nearest neighbours and RBF support vector machines can draw curved or jagged boundaries.

How does the k-nearest neighbours (KNN) algorithm work?​

k-nearest neighbours classifies a new point by measuring its distance to every training point, taking the k closest, and predicting the class most of them belong to. The share of neighbours in each class can be used as a probability. It needs no training step, but the features must be on comparable scales. A small k gives a jagged boundary that follows individual points; a larger k gives a smoother one.

What is naive Bayes?​

Naive Bayes is a classifier that uses Bayes' rule to turn the probability of the features within each class into the probability of each class given the features. It is called naive because it assumes the features are independent within a class. Gaussian naive Bayes models each feature as a normal distribution per class, which gives a quadratic decision boundary. It is fast, needs little data and is a strong baseline for text classification.

What is the difference between a decision tree and a random forest?​

A decision tree splits the data with a sequence of single-feature questions, giving a boundary made of axis-aligned steps that can overfit when the tree is deep. A random forest grows many trees, each on a bootstrap sample of the data with a random choice of features at each split, and averages their predictions. The averaged boundary is smoother and usually more accurate on new data than any single tree.

What is the difference between classification and regression?​

Classification predicts a category, such as spam or not spam, often with a probability for each class, and is evaluated with measures such as accuracy, precision and recall. Regression predicts a continuous number, such as a price or a temperature, and is evaluated with errors such as the mean squared error. Decision boundaries belong to classification; the regression equivalent is a fitted curve checked with a residual plot.

How do I plot a decision boundary in JavaScript?​

Train the classifier, then evaluate its probability for one class on a grid of points covering the data, for example 100 by 100. Draw the grid as a heatmap with a diverging colour map, draw its 0.5 contour as the boundary line, and overlay the training and test points as scatter series coloured by class. With SciChart.js, use UniformHeatmapRenderableSeries for the grid, UniformContoursRenderableSeries for the boundary and XyScatterRenderableSeries for the points; the code is the same in React and Angular.

Sources​