Skip to content

Lesson 8 · SVM

⏱ 52 min read

If many different lines can be drawn between two classes, which one should you choose, and why? A Support Vector Machine (SVM) answers this geometrically: the boundary is chosen by the width of the margin between the classes.

We will start with the simple geometric idea, then move to definitions and formulas with every symbol explained, numerical examples, and typical mistakes. There is no need to remember all the mathematics in advance.


1. Why SVM Is Needed

1.1. First, Let Us Recall What Classification Is

Classification is a machine-learning task in which an algorithm determines which category an object belongs to.

Examples:

  • an email — spam or not spam;
  • a transaction — suspicious or ordinary;
  • an image — contains a cat or a dog;
  • a customer — belongs to one of two given classes.

We have objects, their characteristics, and the known answers for the training examples.

Features are the characteristics used to make the decision.

Class label is the correct category of an object.

Suppose we classify conventional objects by two features:

  • \(x_1\) — the first characteristic;
  • \(x_2\) — the second characteristic.

Every object can be drawn as a point on a plane. The position of the point is determined by two numbers: \((x_1,x_2)\).

Blue points belong to one class, orange points to another. Our task is to learn how to draw a boundary that separates these classes.

1.2. What a Classifier Is

A classifier is a model that predicts the class of an object from its features.

For example, the model can receive the characteristics of an email and produce one of two results:

  • \(+1\) — spam;
  • \(-1\) — not spam.

The numbers \(+1\) and \(-1\) here are conventional class labels. They do not mean that one class is better or worse than the other.

We need to build a rule that takes the features of an object and outputs a decision about its class.

1.3. What a Decision Boundary Is

A decision boundary is a line or surface that separates the regions where the model predicts different classes.

On a plane such a boundary can be a straight line. In a space with three features it is a plane. With more features we use the generalized notion of a hyperplane, which we will discuss later.

If the classes can be completely separated by a straight line, the data is called linearly separable. However, even if there are many separating lines, they are not necessarily equally good.

Consider two situations:

  1. A line passes a millimetre away from several training points.
  2. Another line lies roughly in the middle between the classes, leaving more space on both sides.

The first boundary may turn out to be more sensitive to small changes in the data. The second looks more stable. This is the intuitive motivation for SVM, but not a guarantee that the second model will necessarily be better on any new data.

Three parallel lines between two clouds of points: the middle one is drawn as a bold line, the outer ones are marked with the closest points of both classes, and there is a caption maximum margin
Which boundary to choose. Many straight lines can be drawn through the space between the classes — the figure shows three of them. All three separate the classes, but the distance to the closest objects differs: the middle line (the bold one) has the largest distance, while the outer lines pass almost right against the points. The boundary with the largest margin is chosen, and the closest objects, marked with dots, define its width.

1.4. The Main Idea of SVM

SVM (Support Vector Machine) is the method of support vectors.

In the basic binary classification problem, a linear SVM looks for the separating hyperplane that maximizes the margin between the classes.

Here it is important to distinguish two formulations.

  • Hard-margin SVM — requires that the training objects of the two classes be separated without violations.
  • Soft-margin SVM — allows margin violations and even classification errors, penalizing them during training.

So SVM does not merely look for any boundary. It uses a specific criterion that allows choosing a model with regard to the geometry of the data and to the violations that are acceptable.

1.5. How SVM Differs from Logistic Regression

We already studied logistic regression in Lecture 6. Both algorithms can build a linear boundary between two classes. But their training objectives differ.

Logistic regression uses the logistic loss function (log-loss) and models the probability of a class within its probabilistic formulation.

In its classical form, SVM uses the geometric criterion of margin maximization, and in the soft formulation it is connected with hinge loss.

An ordinary SVM does not output calibrated probabilities automatically.

Question Logistic regression SVM
What does it build? A separating boundary A separating boundary
Main idea Training through log-loss Margin maximization with regard to violations
Main loss function Log-loss Hinge loss in the standard soft formulation
Probabilities Can be obtained directly from the model, but calibration is not guaranteed Additional methods are needed if probabilities are required
Non-linear boundary Possible by extending the features Possible with kernels

The main idea of the section: SVM is a classification algorithm that uses the geometric position of objects to find a separating boundary with a large margin.


2. Geometric Foundations

Before deriving the SVM formulas, let us work through the mathematical concepts we will need later.

2.1. A Point and Its Coordinates

On an ordinary plane, the position of a point is given by two coordinates. For example:

\[ x=(3,2) \]

This means that the first coordinate is \(3\) and the second is \(2\).

In machine learning an object is usually described by a set of features. If there are two features, we get a vector:

\[ x= \begin{pmatrix} x_1\\ x_2 \end{pmatrix} \]

Here \(x\) is the object in its mathematical representation, and \(x_1\) and \(x_2\) are its features. If there are ten features, the vector contains ten coordinates. If there are a hundred — a hundred coordinates.

That is why the mathematical description of an algorithm does not have to depend on whether we can draw all the features on a screen.

2.2. What a Vector Is

A vector is an ordered set of numbers that can be represented geometrically as a direction and a magnitude.

For example:

\[ w= \begin{pmatrix} 2\\ 1 \end{pmatrix} \]

In the context of a linear model, the vector \(w\) contains the weights of the features. For two features:

\[ w=(w_1,w_2) \]
  • \(w_1\) — the weight of the first feature;
  • \(w_2\) — the weight of the second feature.

The weights determine how the features participate in computing the model's decision.

2.3. The Dot Product

The dot product is an operation that multiplies the corresponding coordinates of two vectors and then adds up the results.

For two vectors

\[ w=(w_1,w_2),\qquad x=(x_1,x_2) \]

the dot product is computed as follows:

\[ w^\top x=w_1x_1+w_2x_2 \]

The symbol \(w^\top\) denotes the transposed vector. For our purpose it is enough to remember that this notation allows us to perform the dot product.

Example:

\[ w=(2,1),\qquad x=(3,4) \]

Then

\[ w^\top x=2\cdot3+1\cdot4=10 \]

We have obtained a single number, that is, a scalar. Why does this matter? A linear model uses the dot product to combine all the features of an object into a single value.

2.4. Vector Length and the Norm

The norm of a vector is a quantity that characterizes its length. For the ordinary Euclidean norm:

\[ \lVert w \rVert=\sqrt{w_1^2+w_2^2} \]

The double vertical bars denote the norm. For example, if

\[ w=(3,4), \]

then

\[ \lVert w \rVert=\sqrt{3^2+4^2} =\sqrt{9+16} =\sqrt{25}=5 \]

This is the familiar formula for the length of a right triangle, that is, the Euclidean distance from the origin to the point \(w\).

The square of the norm:

\[ \lVert w \rVert^2=w_1^2+w_2^2 \]

In our example:

\[ \lVert w \rVert^2=3^2+4^2=25 \]

In SVM the squared norm will appear in the objective function. Later we will see why minimizing this quantity is connected with maximizing the margin.

2.5. A Line on a Plane

The general equation of a line can be written like this:

\[ ax_1+cx_2+d=0 \]

Here \(a\), \(c\) and \(d\) are the coefficients of the equation, and \(x_1\), \(x_2\) are the coordinates of a point. For example:

\[ 2x_1+x_2-4=0 \]

Let us check whether the point \((1,2)\) lies on this line:

\[ 2\cdot1+2-4=0 \]

The equality holds, so the point lies on the line. For the point \((2,2)\):

\[ 2\cdot2+2-4=2 \]

We obtained a non-zero value. This point does not lie on the line.

Important: the expression on the left-hand side of the line equation can be evaluated for any point. The sign of the result helps you understand which side of the line the point is on.

This is exactly the idea that a linear SVM uses.

2.6. The Hyperplane

A hyperplane is a generalization of a line and a plane to a space of arbitrary dimension.

  • With two features the hyperplane is a line.
  • With three features it is an ordinary plane.
  • With more features it is the corresponding analogue in a multidimensional space.

The linear separating hyperplane of an SVM is given by the equation:

\[ \boxed{w^\top x+b=0} \]

Let us go through every symbol.

Symbol Meaning
\(x\) The feature vector of an object
\(w\) The weight vector of the model
\(w^\top x\) The dot product of the weights and the features
\(b\) The free term, or bias
\(0\) The value at which a point lies on the boundary

For two features the equation expands to:

\[ w_1x_1+w_2x_2+b=0 \]

If \(w_2\ne0\), we can express the second coordinate:

\[ x_2=-\frac{w_1}{w_2}x_1-\frac{b}{w_2} \]

This is an ordinary equation of a line.

So a hyperplane is not some separate mysterious construction. It is the familiar separating boundary, written so that the formula works for any number of features.


3. How SVM Classifies an Object

3.1. The Decision Function

Let us introduce the decision function:

\[ \boxed{f(x)=w^\top x+b} \]

It takes an object \(x\), multiplies its features by the weights, adds up the results and adds the bias \(b\).

The function returns a number. This number shows which side of the separating hyperplane the object is on, provided that \(w\ne0\).

  • If \(f(x)>0\), the object is on the positive side.
  • If \(f(x)<0\), the object is on the negative side.
  • If \(f(x)=0\), the object lies on the boundary.
