Skip to content

Lesson 5 · Metric Methods

⏱ 15 min read

Why do we even need a new idea?

Until now we studied linear regression. The logic there was roughly this:

there are objects → there are features → we build a mathematical model → the model makes a prediction.

For example, we want to predict the price of an apartment. We have:

Apartment Area Rooms Price
A 40 1 100
B 45 1 110
C 80 3 200

Linear regression tries to find a general pattern, for example:

the larger the area, the higher the price.

But we can look at the task in a completely different way. Suppose a new apartment appears:

D = (43 m², 1 room)

We can ask:

"Which of the already known apartments are most similar to D?"

Obviously A and B are much more similar to it than C. And then a very natural idea arises:

if two objects are similar, perhaps their answers are similar too.

This is a completely different approach to machine learning. We no longer have to first build a global formula like

\[ y = wx+b. \]

We can do this:

Find similar objects → look at what answers they have → use them to predict.

And this is where the metric approach appears.


1. What are metric methods?

Let's start with the word itself.

"Metric"

The word is related to measurement. For example:

  • a metre measures length;
  • a kilogram measures mass;
  • a second measures time.

In metric methods the question we care about is:

how do we measure the distance between objects?

In other words:

how much does one object differ from another?


1.1. A very important idea

Let's picture two people. We can describe them with features:

Person Age Height
A 30 180
B 32 178
C 70 160

By these two features, A and B look similar. A and C are far less similar.

But so far we are saying this only intuitively. We would like to get a number:

A and B are at a distance of 2.5

A and C are at a distance of 45.7

Then we can already say formally:

A is closer to B than to C.

And this is the key transition.


2. From "similarity" to distance

Until now:

"A is similar to B."

That is human reasoning. A machine needs something more formal.

So we can say:

If objects are similar, we will consider the distance between them to be small.

And if they differ greatly:

the distance is large.

We get:

\[ \boxed{\text{similarity} \longleftrightarrow \text{small distance}} \]

This is one of the most important ideas of the whole lecture.


3. Object and features

Now let's define the terms carefully.

Object

An object is a separate instance that we study. For example:

  • one apartment;
  • one person;
  • one photograph;
  • one car;
  • one email;
  • one product.

Let's denote an object with the letter:

\[ x \]

Feature

A feature is a characteristic of an object that we use to describe it. For example, for an apartment:

  • area;
  • number of rooms;
  • floor;
  • distance to the metro.

Then one apartment can be represented as a set of numbers:

\[ x=(40,2,5) \]

This means:

  • area = 40;
  • rooms = 2;
  • floor = 5.

4. What is feature space?

This is a very important term. Imagine we have just two features:

  • \(x_1\) — area;
  • \(x_2\) — number of rooms.

Then every object can be represented as a point on the plane. For example:

\[ A=(40,2) \]
\[ B=(45,2) \]
\[ C=(80,4) \]

We can literally picture it:

number of rooms
       ↑
     4 |                         C
       |
     3 |
       |
     2 |     A   B
       |
     1 |
       +----------------------------→ area
          40  45             80

This is what feature space is.


What does "space" mean?

Here the word may sound scarier than it is. In our case space is simply:

all possible combinations of feature values.

If we have two numerical features, we get a two-dimensional space. If three, a three-dimensional one.

If 100 features, the space has 100 dimensions. We can no longer draw it, but mathematically it exists.


5. Coordinates

At the point

\[ A=(40,2) \]

the numbers 40 and 2 are the coordinates of the object. The first coordinate:

\[ x_1=40 \]

The second:

\[ x_2=2 \]

That is, coordinates simply say:

where the object is located in feature space.


6. Distance between objects

Now we can finally formulate the task. We have: \(A=(1,2)\) and \(B=(4,6)\) We want to find out:

how far is A from B?

On the plane this is an ordinary geometry problem. The difference along the first coordinate:

\[ 4-1=3 \]

Along the second:

\[ 6-2=4 \]

We get a right triangle with sides 3 and 4. And we know:

\[ 3^2+4^2=5^2 \]

Therefore the distance is:

\[ 5 \]

This is the Euclidean distance.


7. Euclidean distance

The formula for two points:

\[ d(A,B)= \sqrt{(x_1-x_2)^2+(y_1-y_2)^2} \]

The formula is not scary. Let's go through it literally, piece by piece.

\(A\) and \(B\).

These are our two objects.

\(x_1\), \(y_1\).

The coordinates of the first object.

\(x_2\), \(y_2\).