A slanted line labelled wᵀx + b = 0, a blue arrow of the weight vector w perpendicular to it, two half-planes of different shades labelled f(x) > 0 and f(x) < 0, and a point on the line itself labelled f(x) = 0
The sign of the decision function sets the side of the boundary. The line wᵀx + b = 0 divides the plane into two halves: in the light region f(x) > 0, in the warm one f(x) < 0, and on the line itself f(x) = 0. The blue arrow is the weight vector w: it is perpendicular to the boundary and points towards the positive class.

For binary classification in the classical SVM it is convenient to use the labels:

\[ y\in\{-1,+1\} \]

The prediction rule:

\[ \hat y= \begin{cases} +1,& f(x)\geq0,\\ -1,& f(x)<0. \end{cases} \]

Here \(y\) is the true label and \(\hat y\) is the predicted label. At the point \(f(x)=0\) we agreed to choose \(+1\); a particular implementation may use a different tie-breaking rule.

3.2. A Numerical Example

Let the model have the form:

\[ f(x)=2x_1+x_2-5 \]

This means that the weights are \(w=(2,1)\) and the bias is \(b=-5\). Consider three objects.

Object A: \(x=(3,1)\).

\[ f(x)=2\cdot3+1-5=2 \]

The result is positive, so the class \(+1\) is predicted. Object B: \(x=(1,1)\).

\[ f(x)=2\cdot1+1-5=-2 \]

The result is negative, so the class \(-1\) is predicted. Object C: \(x=(2,1)\).

\[ f(x)=2\cdot2+1-5=0 \]

The point lies on the boundary.

3.3. Why the Labels Are Exactly \(-1\) and \(+1\)

This choice simplifies the mathematical notation of SVM. Instead of separate conditions for the two classes, we can use a product:

\[ y_i f(x_i) \]

Here \(y_i\) is the true label of an object, and \(f(x_i)\) is the value of the decision function. If the classification is correct, the product is positive:

  • the true class is \(+1\), the function is positive;
  • the true class is \(-1\), the function is negative.

In both cases the signs coincide, and the product is positive. If the signs do not coincide, the product is negative, which indicates a classification error.

If the true label were \(0\) or \(1\), such an expression would no longer have the same convenient meaning. That is why the classical mathematical formulation of SVM often uses \(-1\) and \(+1\).

3.4. The Value of the Decision Function Is Not a Probability

This is fundamentally important. If

\[ f(x)=4, \]

we cannot conclude that the probability of the class \(+1\) is 4 or 80%. The decision function returns an estimate of the position of the object relative to the boundary, not a probability.

The sign determines the side of the boundary, while the magnitude of the value depends on the parameters of the model and on the scale in which the function is written. To obtain probabilistic estimates, an additional calibration procedure is usually applied.


4. Margin and Distance to the Boundary

Now we need to learn how to measure not only the side on which an object lies, but also how far it is from the boundary. Here two concepts appear that must not be confused: the functional margin and the geometric margin.

4.1. The Functional Margin

The functional margin for an object with the label \(y_i\) is defined as follows:

\[ \boxed{\hat\gamma_i=y_i(w^\top x_i+b)} \]

Let us go through the expression:

  • \(x_i\) — the features of the \(i\)-th object;
  • \(y_i\in\{-1,+1\}\) — its true class;
  • \(w^\top x_i+b\) — the value of the decision function;
  • \(\hat\gamma_i\) — the functional margin.

Why do we multiply by the label?

If an object is classified correctly, the product is positive. If it is classified incorrectly, the product is negative. The larger the positive value, the larger the functional margin.

However, there is a subtlety: the functional margin depends on the scale of \(w\) and \(b\). If both parameters are multiplied by a positive number, the boundary does not change, but the values of the function and of the functional margins do change.

That is why the functional margin by itself cannot be treated as an ordinary geometric distance.

4.2. Distance from a Point to a Hyperplane

For a linear hyperplane

\[ H=\{x:w^\top x+b=0\} \]

the distance from a point \(x\) to this hyperplane is:

\[ \boxed{d(x,H)=\frac{\lvert w^\top x+b \rvert}{\lVert w \rVert}} \]

Here:

  • \(d(x,H)\) — a non-negative distance;
  • \(w^\top x+b\) — the value of the decision function;
  • \(\lvert \cdot \rvert\) — the absolute value, which makes the numerator non-negative;
  • \(\lVert w \rVert\) — the Euclidean norm of the weight vector.

Why do we divide by the norm of \(w\)? The value of a linear function changes together with the scale of its coefficients. Dividing by the norm removes this dependence and gives the geometric distance in the original feature space.

4.3. Let Us Compute the Distance

Take the hyperplane:

\[ 2x_1+x_2-5=0 \]

For it:

\[ w=(2,1),\qquad b=-5 \]

The norm of the weight vector:

\[ \lVert w \rVert=\sqrt{2^2+1^2}=\sqrt5 \]

Let a point have the coordinates \(x=(3,1)\). First we compute the decision function:

\[ f(x)=2\cdot3+1-5=2 \]

Now we substitute the result into the distance formula:

\[ d(x,H)=\frac{\lvert 2 \rvert}{\sqrt5} \approx0.894 \]

So the point is approximately at a distance \(0.894\) from the line in the coordinate system being used.

4.4. The Geometric Margin

For a labelled object, the geometric margin with regard to the correct class can be written like this:

\[ \boxed{\gamma_i=\frac{y_i(w^\top x_i+b)}{\lVert w \rVert}} \]

It differs from an ordinary distance in that it takes the true class label into account.

  • If an object is classified correctly, the geometric margin is positive.
  • If an object lies on the boundary, the margin is zero.
  • If an object is classified incorrectly, the margin is negative.

An ordinary distance is always non-negative, while the geometric margin can be negative. For the previous point \(x=(3,1)\), if its true label is \(y=+1\), we get:

\[ \gamma=\frac{1\cdot2}{\sqrt5} \approx0.894 \]

If the true label had been \(y=-1\), then:

\[ \gamma=\frac{-1\cdot2}{\sqrt5} \approx-0.894 \]

The geometric distance to the line would have remained the same, but the margin with regard to the true class would have changed sign.

A slanted line wᵀx + b = 0, two points on opposite sides of it, a dashed perpendicular dropped from each point to the line with a right-angle mark; labels y = +1 → γ > 0 and y = +1 → γ < 0, and the formula d(x, H) = |wᵀx + b| / ‖w‖
Distance and margin are not the same thing. A perpendicular is dropped from each point to the line: its length equals |wᵀx + b| / ‖w‖ and is always non-negative. The geometric margin also takes the true label into account: for the blue point with the label +1 it is positive, while for the orange point with the same label +1 that ended up on the other side of the boundary it is negative, because the model made a mistake.

4.5. Comparison of the Three Concepts

Concept Formula What it shows
Decision function \(f(x)=w^\top x+b\) The side of the boundary and a numerical estimate
Functional margin \(y_i f(x_i)\) Correctness and the size of the margin on the scale of the function
Geometric margin \(\frac{y_i f(x_i)}{\lVert w \rVert}\) The signed margin in units of distance
Ordinary distance \(\frac{\lvert f(x) \rvert}{\lVert w \rVert}\) The non-negative distance to the boundary

Do not mix up these quantities. They are related, but they answer different questions.


5. Margin — the Gap and Why It Matters

5.1. What the Margin Is

The margin in SVM is the distance between the separating hyperplane and the training objects closest to it, considered on both sides of the boundary.

In the ideal geometric picture, three parallel hyperplanes can be drawn:

  1. The central one — the separating boundary.
  2. The first outer one — it passes through the closest objects of one class.
  3. The second outer one — it passes through the closest objects of the other class.

The distance between the central boundary and each outer boundary is the same under the standard SVM normalization. The full width of the margin is the distance between the two outer boundaries.

Margin diagram: two clouds of points of two classes, two dashed margin boundaries, a solid separating line between them, circled support vectors and a double-headed arrow for the full margin width 2/‖w‖; beside it, the derivation of the transition to minimizing ½‖w‖²
Three hyperplanes and the width of the margin. The solid line is the separating boundary, the two dashed lines are the margin boundaries passing through the closest objects of each class; those objects are circled. The double-headed arrow shows the full width of the margin 2/‖w‖. On the right is the derivation: from the conditions wᵀx + b = 1 and wᵀx + b = −1 the problem is reduced to minimizing ½‖w‖².

5.2. Why the Width of the Margin Is Connected with the Norm of the Weights

In the standard notation of SVM, the two margin boundaries are given by the conditions:

\[ w^\top x+b=+1 \]

and

\[ w^\top x+b=-1 \]

The distance between the first boundary and the central hyperplane is:

\[ \frac{1}{\lVert w \rVert} \]

The full width of the margin is:

\[ \boxed{M=\frac{2}{\lVert w \rVert}} \]

Where does the two come from? On one side of the central boundary the margin has a width of \(1/\lVert w \rVert\), and on the other side the same. Adding both halves gives \(2/\lVert w \rVert\).

Now the key idea becomes clear: to maximize the width of the margin, we must minimize the norm of the weight vector under the corresponding constraints.

5.3. An Example

Suppose two models satisfy the necessary constraints and have the following weight norms:

  • model A: \(\lVert w \rVert=2\);
  • model B: \(\lVert w \rVert=1\).

Then the margin width of model A is:

\[ M_A=\frac22=1 \]

For model B:

\[ M_B=\frac21=2 \]

Model B has the wider margin.

This is an illustration of the connection between the norm and the margin, not a claim that you can simply reduce the weights without additional conditions: scaling the weights changes the values of the decision function, so the constraints matter too.

5.4. Why a Wide Margin Can Be Useful

If the boundary passes far from the closest training points, small changes in the position of some objects may not immediately change the side they end up on.

This gives an intuition for why margin maximization can help generalization — the ability of a model to work on new data that it did not see during training.

But a maximal margin does not guarantee ideal quality. The result depends on the distribution of the data, outliers, noise, the chosen features, the parameters of the model, and how well the chosen algorithm matches the task.

The main idea: SVM chooses a boundary not only by the fact that the classes are separated, but also by a geometric criterion. In the hard formulation this is margin maximization with no errors on the training objects.


6. Support Vectors

6.1. Who Support Vectors Are

Support Vectors are the training objects that determine the position of the separating boundary that is found and of the margin around it.

The name can be confusing: this is not some special type of mathematical vector that differs from the others. Every object is already represented by a feature vector. The objects of the training set that play a special role in solving the SVM problem are called support vectors.

In the ideal case of linearly separable data, the closest objects of each class lie on the margin boundaries. For the standard normalization of hard-margin SVM:

\[ y_i(w^\top x_i+b)\geq1 \]

The support vectors that lie directly on the margin boundaries satisfy the equality:

\[ y_i(w^\top x_i+b)=1 \]
Two clouds of points of two classes, a solid separating boundary, two dashed margin boundaries labelled wᵀx + b = +1 and wᵀx + b = −1, four circled support vectors with an arrow to the label support vectors, and a double-headed arrow labelled margin = 2/‖w‖
Support vectors lie on the margin boundaries. These are four circled objects, two on each side. The dashed lines wᵀx + b = +1 and wᵀx + b = −1 pass through them, and the solid line in the middle is the separating boundary. The distance between the dashed lines equals the full width of the margin 2/‖w‖; the remaining objects do not affect the position of the boundary.

6.2. Why They Matter So Much

Imagine a separating line being drawn between two groups of points.

If the blue point closest to the line moves, the geometry of the problem may change. Perhaps the line now has to be positioned differently in order to maximize the margin.

But if a distant blue point moves a little, it may remain far from the boundary and not change the optimal solution. This explains the special role of support vectors.

However, you cannot claim that any distant points always have absolutely no influence on training. If they change the overall configuration of the data, become boundary points, or affect other conditions of the problem, the solution may change too.

6.3. Support Vectors with a Soft Margin

In soft-margin SVM the situation is more complicated. Some support vectors may:

  • lie on the margin boundary;
  • be inside the margin but on the correct side of the separating boundary;
  • end up on the wrong side of the boundary.

When kernels are used, the notion of a support vector is preserved, although the geometry of the boundary in the original space may become non-linear.

Important: support vectors are not all the training objects. They are the objects that have special significance for the model that is found. Their exact composition depends on the training data, the parameters and the formulation of the problem.


7. Hard-margin SVM — the Hard Margin

7.1. When a Hard Margin Applies

Imagine that all the training objects of two classes can be separated by a straight line without a single error. Moreover, suppose we want to find not just any such line, but the one that maximizes the margin.

This is exactly the hard-margin SVM problem (SVM with a hard margin).

It assumes that all training objects must be on the correct side of the boundary and must not violate the given margin constraints.

7.2. Where the Constraint Comes From

For an object \(i\) with the true label \(y_i\in\{-1,+1\}\), we require:

\[ y_i(w^\top x_i+b)\geq1 \]

Consider both classes. If \(y_i=+1\), the condition becomes:

\[ w^\top x_i+b\geq1 \]

If \(y_i=-1\), we get:

\[ -(w^\top x_i+b)\geq1 \]

or, equivalently,

\[ w^\top x_i+b\leq-1 \]

Thus the positive class must lie beyond the \(+1\) boundary, and the negative class beyond the \(-1\) boundary, if we look at the values of the decision function.

Why exactly one? We could choose another positive value, but the scale of \(w\) and \(b\) can be changed accordingly. The condition with one is a convenient standard normalization that lets us write the margin boundaries in a simple form.

7.3. The Objective Function

Earlier we derived the formula for the width of the margin:

\[ M=\frac{2}{\lVert w \rVert} \]

To maximize \(M\), we need to minimize \(\lVert w \rVert\). Usually, instead of the norm itself, half of its square is minimized:

\[ \boxed{\min_{w,b}\frac12\lVert w \rVert^2} \]

subject to the constraints

\[ \boxed{y_i(w^\top x_i+b)\geq1,\quad i=1,\ldots,n} \]

Here:

  • \(w\) — the weight vector;
  • \(b\) — the bias;
  • \(n\) — the number of training objects;
  • \(i\) — the index of an object;
  • \(\lVert w \rVert^2\) — the squared norm of the weights;
  • \(\frac12\) — a convenient factor that simplifies the derivatives.

An important nuance: the objective function does not contain \(b\). The bias participates in the constraints and determines the position of the boundary, but the standard margin-maximization criterion directly minimizes the squared norm of \(w\).

7.4. Why the Factor \(1/2\) Appears

If we differentiate the square of the variable \(w\), a factor of \(2\) appears. The factor \(1/2\) cancels it. For example:

\[ \frac{d}{dw}\left(\frac12w^2\right)=w \]

In the multidimensional case the same holds:

\[ \nabla_w\left(\frac12\lVert w \rVert^2\right)=w \]

The symbol \(\nabla_w\) denotes the gradient with respect to the components of the vector \(w\).

The factor \(1/2\) does not change the minimum point. It is a mathematical convenience, not an additional parameter of the algorithm.

7.5. How the Problem Is Connected with Margin Maximization

The logic consists of three steps:

  1. We want to maximize the width of the margin \(2/\lVert w \rVert\).
  2. While the constraints hold, this is equivalent to minimizing \(\lVert w \rVert\).
  3. For computational convenience we minimize \(\frac12\lVert w \rVert^2\).

That is why the hard-margin SVM problem is written as a quadratic optimization problem with linear constraints. The constraints say which solutions are admissible. The objective function says which of the admissible solutions we prefer.

7.6. Drawbacks of Hard-margin

A hard margin requires separating the training data without any errors. This creates problems if:

  • the classes overlap;
  • the data contains noise;
  • there are outliers;
  • a single mislabelled point ends up deep inside the opposite class.

In that case an admissible solution may not exist at all. That is exactly why practical problems often use soft-margin SVM, which allows margin violations at a certain price.


8. Soft-margin SVM — the Soft Margin

8.1. Why Allow Violations

Real data is rarely ideal.

For example, in a spam-detection task some ordinary emails may contain words typical of spam. And suspicious emails sometimes look quite harmless.

If you force the algorithm to separate every training point perfectly, it may try to fit individual examples too closely — in other words, to overfit.

Soft-margin SVM allows violations in order to find a compromise between a wide margin and errors on the training data.

8.2. Slack Variables

To describe violations, slack variables are introduced, denoted \(\xi_i\) — the Greek letter xi. Each object has its own variable \(\xi_i\).

Its value shows how much the object violates the standard margin constraint. The formulation of the problem:

\[ \boxed{ \min_{w,b,\xi} \frac12\lVert w \rVert^2+C\sum_{i=1}^{n}\xi_i } \]

subject to the conditions:

\[ \boxed{ y_i(w^\top x_i+b)\geq1-\xi_i } \]
\[ \boxed{\xi_i\geq0} \]

Let us go through the parts of the formula.

Element Meaning
\(\frac12\lVert w \rVert^2\) The drive toward a wide margin
\(\xi_i\) The size of the violation for object \(i\)
\(\sum_i\xi_i\) The total violation of the constraints
\(C\) The penalty coefficient for violations
\(\xi_i\geq0\) A violation cannot be negative
\(1-\xi_i\) The relaxed right-hand side of the constraint

Now the algorithm can choose not only a boundary that separates all training points well, but also a boundary that admits some violations if that is more advantageous from the point of view of the overall objective function.

8.3. What Different Values of \(\xi_i\) Mean

For convenience, let us introduce the functional margin:

\[ m_i=y_i(w^\top x_i+b) \]

The constraint of soft-margin SVM requires:

\[ m_i\geq1-\xi_i \]

With the optimal choice of the violation variable for a fixed model, we can write:

\[ \xi_i=\max(0,1-m_i) \]

Let us consider the cases. Case 1. \(\xi_i=0\).

Then the object satisfies the constraint:

\[ m_i\geq1 \]

It is classified correctly and lies on the margin boundary or beyond it. Case 2. \(0<\xi_i<1\).

Then:

\[ 0<m_i<1 \]

The object is on the correct side of the separating boundary, but inside the margin. Case 3. \(\xi_i=1\).

Then:

\[ m_i=0 \]