The coordinates of the second object.

\(d(A,B)\).

The distance between A and B. The letter \(d\) here comes from the English distance.


Let's plug in our points

\[ A=(1,2) \]
\[ B=(4,6) \]

Then:

\[ d(A,B)= \sqrt{(1-4)^2+(2-6)^2} \]

First the differences:

\[ 1-4=-3 \]
\[ 2-6=-4 \]

We get:

\[ d(A,B)= \sqrt{(-3)^2+(-4)^2} \]

The squares:

\[ (-3)^2=9 \]
\[ (-4)^2=16 \]

We add them up:

\[ 9+16=25 \]

The root:

\[ \sqrt{25}=5 \]

Total:

\[ \boxed{d(A,B)=5} \]

8. But why the square at all?

A very good question. We could simply add up:

\[ |x_1-x_2|+|y_1-y_2| \]

But that would be a different distance. In Euclidean geometry we want the length of the straight segment between the points.

And here the Pythagorean theorem does the work:

\[ a^2+b^2=c^2 \]

Therefore:

\[ c=\sqrt{a^2+b^2} \]

This is exactly where the Euclidean distance formula comes from. So it is not some magical ML formula.

It came from ordinary geometry.


9. What is a metric?

Now we can take the next step. We said:

we need to measure distance.

But a problem arises. What exactly should count as distance?

We can invent many different ways. So mathematics says:

a good way of measuring distance must satisfy certain properties.

Such a distance is called a metric.

Formal definition

A metric is a distance function \(d(x,y)\) that satisfies four main properties:

  1. non-negativity;
  2. identity of indiscernibles;
  3. symmetry;
  4. the triangle inequality.

Now let's go through them in plain language.


10. Property #1 — non-negativity

Distance cannot be negative. That is:

\[ d(x,y)\geq0 \]

For example:

\[ d(A,B)=5 \]

is possible.

\[ d(A,B)=0 \]

is possible. But:

\[ d(A,B)=-5 \]

makes no sense.

Intuitively

You cannot say:

"There are minus 3 kilometres left to the shop."

Therefore:

\[ \boxed{d(x,y)\geq0} \]

11. Property #2 — identity of indiscernibles

The name is scary, the meaning is simple. If an object is with itself, the distance is zero:

\[ d(x,x)=0 \]

For example:

\[ A=(1,2) \]

The distance from A to A:

\[ 0 \]

But there is a second part to the property:

if

\[ d(x,y)=0 \]

then the objects must be the same. That is:

\[ d(x,y)=0 \Rightarrow x=y \]

If two different objects are at a distance of 0, our "metric" is not working correctly.


12. Property #3 — symmetry

The distance from A to B is the same as the distance from B to A:

\[ d(A,B)=d(B,A) \]

If Moscow is 1000 km away from some city, that city is also about 1000 km away from Moscow. You cannot have: \(d(A,B)=5\) but \(d(B,A)=17\). For an ordinary distance that is meaningless.


13. Property #4 — the triangle inequality

This one deserves a closer look. Formally:

\[ d(A,C)\leq d(A,B)+d(B,C) \]

What does this mean? Let's picture three points:

A -------- B -------- C

To get from A to C, you can:

option 1: go directly:

A -------------------- C

option 2: first get to B, then to C:

A -------- B -------- C

The path through B cannot turn out to be shorter than the direct path. Therefore:

\[ A\to C \leq A\to B+B\to C \]

A small numerical example

Let:

\[ d(A,B)=3 \]
\[ d(B,C)=4 \]

Then:

\[ d(A,C)\leq3+4 \]

that is:

\[ d(A,C)\leq7 \]

For example, \(d(A,C)=5\) is fine. \(d(A,C)=7\) is also fine.

But:

\[ d(A,C)=10 \]

violates the triangle inequality. Because we get:

\[ 10\not\leq7 \]

14. Why do we need these four properties at all?

A very good question. Because a metric has to behave sensibly, like a distance.

We want:

  • the distance not to be negative;
  • an object not to be removed from itself;
  • the direction not to change the distance;
  • a detour not to be shorter than the direct path.

This creates a mathematically stable notion of "far/near".


15. But distance comes in different kinds

And this is where a very interesting part begins. We can measure distance in different ways.

The best known one:

Euclidean distance

The straight-line distance between points.

\[ d(A,B)= \sqrt{\sum_{i=1}^{n}(x_i-y_i)^2} \]