The object lies on the separating boundary. Case 4. \(\xi_i>1\).

Then:

\[ m_i<0 \]

The object is on the wrong side of the boundary and is classified incorrectly. Example:

Margin \(m_i\) \(\xi_i=\max(0,1-m_i)\) Interpretation
\(2\) \(0\) Correct classification, outside the margin
\(1\) \(0\) On the margin boundary
\(0.4\) \(0.6\) Inside the margin
\(0\) \(1\) On the separating boundary
\(-0.5\) \(1.5\) Classification error

This gives a convenient way to connect the geometric picture with the mathematical optimization.

Two diagrams side by side: on the left hard margin — the line is pressed against the clouds of points, one point is circled in red and labelled one outlier; on the right soft margin — a wide margin band and three circled points labelled ξ = 0, 0 < ξ < 1 and ξ > 1
Hard margin and soft margin. On the left the hard formulation: one atypical point, circled in red, forces the boundary to be drawn almost right against the cloud. On the right the soft formulation: the margin is wider, and violations are allowed and described by the variable ξ. A point outside the margin has ξ = 0, a point inside the margin on the correct side has 0 < ξ < 1, and a point on the wrong side has ξ > 1.

9. The Parameter C: the Trade-off Between Margin and Errors

9.1. What C Controls

The parameter \(C\) determines how strongly the model penalizes margin violations. Let us recall the objective function:

\[ \frac12\lVert w \rVert^2+C\sum_i\xi_i \]

It has two terms:

  • the first encourages a wide margin;
  • the second penalizes violations.

The parameter \(C\) controls the relative importance of the second term.

9.2. A Large C

If \(C\) is large, every violation becomes expensive from the point of view of the objective function.

So the model usually strives harder to reduce violations on the training set. In some tasks this can lead to a narrower margin or to a boundary that is sensitive to individual training points.

However, a large \(C\) does not guarantee that the margin will necessarily become narrower with every increase of the parameter, and it does not automatically mean better test quality.

9.3. A Small C

If \(C\) is small, the penalty for violations is weaker. Then the model may prefer a wider margin, even if several objects lie inside it or are classified incorrectly.

This can help avoid fitting noisy training data too closely, but too weak a penalty can also lead to an unsatisfactory result.

Two diagrams: on the left a straight boundary with a wide margin band and two circled points inside the band; on the right the boundary bends around the same points and the band becomes narrow
What the parameter C changes. On the left a small C: the penalty for violations is weak, so the model chooses a wide margin even if two circled points end up inside it. On the right a large C: violations are expensive, and the boundary bends to remove them — the margin becomes narrow and the model sensitive to individual objects.

9.4. The Connection with Regularization

Regularization is a way to limit the complexity of a model or its tendency to fit the training data too closely.

In the standard formulation of SVM with hinge loss, an expression of the following form is minimized:

\[ \frac12\lVert w \rVert^2+C\sum_i L_i \]

where \(L_i\) is the loss on object \(i\). Equivalently, the whole function can be divided by \(C\) if \(C>0\):

\[ \frac{1}{2C}\lVert w \rVert^2+\sum_iL_i \]

This shows the connection between \(C\) and the relative strength of the regularizing term: all else being equal, a large \(C\) means a smaller relative coefficient in front of the norm of the weights.

In different machine-learning libraries the parameter may be represented differently, so it is important to check the documentation of the specific implementation.

9.5. How C Is Chosen

Usually several values of \(C\) are considered, models are trained, and they are compared on a validation set or by means of cross-validation.

Cross-validation is a way to estimate the quality of a model on several splits of the data, not just on one random split.

The test set should not be used when choosing \(C\): it is intended for the final independent evaluation of the model.

Important: a large \(C\) penalizes violations more strongly, a small one more weakly. Which value turns out to be better depends on the data and on the chosen quality metric.


10. Hinge loss

10.1. What a Loss Function Is

A loss function evaluates how undesirable the prediction of a model is on a particular object. In SVM the standard soft-margin loss is often defined like this:

\[ \boxed{L(y,f(x))=\max(0,1-yf(x))} \]

This is hinge loss. Notation:

  • \(y\in\{-1,+1\}\) — the true label;
  • \(f(x)\) — the value of the decision function;
  • \(yf(x)\) — the functional margin;
  • \(\max(a,b)\) — a function that returns the larger of the two numbers.

Why is the maximum used here? We want the object to be classified correctly and to have a margin of at least one. If this condition holds, the loss is zero. If it does not, a penalty arises.

10.2. The Three Main Cases

Let us denote the margin by \(m=yf(x)\). Then:

\[ L=\max(0,1-m) \]

Case A: \(m=2\).

\[ L=\max(0,1-2)=\max(0,-1)=0 \]

The object is classified correctly and lies beyond the margin boundary. The loss is zero. Case B: \(m=0.4\).

\[ L=\max(0,1-0.4)=0.6 \]

The object is on the correct side of the boundary, but inside the margin. The loss is positive. Case C: \(m=-0.5\).

\[ L=\max(0,1-(-0.5))=1.5 \]

The object is classified incorrectly. The loss is greater than one. The smaller the margin, the larger the loss in the region \(m<1\).

10.3. How Hinge Loss Is Connected with Soft-margin

We have already seen that for fixed \(w\) and \(b\) the minimum admissible value of the violation variable is:

\[ \xi_i=\max(0,1-y_i f(x_i)) \]

But this is exactly hinge loss:

\[ \xi_i=L(y_i,f(x_i)) \]

Consequently, the soft-margin problem can be written without explicitly introducing the variables \(\xi_i\):

\[ \boxed{ \min_{w,b} \frac12\lVert w \rVert^2+ C\sum_{i=1}^{n} \max(0,1-y_i f(x_i)) } \]

This is one of the most useful formulas of SVM. It shows that training balances between regularization and the total loss.

10.4. Comparison with Log-loss

In logistic regression, for the binary labels \(-1,+1\), the logistic loss can be written as:

\[ L_{\text{log}}(y,f(x)) =\log(1+e^{-yf(x)}) \]

Let us compare their behaviour.

Margin \(m=yf(x)\) Hinge loss Log-loss
\(2\) \(0\) \(\log(1+e^{-2})\approx0.127\)
\(1\) \(0\) \(\log(1+e^{-1})\approx0.313\)
\(0\) \(1\) \(\log 2\approx0.693\)
\(-1\) \(2\) \(\log(1+e)\approx1.313\)

The main difference: hinge loss becomes zero once the margin reaches one. Log-loss keeps penalizing finite values of the decision function, although the penalty gradually decreases as the correct margin grows.

These are different loss functions, so they can lead to different trained models.


Hinge loss plot: a straight sloped line descends to the axis and at m = 1 turns into a strictly horizontal line; three points are marked on the curve at m = -0.5, m = 0.4 and m = 2; on the right the same broken line sits next to a smooth log-loss curve
Hinge loss and its kink. While m ≥ 1 the loss is zero — the curve runs exactly along the axis. To the left, for m < 1, the loss grows as a straight line: the smaller m is, the heavier the penalty. The kink falls exactly at m = 1. On the right the same broken line is shown next to a smooth log-loss curve: both punish mistakes, but differently.

11. How SVM Is Trained

Now let us put the previous concepts together into a single process.

11.1. What Training Means

Training a model is the search for parameters that minimize the chosen objective function under the given conditions, that is, solving an optimization problem.

For soft-margin SVM in the standard formulation we can minimize:

\[ J(w,b)= \frac12\lVert w \rVert^2+ C\sum_{i=1}^{n} \max(0,1-y_i(w^\top x_i+b)) \]

Here \(J\) is the objective function to be minimized. The algorithm looks for suitable \(w\) and \(b\) so as to take both the margin and the violations into account at the same time.

11.2. A Reminder: Gradient and Subgradient

The gradient is the vector of partial derivatives of a function with respect to its parameters. It shows the direction of the fastest local increase of a differentiable function.

In Lectures 3–4 we studied optimization methods in which the parameters are changed so as to decrease the objective function. Hinge loss has a special feature:

\[ L(m)=\max(0,1-m) \]

If \(m<1\), the function is linear:

\[ L(m)=1-m \]

Its derivative with respect to \(m\) is \(-1\). If \(m>1\), the function is constant:

\[ L(m)=0 \]

Its derivative is \(0\).

At the point \(m=1\) there is a kink: the ordinary derivative is not defined there. For optimization, a subgradient is used — a generalization of the derivative that applies to certain non-smooth convex functions.

For hinge loss at the kink point, the subgradient can take any value from the interval \([-1,0]\) with respect to the variable \(m\).

11.3. Should SVM Always Be Trained with Gradient Descent?

No.

SVM can be trained with various optimization algorithms. For the classical SVM problem with a quadratic objective function and linear constraints, specialized quadratic-programming solvers are available.

For other formulations, subgradient methods and other algorithms can be used.

So it is more accurate to say that SVM is trained by solving an optimization problem, and the specific method depends on the formulation, the amount of data and the implementation.


12. Primal and Dual

This section is a little more difficult. Its goal is to understand the idea, not to memorize the whole derivation from convex optimization.

12.1. What the Primal Is

The primal problem is the original formulation of the optimization. For example, for hard-margin SVM:

\[ \min_{w,b}\frac12\lVert w \rVert^2 \]

subject to the conditions:

\[ y_i(w^\top x_i+b)\geq1 \]

We directly look for the weight vector \(w\) and the bias \(b\).

12.2. What the Dual Is

The dual problem is another mathematical formulation obtained from the original optimization problem.

For hard-margin SVM, Lagrange multipliers \(\alpha_i\geq0\) are introduced, corresponding to the constraints of the training objects.

After a mathematical transformation, the dual problem is obtained:

\[ \boxed{ \max_{\alpha} \left( \sum_{i=1}^{n}\alpha_i -\frac12 \sum_{i=1}^{n}\sum_{j=1}^{n} \alpha_i\alpha_jy_iy_j \,x_i^\top x_j \right) } \]

subject to the conditions:

\[ \alpha_i\geq0,\qquad \sum_{i=1}^{n}\alpha_i y_i=0 \]

Here \(\alpha_i\) is the Lagrange multiplier for object \(i\).

You do not have to memorize this formula right away. What matters is to see the structure: the dual problem depends on the dot products \(x_i^\top x_j\) between pairs of training objects.

After solving the dual problem, the weight vector can be recovered:

\[ \boxed{w=\sum_{i=1}^{n}\alpha_i y_i x_i} \]

That is, the weights of the model are represented as a combination of the training objects multiplied by their labels and the corresponding coefficients.

12.3. Why This Leads to Support Vectors

In the solution of SVM, many of the multipliers \(\alpha_i\) are zero.

The objects with non-zero multipliers participate in the representation of the solution. In the standard formulation, these are the support vectors.

For objects far beyond the margin, the multiplier is often zero. For objects on the margin boundary it can be positive. In the soft formulation, positive multipliers are also possible for objects that violate the margin.

This explains why the position of the boundary is not connected with all training points in the same way.

12.4. Why the Dual Matters for Kernels

Pay attention to the expression:

\[ x_i^\top x_j \]

In the dual problem the objects appear through dot products.

This opens the way to the Kernel Trick: if a suitable kernel function can be computed instead of the ordinary dot product, then non-linear models can be built without explicitly computing all the coordinates of the new feature space.

This is exactly where the dual formulation becomes especially useful.


13. The Kernel Trick

13.1. What to Do If a Straight Line Does Not Separate the Classes

So far we have considered a linear boundary in the original feature space. But there is data that cannot be separated well by a single straight line.

For example, imagine blue points in the centre and orange points around them in the shape of a ring. No straight line can completely separate the centre from the surrounding ring.

Can SVM still be used? Yes, if we move to a richer representation of the data.

13.2. Feature Mapping

Feature mapping is a transformation of an object into a new representation. Let us denote it:

\[ \phi(x) \]

For example, the original object has two coordinates:

\[ x=(x_1,x_2) \]

And the new representation may contain additional combinations of the features:

\[ \phi(x)=(x_1,x_2,x_1^2,x_1x_2,x_2^2) \]

This is only an illustration of a possible transformation, not a mandatory mapping for every SVM. In the new space, the separating hyperplane may correspond to a non-linear boundary in the original space.

13.3. The Kernel Function

A kernel function allows computing the dot product of objects in the space of mapped features:

\[ \boxed{K(x,z)=\phi(x)^\top\phi(z)} \]

Here \(x\) and \(z\) are two objects.

Instead of explicitly constructing \(\phi(x)\) and \(\phi(z)\), we can compute \(K(x,z)\) directly if a convenient formula exists for the chosen kernel.

13.4. Why It Is Called the Kernel Trick

The Kernel Trick is the use of kernel functions, which allows replacing dot products in the feature space with the computation of a kernel.

In the dual formulation of SVM, the dot products between training objects appear directly in the objective function. They can be replaced:

\[ x_i^\top x_j \quad\longrightarrow\quad K(x_i,x_j) \]

This makes it possible to build non-linear classifiers. But there are two important limitations:

  1. The kernel must correspond to an admissible mathematical construction; not every arbitrary distance function is a suitable SVM kernel.
  2. A non-linear kernel does not guarantee that the chosen model suits the particular data well.

A kernel is not magic that automatically solves any problem. It defines a way of comparing objects in a certain feature space.

Three panels: on the left a cloud of points surrounded by a ring and a dashed straight line that does not separate the classes; in the centre the same points after mapping — the ring has become a flat disc and the centre has risen above it; on the right a blue plane separates the disc from the raised points; at the bottom the formula K(x, z) = φ(x)ᵀφ(z)
The kernel trick. On the left the data in the original space: points of one class surround points of the other in a ring, and a single straight line cannot separate them. In the centre the same set after the mapping φ(x): the ring becomes a flat disc, and the centre rises above it. On the right, in the new space the classes are separated by a plane, which means that in the original coordinates the boundary is non-linear. The formula at the bottom shows that the dot product in the new space can be computed through the kernel without constructing the coordinates explicitly.

14. The Main Types of Kernels

14.1. The Linear Kernel

The formula:

\[ \boxed{K(x,z)=x^\top z} \]

This is the ordinary dot product of the original features.

The linear kernel is suitable when a linear boundary describes the task well enough. It can also be a practical choice for data with a large number of features, especially if computational efficiency and simplicity of the model matter.

14.2. The Polynomial Kernel

One of the standard forms:

\[ \boxed{K(x,z)=(\gamma x^\top z+r)^d} \]

Here:

  • \(x^\top z\) — the dot product;
  • \(\gamma\) — a scale parameter;
  • \(r\) — the free coefficient of the kernel;
  • \(d\) — the degree of the polynomial.

The polynomial kernel allows taking non-linear dependencies and interactions of features into account. For example, with two original features, combinations such as \(x_1x_2\) or \(x_1^2\) may become important.

At the same time, the degree \(d\), the parameter \(\gamma\) and the coefficient \(r\) affect the shape of the model. Too complex a representation can increase the risk of fitting the training data.

14.3. RBF / Gaussian Kernel

RBF (Radial Basis Function) is the radial basis kernel, often called the Gaussian kernel. Its standard formula:

\[ \boxed{K(x,z)=\exp(-\gamma\lVert x-z \rVert^2)} \]

Let us go through the symbols:

  • \(x,z\) — two objects;
  • \(\lVert x-z \rVert^2\) — the squared Euclidean distance between them;
  • \(\gamma>0\) — a parameter that controls the scale of influence;
  • \(\exp(a)=e^a\) — the exponential.

If the objects coincide, the distance is zero:

\[ K(x,x)=\exp(0)=1 \]

If the objects are far apart, the value of the kernel usually approaches zero. In other words, the RBF kernel estimates the closeness of objects using an exponentially decreasing function of distance.

14.4. What Gamma Does

The parameter \(\gamma\) is a hyperparameter: it controls how quickly the value of the RBF kernel decreases with distance.

  • A large \(\gamma\): the influence of each object fades faster with distance. The boundary may become more local and complex.
  • A small \(\gamma\): the influence of objects extends further. The boundary is often smoother.

This is a general tendency, not a guarantee of a particular shape of the boundary for any data and values of the remaining parameters.

Two diagrams: on the left a smooth curved boundary between clouds of points, labelled small γ and smooth boundary; on the right the boundary has broken up into separate regions around the points, four points are circled, labelled large γ and local boundary
What gamma does. On the left a small γ: the influence of objects fades slowly, and the boundary turns out smooth. On the right a large γ: the influence weakens quickly with distance, and the boundary becomes local — it breaks up into separate regions around the points.

14.5. Comparison of Kernels

Kernel Main idea When it may be suitable Limitations
Linear The ordinary dot product Data close to linearly separable Does not model an arbitrary non-linear boundary
Polynomial Combinations of features of a given degree Interactions of features matter The degree and other parameters have to be tuned
RBF Closeness of objects by distance A non-linear boundary is expected Sensitive to the scale of the features and to the parameters

There is no universally best kernel. The choice depends on the task, the data, the resources and the validation results.


15. Feature Scaling Before SVM

15.1. Why Scale Matters

Imagine two features:

  • a person's age — from 18 to 80;
  • a company's annual turnover — from 10,000 to 5,000,000.

If both features participate in computing distances, the second one can strongly influence the geometry simply because of its numerical scale — that is why feature scaling is applied before SVM.

This is especially important for the RBF kernel:

\[ K(x,z)=\exp(-\gamma\lVert x-z \rVert^2) \]

The distance depends on the differences along all coordinates. A feature with very large numerical values can dominate the sum of squared differences.

15.2. Standardization

Standardization is the transformation of a feature so that it has zero mean and unit standard deviation on the training set, provided that the standard deviation is positive.

The formula:

\[ \boxed{z=\frac{x-\mu}{\sigma}} \]

Here:

  • \(x\) — the original value;
  • \(\mu\) — the mean value of the feature;
  • \(\sigma\) — the standard deviation;
  • \(z\) — the standardized value.

For example, if the mean age is \(40\), the standard deviation is \(10\), and a particular person is \(50\) years old, then:

\[ z=\frac{50-40}{10}=1 \]

This means that the value is one standard deviation above the mean.