Here:

  • \(n\) is the number of features;
  • \(x_i\) is the value of the \(i\)-th feature of the first object;
  • \(y_i\) is the value of the \(i\)-th feature of the second object;
  • \(\sum\) means "add everything up over all features".

For two features this is our old formula:

\[ \sqrt{(x_1-y_1)^2+(x_2-y_2)^2} \]

16. Manhattan distance

Now let's picture a city where you cannot walk diagonally. For example:

A . . . .
  . . . .
  . . . B

If the streets only run horizontally and vertically, we have to go:

  • first 3 steps to the right;
  • then 4 steps up.

Total:

\[ 3+4=7 \]

This is Manhattan distance. The formula:

\[ d(A,B)= |x_1-x_2|+|y_1-y_2| \]

For our points:

\[ A=(1,2) \]
\[ B=(4,6) \]

We get:

\[ d(A,B)=|1-4|+|2-6| \]
\[ =3+4 \]
\[ \boxed{7} \]

17. Why did Euclidean give 5 and Manhattan 7?

Because they answer slightly different geometric questions.

Euclidean

What is the length of the straight segment between the points?

We got:

\[ 5 \]

Manhattan

How far do you have to travel along horizontal and vertical directions?

We got:

\[ 7 \]

That is:

choosing a metric is choosing what we consider "closeness".

Three panels: points equidistant from the centre form a diamond for Manhattan distance, a circle for Euclidean, and a square for Chebyshev
The same distance, three different shapes. Points equidistant from the centre form their own figure in each metric: L1 (Manhattan) a diamond, L2 (Euclidean) a circle, L∞ (Chebyshev) a square. That is why "nearby" means different regions of space in different metrics.

And this will be extremely important for KNN.


18. The most important thought before KNN

Imagine we have a new object. We can say:

"Find the most similar objects."

But a computer does not know what "similar" means. We have to give it a rule.

For example:

"Consider those objects similar between which the Euclidean distance is small."

Or:

"Use Manhattan distance."

Therefore:

\[ \boxed{ \text{KNN} \neq \text{data + K only} } \]

At a minimum, what matters is:

\[ \boxed{ \text{data + features + metric + K} } \]

And changing the metric can change the nearest neighbours. And if the neighbours change, the prediction can change too.


19. A very important problem: the scale of features

Now let's picture two features. We have cars:

  • age — from 1 to 20 years;
  • mileage — from 10,000 to 500,000 km.

Suppose:

\[ A=(5,\;50000) \]
\[ B=(6,\;51000) \]

The difference:

  • age: \(1\);
  • mileage: \(1000\).

If we use ordinary Euclidean distance:

\[ d(A,B)= \sqrt{1^2+1000^2} \]
\[ =\sqrt{1+1\,000\,000} \]
\[ \approx1000 \]

What happened? The mileage feature completely suppressed the age feature.

Even though we might have wanted to take both into account.


20. Why is this a problem?

Let's picture two objects:

A

Age:

\[ 5 \]

Mileage:

\[ 50\,000 \]

B

Age:

\[ 6 \]

Mileage:

\[ 50\,100 \]

And C:

Age:

\[ 15 \]

Mileage:

\[ 50\,000 \]

In terms of meaning:

  • A and B are very similar;
  • A and C differ greatly in age.

But if we simply compute the distance from the raw numbers, the huge scale of mileage starts to dominate. That is, the distance starts answering not the question:

"How similar are the objects?"

but rather:

"How much do the big numbers differ?"

This is a bad situation.


21. Feature scaling

Two panels: without scaling the cloud is stretched into a strip, after standardization the nearest neighbours change
The scale of features changes who counts as a "neighbour". On the left, two features in completely different units: age in tens, mileage in hundreds of thousands. Because of this the cloud of objects is stretched into a narrow strip, the distance is almost entirely determined by mileage, and age stops mattering. On the right, the same objects after standardization: both features are on the same scale, and the nearest neighbours turn out to be completely different.

That is why feature scaling is often used before metric algorithms.

Scaling

This is transforming features so that their numerical scales become comparable. For example, instead of:

age:        5
mileage:    50000

get something like:

age:        0.25
mileage:    0.10

Then no feature automatically gets a giant advantage just because of the units of measurement.


22. Normalization

Normalization.

One common variant brings values into a range, for example:

\[ [0,1] \]

One of the formulas:

\[ x'= \frac{x-x_{\min}} {x_{\max}-x_{\min}} \]

Here:

  • \(x\) is the original value;
  • \(x_{\min}\) is the minimum value of the feature;
  • \(x_{\max}\) is the maximum;
  • \(x'\) is the new scaled value.

For example, if age ranges from 20 to 80 and a person is 50:

\[ x'= \frac{50-20}{80-20} = \frac{30}{60} = 0.5 \]

23. Standardization

Another approach is standardization. Here a feature is transformed relative to its mean value and spread.

The formula:

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

Where:

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

Let's not dig deep into standard deviation for now — it is a separate mathematical object. The main idea:

normalization usually brings values into a given range, often [0,1];

standardization expresses a feature relative to its mean and the scale of its spread.


24. And now we are ready for KNN

Now the transition comes out naturally. We already know how to:

  1. represent an object as a set of features;
  2. represent an object as a point;
  3. represent a set of objects as feature space;
  4. measure distance;
  5. determine which objects are closer;
  6. understand why the metric matters;
  7. understand why the scale of features matters.

Now a question arises:

What if we use the nearest objects to make a prediction?

This is where the following appears:

K-Nearest Neighbors

KNN — K-Nearest Neighbors, that is:

the K nearest neighbours.

Let's break down the name:

  • K — how many neighbours we take;
  • Nearest — closest;
  • Neighbors — neighbours.

25. What is a neighbour?

In KNN a neighbour is simply:

an object that is close to our object according to the chosen metric.

For example, a new object X has arrived. We computed the distances:

Object Distance to X
A 1.2
B 0.7
C 4.8
D 2.1
E 0.9

We sort them:

Place Object Distance
1 B 0.7
2 E 0.9
3 A 1.2
4 D 2.1
5 C 4.8

If:

\[ K=3 \]

we take:

\[ B,E,A \]

These are the three nearest neighbours.


26. KNN for classification

Suppose every object has a class. For example:

  • A;
  • B.

Our neighbours:

Neighbour Class
B A
E A
A B

We get:

  • class A — 2 votes;
  • class B — 1 vote.

The majority:

\[ A \]

Consequently:

\[ \boxed{\text{prediction}=A} \]

This is called a majority vote.


27. What is K?

Three panels with the same objects and a decision boundary at K equal to 1, 3, and 15
The same thing, but with different K. All three panels are built from the same objects; only the number of neighbours changes. On the left K = 1: the boundary goes around every point, and any noise creates its own little island. In the middle K = 3: the boundary is calmer. On the right K = 15: the boundary is almost straight, individual details disappear. A small K is sensitive to noise, a large one smooths; a workable value is found by looking at quality on new data.

K is one of the most important parameters of KNN. For example:

\[ K=1 \]

means:

we look only at the single nearest neighbour.

\[ K=3 \]

means:

we look at the three nearest.

\[ K=5 \]

means:

we look at the five nearest.


28. Why is K a hyperparameter?

A hyperparameter is a setting of an algorithm that we choose ourselves before or during the construction of a model, rather than an ordinary parameter that the algorithm obtains directly as a result of optimization on the training data.

For KNN:

\[ K \]

is usually chosen by us. For example:

let's try K=1, 3, 5, 7 and see which option performs better on validation.

This is different from linear regression. There we looked for the parameters:

\[ w,\ b \]

from the data. In KNN the classical variant does not require finding such coefficients at all.


29. Why can K=1 be bad?

Imagine that one object in the training set accidentally turned out to be wrong. For example:

A A A A A
      X
    noise

If:

\[ K=1 \]

the new object may end up right next to that erroneous object. And then the prediction will be wrong.

That is, K=1 is very sensitive to local noise.


30. Why can a large K also be bad?

Now the opposite situation. Imagine we took too many neighbours.

For example:

\[ K=1000 \]

Then for one local object we start asking the opinion of a huge number of objects. As a result, the local structure can get lost.

The model starts saying roughly:

"It doesn't matter who is right next to it: I take a very large part of the dataset and the overall majority."

This leads to smoothing.


31. Overfitting and underfitting

Here we connect KNN to the general idea of ML.

Small K

The model reacts very strongly to local peculiarities. This can mean:

\[ \boxed{\text{sensitivity that is too high}} \]

and lead to overfitting.

Overfitting is a situation where a model fits the training data too well, including noise and random peculiarities, and performs worse on new data.


Large K

The model averages too much. Small but real differences can disappear.

This can lead to:

\[ \boxed{\text{underfitting}} \]

Underfitting is a situation where a model is too simple or smooths out patterns too much and therefore describes even the important structure of the data poorly.

We get an important trade-off:

\[ \boxed{ K\text{ too small} \rightarrow \text{noise / overfitting} } \]
\[ \boxed{ K\text{ too large} \rightarrow \text{smoothing / underfitting} } \]

What comes next

This is where the most important foundation has been built:

  1. What the metric approach is

  2. What distance is

  3. What a metric is

  4. What kinds of distances exist

  5. Why scale matters

  6. Why we can look for nearest neighbours

  7. Where KNN naturally comes from

What comes next is KNN itself, much more deeply: decision boundary, weighted KNN, regression, lazy learning, choosing K, brute force, computational cost, the curse of dimensionality, indexes and embeddings.

And that will no longer be a set of definitions, but one continuous story:

We learned to measure closeness — now we use closeness to predict.


32. Tasks for self-check

Answer each task for yourself, then open the answer and compare. You do not have to solve it perfectly — the goal is to see where the gaps are.

The tasks build on the material of the lecture: distances, the scale of features and KNN. The solutions are given below.

Task 1. Euclidean and Manhattan distance

Given the points \(A=(1,2)\) and \(B=(4,6)\). Find the Euclidean and the Manhattan distance between them, and explain why the results differ.

Show answer

Euclidean distance:

\[ d(A,B)=\sqrt{(1-4)^2+(2-6)^2}=\sqrt{9+16}=\sqrt{25}=5. \]

Manhattan distance:

\[ d(A,B)=\lvert 1-4 \rvert+\lvert 2-6 \rvert=3+4=7. \]

The Euclidean distance measures the length of the straight segment between the points, while the Manhattan distance is the total path along the horizontal and the vertical. That is why the same points give different values.

Task 2. The scale of features

Cars are described by the features "age" (from 1 to 20 years) and "mileage" (from 10 000 to 500 000 km). For the objects \(A=(5,\;50\,000)\) and \(B=(6,\;51\,000)\) compute the Euclidean distance, determine which feature drives the result, and name a way of bringing the features to a comparable scale.

Show answer

The difference in age is \(1\) and in mileage \(1000\):

\[ d(A,B)=\sqrt{1^2+1000^2}=\sqrt{1+1\,000\,000}\approx 1000. \]

The result is almost entirely determined by the mileage: its scale is thousands of times larger, so the contribution of age is invisible. Features are brought to a comparable scale by normalization (to a range, for example \([0,1]\)) or by standardization.

Task 3. Normalization

The age of the clients lies in the range from 20 to 80 years. Bring the value \(50\) to the range \([0,1]\) using the normalization formula and state the standardization formula.

Show answer

By the normalization formula:

\[ x'=\frac{x-x_{\min}}{x_{\max}-x_{\min}}=\frac{50-20}{80-20}=\frac{30}{60}=0.5. \]

For standardization the formula \(z=\frac{x-\mu}{\sigma}\) is used, where \(\mu\) is the mean value of the feature and \(\sigma\) the standard deviation.

Task 4. Voting of the neighbours

For a new object \(X\) the distances to the objects of the sample are: \(A\) — \(1.2\), \(B\) — \(0.7\), \(C\) — \(4.8\), \(D\) — \(2.1\), \(E\) — \(0.9\). The objects \(B\) and \(E\) belong to class A, and the object \(A\) to class B. Which class will be predicted with \(K=3\)?

Show answer

The distances in increasing order: \(B\) — \(0.7\), \(E\) — \(0.9\), \(A\) — \(1.2\), \(D\) — \(2.1\), \(C\) — \(4.8\). With \(K=3\) the voting involves \(B\), \(E\) and \(A\). The objects \(B\) and \(E\) belong to class A, and the object \(A\) to class B. The votes: class A — 2, class B — 1, so class A is predicted (majority vote).

Task 5. Choosing K

Why is a small value \(K=1\) bad, and why is a very large \(K\) bad? How is the value of \(K\) chosen?

Show answer

With \(K=1\) the prediction is determined by one nearest object, so a random outlier creates a separate region — this leads to overfitting. With a very large \(K\) the averaging captures distant objects and fine patterns disappear — this leads to underfitting. The value of \(K\) is a hyperparameter; it is chosen by quality on new data.


🧪 Practice

  1. KNN: the K nearest neighbours — drag the query point, turn K and the metric: you can see how the decision boundary and the prediction change.

  2. Embeddings, PCA and k-means — 303 objects in a 16-dimensional space: objects as points, distances, and groups.

Check yourself

📚 Further reading