Two diagrams: on the left the points are stretched into a narrow vertical strip near the middle of the panel, labelled one feature dominates and before scaling; on the right the same points are spread over the whole area, labelled comparable ranges and after standardization
Before and after standardization. On the left a feature with a large numerical range suppresses the second one: the points line up in a narrow strip, and the distance between them is determined by almost a single feature. On the right the same set after standardization: both features are on a comparable scale, and the points occupy the whole area of the panel.

15.3. An Important Rule Against Data Leakage

The statistics \(\mu\) and \(\sigma\) must be computed on the training set only. After that, the same parameters are applied to the validation and test data.

Why can the mean and the standard deviation not be computed on the whole dataset before the split? Because then information from the validation or test part participates in preparing the data, although the model must not use it during training.

This is an example of data leakage. Leakage can make the quality estimate overly optimistic and lead to the wrong choice of model.

15.4. Is Standardization Always Needed?

Not necessarily in every variant of the task, but for SVM it is often useful, especially for kernels based on distances.

You also need to take the meaning of the features, their distributions and the preprocessing method being used into account. If the features are already on comparable scales, an additional transformation may not produce a noticeable effect.


16. SVM and Logistic Regression

These algorithms are often compared at ML interviews, because both can solve a binary classification problem with a linear boundary.

16.1. A Detailed Comparison

Criterion Logistic regression SVM
Main goal Train a probabilistic linear model Find a boundary with a large margin
Typical loss function Log-loss Hinge loss
Geometry A linear boundary in the original space A linear boundary, or a non-linear one with a kernel
Closest objects Can influence training depending on the error Support vectors play a special role
Probabilities Produced by the model, but may require calibration Not produced directly by the ordinary model
Regularization Limits the weights and affects generalization Affects the norm of the weights and the trade-off with violations
Non-linearity Feature transformations can be added Kernels can be used
Interpretation It is often convenient to analyse the coefficients and odds ratios A linear model is interpretable through its weights; a non-linear one is usually harder

16.2. Why SVM Does Not Output a Probability

In the standard formulation, SVM is trained not to predict a probability directly, but to construct a classifying boundary. Its decision function:

\[ f(x)=w^\top x+b \]

returns an estimate whose sign determines the class. The magnitude of this estimate does not have to be a probability and is not restricted to the interval from zero to one.

To obtain probabilistic estimates, additional methods can be applied, for example calibration on held-out data.

16.3. Which Algorithm Is Better

Neither of them is better in all tasks.

Logistic regression may be preferable when probabilistic estimates, simple interpretation and convenient handling of a large number of observations matter.

SVM may be useful when the geometry of the margin suits the task, and when a non-linear boundary is required through the use of kernels.

The final choice should be made based on the results of correct validation and with regard to computational costs.


17. Advantages and Limitations of SVM

17.1. Advantages

1. Geometric interpretability of the linear model. You can understand what boundary the algorithm builds, what the margin is, and why some objects become support vectors.

2. Margin maximization. SVM uses an explicit geometric criterion that can help generalization under suitable conditions.

3. Non-linear boundaries with kernels.

The Kernel Trick allows applying a linear mathematical formulation in a feature space, obtaining non-linear boundaries in the original space.

4. Usefulness with a large number of features.

SVM can work well in high-dimensional spaces, especially if the number of features is large relative to the number of observations. But this depends on the data, the regularization and the computational implementation.

17.2. Limitations

1. Sensitivity to parameters. The result may depend on \(C\), the kernel parameters and the preprocessing of the features.

2. Computational costs.

A kernel SVM can be expensive in time and memory on large samples, since it has to work with the relations between pairs of objects.

3. No probabilities in the standard formulation. If a business task specifically needs probabilities, additional calibration may be required.

4. Difficulty of interpreting a non-linear boundary.

A linear SVM is easier to explain through its weights and the hyperplane. For a complex kernel SVM, the geometric interpretation is less intuitive.

5. The need to check quality. A large margin, a complex kernel and a high result on the training data do not guarantee better quality on new objects.


18. A Complete Numerical Example

Now let us go all the way from the data to the geometric interpretation. In this example the model parameters are chosen manually for clarity, rather than obtained by running a training algorithm.

18.1. The Initial Data

Suppose we have two features \(x_1,x_2\) and two classes:

Object \(x_1\) \(x_2\) Label \(y\)
A 2 2 \(+1\)
B 2 3 \(+1\)
C 4 2 \(+1\)
D 0 0 \(-1\)
E 0 1 \(-1\)
F 1 0 \(-1\)

For illustration, let us take the decision function:

\[ f(x)=x_1+x_2-3 \]

This means:

\[ w=(1,1),\qquad b=-3 \]

The separating boundary is given by the equation:

\[ x_1+x_2-3=0 \]

or

\[ x_2=3-x_1 \]

This is a straight line on the plane.

18.2. Let Us Check the Classification

For object A \((2,2)\):

\[ f(A)=2+2-3=1 \]

The class \(+1\) is predicted, which coincides with the true label. For object D \((0,0)\):

\[ f(D)=0+0-3=-3 \]

The class \(-1\) is predicted, which is also correct. For object F \((1,0)\):

\[ f(F)=1+0-3=-2 \]

The model predicts the class \(-1\).

18.3. Let Us Find the Norm and the Distance

The weight vector:

\[ w=(1,1) \]

Its norm:

\[ \lVert w \rVert=\sqrt{1^2+1^2}=\sqrt2 \]

For object A the decision function equals \(1\). The distance to the boundary:

\[ d(A,H)=\frac{\lvert 1 \rvert}{\sqrt2} \approx0.707 \]

For object D:

\[ d(D,H)=\frac{\lvert -3 \rvert}{\sqrt2} =\frac3{\sqrt2} \approx2.121 \]

Thus object D is farther from the boundary than object A.

18.4. Let Us Look at the Margins

For object A with the label \(+1\):

\[ m_A=y_Af(A)=1\cdot1=1 \]

For object B \((2,3)\):

\[ f(B)=2+3-3=2 \]
\[ m_B=1\cdot2=2 \]

For object D with the label \(-1\):

\[ m_D=(-1)\cdot(-3)=3 \]

All the objects are classified correctly, but their margins differ.

In this small example only object A lies on the margin boundary: its functional margin equals \(1\). The other objects have margins greater than one: \(m_B=2\), \(m_C=3\), \(m_D=3\), \(m_E=2\), \(m_F=2\). The parameters here are chosen manually rather than obtained by training, so the set of support vectors in this illustrative configuration is conditional — strictly on the margin boundary there is a single object.

18.5. What the Margin Looks Like

For the chosen parameters \(w=(1,1)\), \(b=-3\), the central boundary is:

\[ x_1+x_2-3=0 \]

The margin boundaries:

\[ x_1+x_2-3=+1 \]

and

\[ x_1+x_2-3=-1 \]

That is:

\[ x_1+x_2=4 \]

and

\[ x_1+x_2=2 \]

The width of the margin:

\[ M=\frac2{\sqrt2}=\sqrt2\approx1.414 \]

18.6. What Happens When a Difficult Object Appears

Imagine that an object with the features \((2,1)\) and the label \(+1\) is added. For it:

\[ f(x)=2+1-3=0 \]

It lies directly on the separating boundary. By our classification rule the model predicts \(+1\), but its functional margin is zero:

\[ m=yf(x)=1\cdot0=0 \]

Its hinge loss:

\[ L=\max(0,1-0)=1 \]

The object violates the margin. If its decision function had turned out to be negative, it would have been classified incorrectly and the loss would have been greater than one.

Soft-margin SVM allows such an object to be taken into account without necessarily rebuilding the boundary so that every training observation has a margin of at least one.

18.7. How C Works Here

If \(C\) is large, a violation by such an object influences the objective function more strongly. If \(C\) is small, the algorithm may prefer to keep a wider margin by allowing the violation.

But this does not mean that the boundary will necessarily shift in a particular direction with any increase of \(C\). The new solution is determined by all the objects and by the overall optimization problem.

The takeaway from the example: the decision function determines the side of the boundary, the distance shows geometric closeness, the margin takes the true class into account, hinge loss penalizes an insufficient margin, and the soft margin allows balancing between the margin and violations.


Numeric example: three parallel lines — a solid decision boundary in the middle and two dashed margin boundaries, with a symmetric band between them crossed by a double-headed arrow labelled M = sqrt(2); three amber points A, B, C above the band and three grey points D, E, F below it
Numeric example: boundary and margin. The solid line is the decision boundary x₁ + x₂ − 3 = 0, the dashed ones are the margin boundaries x₁ + x₂ = 2 and x₁ + x₂ = 4. The margin band is symmetric about the boundary and its full width is 2/‖w‖ = √2. Point A lies exactly on the upper margin boundary: it is a support vector, while the other objects lie farther from the boundary.

19. Typical Mistakes and Misconceptions

Mistake 1. "SVM simply looks for any separating line"

No. In the standard formulation SVM strives to maximize the margin, and in the soft formulation it takes the trade-off between the margin and violations into account.

Mistake 2. "Support vectors are all the points of the training set"

No. Support vectors are only those training objects that have special significance for the solution of the optimization problem.

Mistake 3. "A large margin guarantees perfect generalization"

No. A large margin is a useful geometric criterion, but quality on new data also depends on the distribution of the data, noise, the features and the tuning of the model.

Mistake 4. "A large C is always better"

No. A large \(C\) penalizes violations more strongly, but this does not guarantee an improvement in quality on the test data.

Mistake 5. "Hinge loss and log-loss are the same thing"

No. Hinge loss becomes zero when the margin is at least one. Log-loss keeps decreasing as the correct margin grows, but it does not become exactly zero at a finite value of the decision function.

Mistake 6. "The decision function is a probability"

No. The value \(f(x)\) is not automatically a probability. It shows the side of the boundary and a numerical estimate used by the classifier.

Mistake 7. "The Kernel Trick necessarily creates a huge matrix of new features"

No. The point of the kernel trick is that the required dot products can be computed directly through the kernel, without explicitly constructing all the coordinates of the mapping.

Mistake 8. "The RBF kernel is always better than the linear one"

No. A more flexible boundary is not necessarily more useful. Sometimes a linear model matches the structure of the data better and requires fewer computations.

Mistake 9. "SVM works only with two features"

No. We need two features for illustrative figures. The formulas of SVM apply to vectors with a large number of features.

Mistake 10. "Scaling does not matter"

For many SVM formulations the scale of the features affects distances and geometry. It is especially important to take the scale into account when using the RBF kernel.

Mistake 11. "If an object is classified correctly, its hinge loss is zero"

Not necessarily. An object may be on the correct side of the boundary but inside the margin. Then it is classified correctly, yet its margin is less than one and the loss is positive.

Mistake 12. "The more complex the kernel, the better the model"

No. The complexity of a model must be justified by its quality on new data. The choice of kernel and its parameters should be checked on a validation set.


20. ML Interview Questions

Let us divide the questions into three levels: basic, intermediate and advanced. The answers are formulated so that they can be used as a basis for an oral answer at an interview.

20.1. Basic Level

Question 1. What is SVM?

SVM (Support Vector Machine) is a machine-learning method that, in a classification task, looks for a separating hyperplane. In the standard formulation it maximizes the margin between the classes, and in the soft formulation it allows margin violations while penalizing them.

Question 2. What is a hyperplane?

A hyperplane is a generalization of a line and a plane to a space of arbitrary dimension. In a linear SVM it is given by the equation \(w^\top x+b=0\).

Question 3. What is the margin?

The margin is the distance between the separating hyperplane and the closest objects of the classes. Under the standard SVM normalization the width of the margin is \(2/\lVert w \rVert\).

Question 4. What are support vectors?

These are the training objects that play a special role in determining the separating boundary. In the dual formulation they are associated with non-zero Lagrange multipliers.

Question 5. What are hard-margin and soft-margin?

Hard-margin requires that all training objects satisfy the margin constraints without violations. Soft-margin introduces violation variables and penalizes them, which makes it possible to work with noisy and imperfectly separable data.

20.2. Intermediate Level

Question 6. Why does SVM maximize the margin?

Margin maximization serves as a geometric criterion for choosing the boundary. It can promote stable separation of the classes and generalization to new data, although it does not guarantee ideal quality.

Question 7. What is the parameter \(C\) responsible for?

\(C\) controls the penalty for violations in soft-margin SVM. A large \(C\) means a stronger penalty, a small one a weaker penalty. The best value depends on the data and is usually chosen by validation or cross-validation.

Question 8. What is hinge loss? It is the loss function:

\[ L(y,f(x))=\max(0,1-yf(x)) \]

It equals zero if the correct margin is at least one, and it is positive in all other cases. Question 9. Why does the objective function contain the norm of the weights?

The width of the margin under the standard normalization is \(2/\lVert w \rVert\). Therefore minimizing \(\frac12\lVert w \rVert^2\) while satisfying the constraints is equivalent to maximizing the margin.

Question 10. Why does an ordinary SVM not output a probability?

Its decision function \(f(x)=w^\top x+b\) determines the side of the boundary, but it is not a probabilistic estimate. Additional calibration is used to obtain probabilities.

20.3. Advanced Level

Question 11. What is the Kernel Trick?

It is a way of computing dot products in the space of transformed features by means of a kernel function. It makes it possible to build non-linear boundaries without having to compute all the coordinates of the new space explicitly.

Question 12. How do the linear, polynomial and RBF kernels differ?

The linear kernel uses the ordinary dot product. The polynomial kernel allows polynomial combinations of features to be taken into account. The RBF kernel depends on the distance between objects and allows building flexible non-linear boundaries.

Question 13. How are the primal, the dual and the support vectors connected?

In the primal problem the parameters of the hyperplane are sought directly. In the dual problem Lagrange multipliers and dot products of objects are used. The objects with non-zero corresponding multipliers are the support vectors.

Question 14. Why is it important to scale features?

The scale of features affects the geometry and the distances. For kernels based on distances, one numerically large feature can dominate the others. Standardization helps make the scales comparable.

Question 15. What is the difference between SVM and logistic regression?

Both algorithms can build a linear boundary. However, logistic regression is usually trained with log-loss and directly models class probabilities, whereas SVM focuses on the margin and usually uses hinge loss in the soft formulation. SVM does not output calibrated probabilities automatically.

20.4. What Is Especially Important at an Interview

Do not limit yourself to memorizing formulas. A good answer explains cause-and-effect relationships:

  • why the margin is connected with the norm of the weights;
  • why the variables \(\xi_i\) are needed;
  • why \(C\) appears;
  • how hinge loss is connected with the soft margin;
  • why the dual problem leads to the kernel trick;
  • why the decision function is not a probability.

21. Practice Problems with Solutions

First try to solve the problems on your own. The answers are placed below so that you can check yourself after an attempt.

21.1. Tasks for Independent Work

In problems 1–10 use the definitions and formulas from the lecture.

1. Class by sign

The decision function of an object equals \(f(x)=-3\). Which class does SVM predict with the labels \(-1\) and \(+1\)?

2. The decision function

Given \(w=(2,-1)\), \(b=1\), \(x=(3,2)\). Compute \(f(x)\) and determine the predicted class.

3. Distance to the boundary

For \(w=(3,4)\), \(b=-5\) and the point \(x=(3,2)\), compute the distance to the hyperplane.

4. Functional and geometric margins

The true label is \(y=+1\), and the decision function equals \(6\). The norm of the weights is \(3\). Find both margins.

5. Margin violation

An object has the true label \(y=-1\), and the decision function equals \(f(x)=-0.5\). Is it classified correctly? Does it violate the margin?

6. Hinge loss

Compute hinge loss for a correct margin \(m=yf(x)\) equal to \(0.2\), \(1\) and \(-2\).

7. The influence of C

Two models have the same norm of the weights. The first has a total violation of \(4\), the second of \(1\). Which model will the objective function prefer when \(C>0\), if all other conditions are the same?

8. Comparison of kernels

The classes have the shape of a ring: one class is in the centre, the other surrounds it. Why may the linear kernel be insufficient, and which kernel should be considered?

9. Scaling

One feature ranges from 0 to 1, the other from 0 to 100,000. Why may standardization be useful for an RBF SVM?

10. An end-to-end problem

Given \(w=(1,1)\), \(b=-3\), \(x=(1,1)\), \(y=-1\). Compute the decision function, the predicted class, the functional margin, hinge loss and the geometric distance to the boundary.

Show detailed solutions

1. The decision function is negative: \(f(x)=-3<0\), so the class \(-1\) is predicted.

2. Substitute the values: \(f(x)=w^\top x+b=2\cdot3+(-1)\cdot2+1=6-2+1=5\). The value is positive, so the class \(+1\) is predicted.

3. First the decision function: \(f(x)=3\cdot3+4\cdot2-5=9+8-5=12\). The norm of the weights: \(\lVert w \rVert=\sqrt{3^2+4^2}=5\). The distance to the hyperplane: \(d=\frac{\lvert 12 \rvert}{5}=2.4\).

4. Functional margin: \(m=yf(x)=1\cdot6=6\). Geometric margin: \(\gamma=\frac{m}{\lVert w \rVert}=\frac{6}{3}=2\).

5. The product \(yf(x)=(-1)\cdot(-0.5)=0.5\) is positive, so the object is classified correctly. But the margin is less than one, which means the margin is violated: the object is inside the margin on the correct side of the boundary, and \(\xi=1-0.5=0.5\).

6. By definition \(L=\max(0,1-m)\). For \(m=0.2\) we get \(L=0.8\); for \(m=1\) we get \(L=0\); for \(m=-2\) we get \(L=3\).

7. The norms of the weights are the same, so the first term \(\frac12\lVert w \rVert^2\) is the same for both models. When \(C>0\), the second term \(C\sum_i\xi_i\) is smaller for the model with a total violation of \(1\) — that is the model the objective function will prefer.

8. The centre and the ring surrounding it cannot be separated by a single straight line, so the linear kernel is not enough. The RBF kernel or a polynomial kernel should be considered: in the original space the boundary will become a closed curve around the centre.

9. The squared distance \(\lVert x-z \rVert^2\) adds up the differences along all features, so a feature with a range up to 100,000 will swamp the second one. Standardization brings both features to a comparable scale, and the distance starts to reflect the differences along both features.

10. Decision function: \(f(x)=1\cdot1+1\cdot1-3=-1\), the class \(-1\) is predicted, which coincides with the true label. Functional margin: \(m=yf(x)=(-1)\cdot(-1)=1\). Hinge loss: \(L=\max(0,1-1)=0\). Distance to the boundary: \(d=\frac{\lvert -1 \rvert}{\sqrt2}=\frac{1}{\sqrt2}\approx0.707\).

21.2. Additional Tasks for Deeper Practice

  1. Explain why the norm of the weights cannot be reduced to zero without taking the SVM constraints into account.
  2. What changes in the formulation if the two classes cannot be separated without errors?
  3. Why can a large value of \(C\) lead to a less successful result on test data?
  4. How does the distance to the boundary differ from the functional margin?
  5. Why must a kernel function possess certain mathematical properties?
  6. How can you check whether the RBF kernel improves quality compared with the linear kernel?
  7. Why can hyperparameters not be tuned on the test set?

When solving these, do not just name the right term — explain which formula or idea the answer follows from.


22. Final Map of the Topic

22.1. The Whole Logic of SVM in One Chain

  1. Training data

    Features \(x_i\) and labels \(y_i\in\{-1,+1\}\)

  2. The separating hyperplane

    \[ w^\top x+b=0 \]
  3. The decision function

    \[ f(x)=w^\top x+b \]

    The sign determines the side of the boundary

  4. Margin and distance

    \[ y_i f(x_i),\qquad \frac{\lvert f(x) \rvert}{\lVert w \rVert} \]
  5. Margin maximization

    \[ M=\frac{2}{\lVert w \rVert} \]
  6. Support vectors

    The objects that determine the optimal solution

  7. Soft-margin and hinge loss

    \[ \frac12\lVert w \rVert^2+C\sum_i\max(0,1-y_i f(x_i)) \]
  8. Kernel functions

    Linear, polynomial, RBF — for different data structures

22.2. The Main Formulas

Concept Formula
Separating hyperplane \(w^\top x+b=0\)
Decision function \(f(x)=w^\top x+b\)
Prediction \(\hat y=\operatorname{sign}(f(x))\)
Norm of the weights \(\lVert w \rVert=\sqrt{\sum_j w_j^2}\)
Functional margin \(y_i f(x_i)\)
Geometric margin \(\frac{y_i f(x_i)}{\lVert w \rVert}\)
Distance to the boundary \(\frac{\lvert f(x) \rvert}{\lVert w \rVert}\)
Width of the margin \(\frac{2}{\lVert w \rVert}\)
Hard-margin \(\min \frac12\lVert w \rVert^2\), under \(y_i f(x_i)\geq1\)
Soft-margin \(\min \frac12\lVert w \rVert^2+C\sum_i\xi_i\)
Soft-margin constraints \(y_i f(x_i)\geq1-\xi_i,\ \xi_i\geq0\)
Hinge loss \(\max(0,1-yf(x))\)
Linear kernel \(K(x,z)=x^\top z\)
Polynomial kernel \(K(x,z)=(\gamma x^\top z+r)^d\)
RBF kernel \(K(x,z)=e^{-\gamma\lVert x-z \rVert^2}\)

22.3. Glossary of Terms

Term Meaning
Support Vector Machine (SVM) A classification method that looks for a separating hyperplane with a maximum margin
Classifier A model that assigns an object to one of the classes
Decision boundary The line or surface separating the regions of different classes
Hyperplane A generalization of a line and a plane to a space of arbitrary dimension
Feature A characteristic of an object used for prediction
Label The correct class of an object in the training data
Decision function The linear value that determines the side of the boundary
Functional margin The product of the true label and the decision function: correctness and size of the margin on the scale of the function
Geometric margin The functional margin divided by the norm of the weights, measured in distance units
Margin The gap between the separating boundary and the closest objects of the classes
Support vector A training object that determines the position of the boundary
Hard-margin A formulation in which margin violations are not allowed
Soft-margin A formulation that allows margin violations and penalizes them
Slack variable A variable showing how much an object violates the margin constraint
Hinge loss A loss that becomes zero once the correct margin is at least one
Regularization Limiting the complexity of a model or its tendency to fit the training data too closely
Hyperparameter A parameter set before training, for example the penalty coefficient or the kernel scale
Primal problem The original formulation of the optimization problem
Dual problem An equivalent formulation in terms of Lagrange multipliers
Lagrange multiplier The coefficient of the constraint of a training object in the dual problem
Kernel function A function that computes a dot product in the space of mapped features
Kernel Trick Replacing dot products with a kernel in order to build non-linear models
Linear kernel A kernel that uses the ordinary dot product of the original features
Polynomial kernel A kernel built from polynomial combinations of the features
RBF / Gaussian kernel A radial kernel based on the distance between objects
Standardization Transforming a feature to have zero mean and unit standard deviation
Cross-validation Estimating quality on several splits of the data rather than on one
Generalization The ability of a model to work on new data
Data leakage Information from the validation or test part leaking into the preparation of the data
Calibration Obtaining probabilistic estimates from the scores of a model

22.4. A Cheat Sheet Before an Interview

If you need to explain SVM in a minute:

SVM is a classification algorithm that, in its linear formulation, looks for a separating hyperplane with the maximum margin between the classes. Support vectors play an important role — the training objects that determine the boundary that is found.

Hard-margin SVM requires separating the training data without violations. Soft-margin SVM introduces the variables \(\xi_i\) that allow violations, and the parameter \(C\) controls the penalty for them. Hinge loss is connected with this formulation:

\[ L(y,f(x))=\max(0,1-yf(x)) \]

If a linear boundary does not fit, kernel functions can be used. The linear kernel uses the ordinary dot product, the polynomial kernel takes combinations of features into account, and the RBF kernel depends on the distance between objects.

An ordinary SVM does not output probabilities automatically. Scaling the features is often useful, especially for kernels based on distances. Hyperparameters should be tuned on validation data or by cross-validation.

22.5. Self-check

Below are twelve statements for self-check. If you can explain each of them in your own words, the topic is covered.

  • You can explain why SVM maximizes the margin.
  • The equation \(w^\top x+b=0\) is clear, and so is how the class is determined from the sign of the decision function.
  • You can compute the decision function and predict the class.
  • You can tell the functional margin, the geometric margin and the distance to the boundary apart.
  • The role of support vectors is clear.
  • You can explain the difference between hard-margin and soft-margin.
  • The meaning of the variables \(\xi_i\) and of the parameter \(C\) is clear.
  • You can compute hinge loss.
  • The difference between the primal and the dual is clear at a conceptual level.
  • The Kernel Trick is clear, as are the differences between the linear, polynomial and RBF kernels.
  • You can explain why scaling the features and correct validation matter.
  • You can compare SVM with logistic regression.

22.6. Practice on AI Wiki

Theory is best reinforced with experiments: compare linear and non-linear separating boundaries, see how the result changes when \(C\) is tuned, and explore the effect of the scale of the features.

There is no separate SVM demo in the lab yet, so the practice block below gathers three pages about related ideas: the boundary built from the closest objects, the loss function, and the geometry of a line.

Conclusion

In this lecture we went from a geometric problem to a full mathematical formulation of SVM.

The main thing to take away: SVM is not just an algorithm that draws a line between two classes. It chooses the boundary by a specific optimization criterion, takes the margin into account and, in the soft formulation, balances between the width of the margin and violations.

We worked through why the decision function is connected with the hyperplane, how margins and distances differ, what role support vectors play, how hard-margin and soft-margin are structured, why the parameter \(C\) is needed, how hinge loss works, and why the dual formulation leads to the kernel trick.

The whole topic fits into a single sequence:

data → separating hyperplane → decision function → margin → gap → support vectors → optimization → soft margin → hinge loss → kernel functions → non-linear classification.

You do not have to memorize all the formulas at once. It is far more important to understand what problem each of them solves and how one concept follows from another.

Once this logic becomes familiar, the mathematical notation of SVM will stop looking like a set of unrelated symbols: the formulas will describe the same idea from different sides.

Practice in the Lab

Three things to do for this lecture: see how the boundary depends on the data, look at the loss function, and work through the geometry of a line.

  1. Look at the data and the boundary — open KNN: the K nearest neighbours and move the query point: the boundary is built from the training objects, and you can see that it may be curved. In SVM the boundary is defined only by the closest objects — the support vectors — so it is useful to compare what the boundary looks like when it is determined by a few points rather than by all of them at once.

  2. See the loss function — open Logistic loss: it shows the loss surface over two parameters and descent along it. The hinge loss from this lecture is built differently — it has a region where the loss is zero — but the idea that parameters are chosen by minimizing the loss is the same.

  3. Work through the geometry of a line — open Fit a line by hand: a line on a plane, the distances from points to it, and how the position of the line changes the error. The separating hyperplane in SVM is the same line, just written as the equation \(w^\top x+b=0\).

There is no separate SVM demo in the lab yet: these three pages show related ideas, not the method of support vectors itself.

Check yourself