Skip to content

Lesson 10 · Ensembles

⏱ 52 min read

1. Why ensembles are needed

1.1. Let us start with a simple idea

Imagine you need to predict the price of an apartment. Its area, the number of rooms, the district and the state of the renovation are known.

We trained one machine learning model. It valued the apartment at 8 million rubles. But how far can this forecast be trusted? Perhaps the model did not take the district into account well enough. Another model might have valued the area differently, and a third might have paid more attention to the number of rooms.

What if we combine several forecasts?

  • model A — 8.0 million ₽;
  • model B — 9.0 million ₽;
  • model C — 8.5 million ₽;
  • the ensemble (the mean of the three forecasts) — 8.5 million ₽.

We obtained a final estimate of 8.5 million rubles.

This does not prove that the result has become more accurate: the real price is not known yet, and all three models may be wrong in the same direction. But if their errors differ, combining them may indeed prove more useful than individual forecasts.

That is the basic idea of ensembles: to use several models together in order to obtain a single final prediction.

1.2. What a machine learning model is

Let us start with a definition.

A machine learning model is a mathematical relationship that, after training, is able to take a description of an object and produce a forecast.

For example, the model receives information about an apartment:

  • area — 60 m²;
  • number of rooms — 2;
  • floor — 4;
  • district — central.

On the basis of this data it predicts the price. Let us go through three important concepts.

Term Simple explanation Example
Object (sample, instance) The thing for which we make a prediction A particular apartment
Feature A characteristic of the object that the model receives Area, floor
Prediction The answer that the model produces 8.5 million ₽

Training a model is the process in which the model uses examples from the training data to adjust its internal parameters and learn to make predictions.

For example, on historical data about apartments the model learns to connect the area, the district and other features with the price.

After training the model can be applied to new apartments whose prices we do not know yet.

1.3. What an ensemble is

An ensemble is a machine learning method in which the predictions of several models are combined according to a certain rule. The models taking part in an ensemble are called base models or base learners.

An ensemble has two main components:

  1. The base models make their predictions.
  2. An aggregation mechanism transforms them into a common result.

For example:

  • the first model predicts 8 million;
  • the second — 9 million;
  • the third — 8.5 million;
  • the ensemble computes the mean and produces 8.5 million.

An important nuance: the models do not have to be completely different algorithms. Sometimes they are models of the same type trained on different samples or with different settings. Sometimes different algorithms are used.

An ensemble is also not necessarily a simple mean: there are voting, weighted combination and methods in which a separate model learns to combine the predictions of the others.

A left-to-right diagram: a card with an object, three arrows to three cards of different models, then an aggregation box and a final ensemble prediction card
One object — three models — one answer. On the left an object; arrows fan out from it to three different models ("model A", "model B", "model C"): a linear one, a tree and a nearest-neighbour model, and the gauge inside each card shows its own prediction. The answers then converge into the "aggregation" box, and the output is a single ensemble prediction — the mean of the three.

1.4. What tasks ensembles solve

Let us consider two main types of task.

Classification — the model chooses a category or class.

Examples:

  • an email is spam or not spam;
  • a review is positive or negative;
  • an image is a cat, a dog or a bird.

Regression — the model predicts a numerical quantity.

Examples:

  • the price of an apartment;
  • the demand for a product;
  • the delivery time;
  • electricity consumption.

Ensembles are applied in both cases, but the way they are combined may differ.

Task What the base models predict How they are combined
Classification Classes or class probabilities Voting
Regression Numbers Averaging or weighted averaging

1.5. Why several models can perform better than one

Suppose three models estimate the same apartment. The first usually overestimates small apartments, the second sometimes underestimates apartments in the centre, and the third reacts to other peculiarities of the data.

If the errors partially compensate for each other, the final forecast may be more accurate. However, there are three fundamental conditions here.

  • The base models must produce sufficiently useful forecasts.
  • Their errors must not coincide completely.
  • The combination rule must suit the task.

Is an ensemble always better than a single model? No. If all the models make the same errors, averaging will not fix the problem. If you add many weak or systematically wrong models, the result may even get worse.

Besides that, an ensemble requires more computation and memory, and the final prediction can be harder to explain.

The main thought: an ensemble is not a magical improvement obtained by using more models. Its usefulness depends on the quality of the base models and on how they make mistakes.

2. Basic concepts

Before examining ensemble algorithms, let us sort out the terms on which everything will be built.

2.1. Base model (Base Model, Base Learner)

This is an individual model that is part of the ensemble. For example, if three decision trees together predict whether a client will leave a bank, each tree is a base model.

Base models can differ:

  • in their algorithm;
  • in their training sample;
  • in their parameters;
  • in the features they use;
  • in the randomness that arises during training.

At the same time, a base model does not have to be weak. It may be quite good on its own.

2.2. Prediction

A prediction is the result of the work of a model for a particular object. Let us denote the prediction of model \(i\) for object \(x\) as

\[ \hat y_i(x). \]

Let us go through the symbols:

  • \(x\) — the object, for example an apartment;
  • \(y\) — the true value, for example the real price of the apartment;
  • the hat over \(y\), that is, \(\hat y\), means that this is a prediction and not a known true answer;
  • the index \(i\) denotes the number of the model.

If three models predicted the price of one apartment, then:

\[ \hat y_1(x)=8,\qquad \hat y_2(x)=9,\qquad \hat y_3(x)=8.5. \]

Here the prices are expressed in millions of rubles.

2.3. Prediction error

The error shows how much the prediction differs from the true value. For regression a signed error can be defined:

\[ e_i=\hat y_i-y. \]

Here:

  • \(e_i\) — the error of model \(i\);
  • \(\hat y_i\) — its prediction;
  • \(y\) — the true value.

Suppose the real price of the apartment is 8 million rubles.

Model Forecast Error "forecast − truth"
A 8 million 0
B 9 million +1 million
C 7 million −1 million

A positive error here means an overstatement of the price, a negative one an understatement.

Note that the errors \(+1\) and \(-1\) can compensate for each other during averaging. It is exactly this property that underlies one of the advantages of ensembles.

But in machine learning the word "error" is used for different quantities: the difference between the prediction and the answer, its square, the absolute error, or an averaged quality metric. So you should always specify which error is being considered.

2.4. Diversity

Diversity means that the models of an ensemble do not give completely identical predictions or make different errors. Let us consider two situations.

Situation A: five models predict a price of 10 million. Their answers coincide completely. Situation B: the models predict 9.5, 10.2, 10.4, 9.8 and 10.1 million.

In the second case the forecasts are more diverse.

But diversity by itself does not guarantee quality. If the true price is 10 million, the forecasts of the second group look useful. If all five models produce values around 2 million, diversity will not save the ensemble.

Consequently, it is not any diversity that is useful, but diversity that helps to compensate for errors without an excessive deterioration of the individual forecasts.

2.5. Error correlation

Correlation is an indicator of how inclined two quantities are to change in agreement. In our case we are interested in how consistently the models make mistakes.

For example, if model A overestimates the prices of apartments in the centre and model B does the same for roughly the same apartments, their errors are positively related.

If one model overestimates where another underestimates, the errors may partially compensate for each other.

Important: the correlation of errors and the similarity of the forecasts themselves are related but not identical things. For assessing an ensemble it is especially important how the errors relate to each other with respect to the true answers.

2.6. Bias and variance

These concepts will help to explain why ensembles can improve quality. Bias is a systematic deviation of the forecasts of a model from the correct relationship.

For example, a model is too simple and cannot reflect the dependence of the price of an apartment on the district. It regularly underestimates expensive apartments.

Variance is the sensitivity of a trained model to changes in the training data.

Imagine that the same algorithm was trained several times on slightly different samples. If the resulting forecasts for one apartment differ strongly, the model has a large variance.

Intuitively:

  • a large bias — the model systematically fails to capture important patterns;
  • a large variance — the model reacts too strongly to the particular composition of the training data.

Ensembling is especially interesting in a situation where the individual models have a large variance and their errors do not coincide too strongly. Averaging can reduce that variance.

A more detailed mathematical explanation will be given in section 6.

3. How to combine predictions

Now let us examine two main ways: voting for classification and averaging for regression.

3.1. Voting for classification

Imagine that we are classifying an email. We need to determine whether it is spam, an ordinary email or advertising. Three models produced the following answers:

Model Predicted class
A Spam
B Spam
C Advertising

Two models chose spam and one chose advertising. If all the votes have equal weight, the final class is spam. This is called hard voting.

3.1.1. Hard voting

Each model casts one vote for the class it has chosen. The class that receives the most votes wins. Formally, for a class \(c\):

\[ V(c)=\sum_{i=1}^{M} \mathbf{1}(\hat y_i=c). \]

Let us go through the notation:

  • \(c\) — the class under consideration, for example "spam";
  • \(M\) — the number of models;
  • \(i\) — the number of the model;
  • \(\hat y_i\) — the class chosen by model \(i\);
  • \(\mathbf{1}(\hat y_i=c)\) — an indicator: it equals 1 if the model chose the class \(c\) and 0 otherwise;
  • \(V(c)\) — the number of votes for the class \(c\).

Let us write down the votes for the three models:

  • model A: spam;
  • model B: spam;
  • model C: advertising.

Then:

\[ V(\text{spam})=1+1+0=2, \]
\[ V(\text{advertising})=0+0+1=1. \]

Since \(2>1\), the ensemble chooses the class "spam". What is important: hard voting takes the chosen classes into account, but not how confident each model is in its answer.

Three model cards labelled spam, spam and ads, two tally columns below with two filled squares for spam and one for ads, the winning column outlined and leading to a final spam badge
Hard voting. The three models cast one vote each: A and B chose "spam", C chose "ads". In the tally two filled squares stand for "spam" and one for "ads", so the left column is declared the winner and the final class is "spam". The main rule is visible at a glance: only the chosen classes are counted, and the confidence of the models is ignored.

This is exactly where the second approach appears.

3.1.2. How a class differs from the probability of a class

Suppose a model has to determine whether an email is spam. It may produce:

  • the class: "spam";
  • the probability of spam: 0.51.

Or another model may produce:

  • the class: "spam";
  • the probability of spam: 0.99.

Both models chose the same class, but their confidence in the forecast differs. A class is a final category.

The probability of a class is a numerical estimate of the probability that the object belongs to that category, produced by the model.

For example, in binary classification a model may produce:

\[ P(\text{spam}\mid x)=0.8. \]

This means that the model estimates the probability of the class "spam" for the object \(x\) at 80%.

Ideally such probabilities should be well calibrated: among objects with a predicted probability of about 0.8, roughly 80% should really belong to that class. However, not every model has this property automatically.

For multiclass classification a model may produce a vector of probabilities:

Class Probability
Ordinary email 0.10
Spam 0.75
Advertising 0.15
Sum 1.00

If a model produces the probabilities of all mutually exclusive classes, their sum is usually equal to 1.

3.1.3. Soft voting

Soft voting combines not the finished classes but the probabilities predicted by the models. In the simplest variant the probabilities are averaged.

Let three models estimate the probabilities that an email belongs to the classes "spam" and "advertising".

Model \(P(\text{spam})\) \(P(\text{advertising})\)
A 0.51 0.49
B 0.51 0.49
C 0.01 0.99

With hard voting models A and B would choose spam and model C advertising. So spam would win by 2 to 1. With soft voting we first average the probabilities of spam:

\[ P_{\text{ensemble}}(\text{spam}) =\frac{0.51+0.51+0.01}{3}. \]

We add them up:

\[ 0.51+0.51+0.01=1.03. \]

We divide by three:

\[ P_{\text{ensemble}}(\text{spam}) =\frac{1.03}{3}\approx0.343. \]

Now let us compute the average probability of advertising:

\[ P_{\text{ensemble}}(\text{advertising}) =\frac{0.49+0.49+0.99}{3}. \]
\[ P_{\text{ensemble}}(\text{advertising}) =\frac{1.97}{3}\approx0.657. \]

Let us compare:

  • spam: approximately 34.3%;
  • advertising: approximately 65.7%.

Soft voting will choose advertising, although hard voting chose spam.

Why? Two models barely preferred spam, while the third was almost completely confident about advertising. Soft voting takes this difference in probabilities into account.

Four rows of paired probability gauges: in models A and B the amber part is slightly longer, in model C almost the whole gauge is blue, and in the soft voting row the blue part takes about two thirds
Soft voting. Each model has a pair of gauges: amber is the probability of "spam", light blue is the probability of "ads", and together they make up the whole. Models A and B barely prefer spam, while model C is almost certain about advertising. After the probabilities are averaged (the highlighted "soft voting" row) the blue part becomes longer and the ensemble chooses "ads" — whereas hard voting chose "spam" (the two cards in the lower right corner).

This does not mean that soft voting is always better than hard voting. The result depends on the quality of the models, the calibration of the probabilities and the specific task.

3.1.4. Weighted voting

Sometimes the base models have different quality. Then they can be assigned different weights. Weighted soft voting computes:

\[ P_{\text{ensemble}}(c\mid x) = \frac{\sum_{i=1}^{M}w_iP_i(c\mid x)} {\sum_{i=1}^{M}w_i}. \]

Here:

  • \(P_i(c\mid x)\) — the probability of the class \(c\) produced by model \(i\);
  • \(w_i\) — the weight of the model;
  • \(M\) — the number of models;
  • the denominator \(\sum w_i\) normalises the sum in order to obtain a weighted average.

If all the weights are equal to 1, the formula turns into ordinary averaging of the probabilities.

For example, let model A have weight 2 and model B weight 1. For the class "spam" they produced the probabilities 0.8 and 0.2 respectively.

\[ P_{\text{ensemble}}(\text{spam}) =\frac{2\cdot0.8+1\cdot0.2}{2+1}. \]
\[ =\frac{1.6+0.2}{3} =\frac{1.8}{3} =0.6. \]

The final probability is 60%.

The weight means the contribution of the model to the final forecast, not a guaranteed probability that it is right. In practice the weights have to be chosen in a justified way, for example from validation results, without fitting to the test answers.

3.1.5. What to do when the votes are tied?

Suppose two models chose class A and two chose class B. Hard voting has no single winner: the score is tied.

In a real implementation a tie-breaking rule must be defined in advance. Possible options:

  • choose a class by a fixed order;
  • use the probabilities of the models as an additional criterion;
  • apply a predefined priority of the classes;
  • return a tie if the interface or the task allows such an answer.

One cannot assume that every algorithm resolves a tie automatically in the same way.

3.1.6. Hard voting and soft voting: a comparison

Characteristic Hard Voting Soft Voting
What it combines The chosen classes The class probabilities
Takes the confidence of the models into account No Yes
What is needed from the model The predicted class The class probabilities
A possible drawback Loses information about confidence Depends on the quality of the probabilities
A simple example The majority of votes The mean of the probabilities

Let us remember: hard voting counts votes, soft voting averages probabilities.

3.2. Averaging for regression

For regression the models produce numbers. Therefore it is often natural to take their mean. Let three models predict the delivery time of an order:

  • model A: 30 minutes;
  • model B: 40 minutes;
  • model C: 35 minutes.

The average prediction:

\[ \hat y_{\text{ensemble}} =\frac{30+40+35}{3}. \]

First we add them up:

\[ 30+40+35=105. \]

Then we divide by the number of models:

\[ \hat y_{\text{ensemble}}=\frac{105}{3}=35. \]

The final forecast is 35 minutes.

3.2.1. The general formula

For \(M\) models with the forecasts \(\hat y_1,\hat y_2,\ldots,\hat y_M\):

\[ \hat y_{\text{ensemble}} =\frac{1}{M}\sum_{i=1}^{M}\hat y_i. \]

Let us go through the formula:

  • \(M\) — the number of models;
  • \(i\) — the index of the model;
  • \(\hat y_i\) — the forecast of model \(i\);
  • \(\sum\) — the summation sign, that is, the addition of all the listed quantities;
  • \(1/M\) — the factor that turns the sum into a mean.

For example, for the four forecasts 10, 12, 14 and 16:

\[ \hat y_{\text{ensemble}} =\frac{10+12+14+16}{4} =\frac{52}{4}=13. \]

3.2.2. How do the errors compensate for each other?

Suppose the true delivery time is 35 minutes. Three models produced 30, 40 and 35 minutes. The errors "forecast − truth":

\[ e_1=30-35=-5, \]
\[ e_2=40-35=+5, \]
\[ e_3=35-35=0. \]

The average error:

\[ \bar e=\frac{-5+5+0}{3}=0. \]

Since the positive and the negative error compensated for each other, the average forecast turned out to be accurate:

\[ \frac{30+40+35}{3}=35. \]

But one should not conclude that the average error is always zero. In our example this happened thanks to the particular numbers. Let us consider a counterexample. The true value is 35, and three models predict 50, 55 and 60.

Then:

\[ \hat y_{\text{ensemble}} =\frac{50+55+60}{3}=55. \]

The ensemble is wrong by 20 minutes. Averaging did not eliminate the systematic overstatement, because all three models were wrong in the same direction.

3.2.3. Weighted averaging

If the models have different quality, a weighted mean can be used:

\[ \hat y_{\text{ensemble}} =\frac{\sum_{i=1}^{M}w_i\hat y_i} {\sum_{i=1}^{M}w_i}. \]

Suppose:

  • model A predicts 30 minutes and has weight 2;
  • model B predicts 40 minutes and has weight 1.

Then:

\[ \hat y_{\text{ensemble}} =\frac{2\cdot30+1\cdot40}{2+1} =\frac{60+40}{3} =\frac{100}{3}\approx33.33. \]

The final forecast is approximately 33.33 minutes. Model A influences the result more strongly because its weight is larger.

However, the choice of the weights is a separate task. If they are assigned unsuccessfully, the weighted ensemble may turn out worse than a simple mean.

4. Why combining models sometimes helps

Now we have two ways of combining. But the main question remains: why can this improve quality at all?

4.1. The errors can differ

Imagine that three models predict the price of one object whose true value is 100.

Model Forecast Error
A 90 −10
B 105 +5
C 110 +10

The average forecast:

\[ \hat y=\frac{90+105+110}{3} =\frac{305}{3}\approx101.67. \]

The error of the ensemble:

\[ e_{\text{ensemble}}=101.67-100=1.67. \]

The individual errors were 10, 5 and 10 units in absolute value. The error of the mean turned out smaller than each of them.

Why did this happen? Model A underestimated the value, while the other two overestimated it. Their errors partially compensated for each other.

This is an example of how an ensemble can help, but not a proof that it will work like this on any data.

4.2. A counterexample: identical errors

Now all three models predict 120 while the true value is 100.

\[ \hat y=\frac{120+120+120}{3}=120. \]

The error of the ensemble equals \(+20\), just as for each base model. Adding models did not help: all of them were wrong in the same way.

This is the most important property of ensembling:

If the models make the same errors, simply increasing their number does not fix them.

Two panels with a horizontal axis and a dashed true-value line: on the left predictions lie on both sides of the line and the average marker lands on it, on the right all predictions are to the right of the line and the average marker is shifted right as well
When errors cancel each other out and when they do not. On the left ("errors cancel") the predictions of A and B deviate from the true value in opposite directions by equal distances, while C lands exactly on it: the ensemble mean falls on the true line. On the right ("errors agree") all three models err in the same direction and the mean stays far from the truth. Averaging pays off when the errors of the models differ.

4.3. Quality and diversity must be considered together

Four situations can be compared.

Quality of the base models Diversity of the errors What can be expected
High Useful The ensemble may improve the result
High Almost absent The additional benefit is often small
Low High The result is unpredictable: diversity does not guarantee success
Low Almost absent Combining usually fixes very little

This is a qualitative scheme, not a universal mathematical guarantee.

A good ensemble is not just a group of different models. You need models whose forecasts are useful and whose errors differ sufficiently.

5. Variance on a simple example

We have already met the word "variance" when discussing models. Now let us examine it mathematically.

5.1. The intuitive meaning

Imagine that several models were trained on slightly different training samples. Then each model predicts the price of the same apartment.

The first set of forecasts:

\[ 9.9,\quad10.0,\quad10.1. \]

The second set:

\[ 7,\quad10,\quad13. \]

The mean of both sets equals 10. But in the second case the forecasts are scattered around the mean much more strongly. This is the intuitive idea of variance: it characterises the magnitude of the spread of the values around the mean.

5.2. How to compute the variance

For the numbers \(x_1,x_2,\ldots,x_n\) the variance with division by \(n\) is defined by the formula:

\[ D=\frac{1}{n}\sum_{i=1}^{n}(x_i-\bar x)^2. \]

Here:

  • \(n\) — the number of numbers;
  • \(x_i\) — an individual number;
  • \(\bar x\) — the arithmetic mean;
  • \(x_i-\bar x\) — the deviation of the number from the mean;
  • the square \((x_i-\bar x)^2\) makes all the terms non-negative;
  • division by \(n\) gives the mean of the squares of the deviations.

Why are the deviations squared? If the deviations from the mean were simply added up, the positive and negative values would cancel each other out. The square makes it possible to measure the spread without allowing such compensation.

This formula describes the variance of the whole set under consideration. When estimating the variance of a population from a sample, another formula is often used — with division by \(n-1\). Here we need the first formula in order to understand the principle.

5.3. Computing by hand

Let us take the forecasts:

\[ 7,\quad10,\quad13. \]

Step 1. Compute the mean.

\[ \bar x=\frac{7+10+13}{3} =\frac{30}{3}=10. \]

Step 2. Compute the deviations from the mean.

  • \(7-10=-3\);
  • \(10-10=0\);
  • \(13-10=3\).

Step 3. Square the deviations.

  • \((-3)^2=9\);
  • \(0^2=0\);
  • \(3^2=9\).

Step 4. Add up the squares.

\[ 9+0+9=18. \]

Step 5. Divide by the number of values.

\[ D=\frac{18}{3}=6. \]

The variance equals 6. Now let us take the forecasts \(9,10,11\). The mean again equals 10.

The squares of the deviations:

\[ (-1)^2=1,\quad 0^2=0,\quad 1^2=1. \]

Consequently:

\[ D=\frac{1+0+1}{3}=\frac23\approx0.67. \]

The first set had a variance of 6 and the second about 0.67. So the first set of forecasts is scattered much more strongly.

5.4. Variance and standard deviation

The standard deviation is the square root of the variance.

\[ \sigma=\sqrt{D}. \]

For the first set:

\[ \sigma=\sqrt6\approx2.45. \]

For the second:

\[ \sigma=\sqrt{2/3}\approx0.82. \]

Variance is expressed in squared units. If we measure the forecasts in rubles, its unit of measurement is rubles squared. The standard deviation is measured in the same units as the original values.

That is why the standard deviation is often easier to interpret in practice.

5.5. Why the mean of several models can have a smaller variance

Suppose each model produces a forecast consisting of the correct value and an error:

\[ \hat y_i=y+\varepsilon_i. \]

Here:

  • \(y\) — the correct value;
  • \(\varepsilon_i\) — the error of model \(i\);
  • \(\hat y_i\) — the forecast.

The mean of the forecasts:

\[ \bar{\hat y} =\frac1M\sum_{i=1}^{M}\hat y_i. \]

Let us substitute the first expression:

\[ \bar{\hat y} =\frac1M\sum_{i=1}^{M}(y+\varepsilon_i). \]

Since the correct value \(y\) is the same for all models:

\[ \bar{\hat y} =y+\frac1M\sum_{i=1}^{M}\varepsilon_i. \]

It turns out that averaging the forecasts is equivalent to averaging the errors, if the true value is the same for all the forecasts.

If the errors are independent, have the same variance \(\sigma^2\) and zero expectation, the variance of the mean of the errors equals:

\[ \operatorname{Var}(\bar\varepsilon) =\frac{\sigma^2}{M}. \]

Here:

  • \(\operatorname{Var}\) — the variance operator;
  • \(\bar\varepsilon\) — the average error;
  • \(\sigma^2\) — the variance of the error of one model;
  • \(M\) — the number of models.

With independent errors, increasing the number of models reduces the variance of their mean. For example, if the variance of the error of one model equals 12, then with independent errors:

Number of models \(M\) Variance of the mean \(12/M\)
1 12
2 6
3 4
4 3
6 2

This is a mathematical result under the stated assumptions, not a promise that a real ensemble will behave exactly like this.

A bar chart with five decreasing bars: the first amber one is the tallest, the rest are light blue and about two, three, four and six times shorter
The variance of the mean falls as the number of models grows. The horizontal axis is the number of models (1, 2, 3, 4, 6) and the vertical axis is variance. The first bar, a single model, is the tallest; after that the height falls roughly as one divided by the number of models: half as tall with two models, a third with three. This is the same calculation as in the table: 12, 6, 4, 3, 2.

5.6. What changes if the errors are correlated?

Real models rarely make mistakes completely independently. They may be trained on the same data, use similar features and capture the same patterns.

If the errors are positively correlated, the mean retains part of the common spread. For equal error variances and an equal pairwise correlation \(\rho\) we get:

\[ \operatorname{Var}(\bar\varepsilon) =\frac{\sigma^2}{M} \left(1+(M-1)\rho\right). \]

This formula assumes the same variance for all the errors and the same correlation for every pair. If \(\rho=0\), the errors are uncorrelated and the formula simplifies to \(\sigma^2/M\).

If \(\rho=1\), all the errors coincide completely:

\[ \operatorname{Var}(\bar\varepsilon) =\frac{\sigma^2}{M}\cdot M =\sigma^2. \]

The variance does not decrease at all.

Conclusion: the usefulness of an ensemble depends not only on the number of models but also on the relationship between their errors.

Two panels with a horizontal error axis and a zero mark: on the left the points lie on both sides of zero and the amber average marker sits on zero, on the right all points are to the right of zero and the average is shifted right too
Why the correlation of errors matters. Each panel marks the errors of the individual models and their average. On the left ("independent") the errors have different signs: some models underestimate and others overestimate, so the average error lands exactly at zero. On the right ("correlated") all models err in the same direction, so the average stays far from zero. When the errors are correlated, averaging hardly helps.

6. Bias, variance and the bias-variance trade-off

6.1. An analogy with a target

Imagine that we are shooting at a target. The centre of the target is the correct value, and the hits are the forecasts of the model on different training samples.

Four cases are possible:

  • Small bias, small variance — the forecasts are close to the correct value and to each other.
  • Large bias, small variance — the models consistently give the wrong answer.
  • Small bias, large variance — the average result is close to the centre, but the individual forecasts differ strongly.
  • Large bias, large variance — the forecasts are simultaneously inaccurate and unstable.

This is an analogy. In machine learning bias and variance are determined mathematically, not by the visual arrangement of the hits.

On the left four targets with clusters of hits and arrows labelled bias and variance; on the right two bars of three segments, the lower one with a shorter amber variance segment and a dashed empty space at its end
Targets and the decomposition of the error. The four targets on the left are the four cases: hits tightly clustered at the centre (small bias and small variance), clustered but displaced to one side, spread around the centre, and spread with a displacement. The downward arrow is variance and the arrow to the right is bias. On the right the error is split into three parts: bias (grey), variance (amber) and irreducible noise (light blue). In the ensemble only the variance part is shorter, so an empty space outlined with dashes remains at the right end.

6.2. What bias is

Bias characterises the difference between the average prediction of a model and the true value. For a particular object \(x\) we can write:

\[ \operatorname{Bias}(x) =\mathbb E[\hat f(x)]-f(x). \]

Here:

  • \(f(x)\) — the true relationship that we want to predict;
  • \(\hat f(x)\) — the prediction of the trained model;
  • \(\mathbb E[\hat f(x)]\) — the average prediction over the possible training samples;
  • \(\operatorname{Bias}(x)\) — the bias for the object \(x\).

The sign of the bias shows the direction of the systematic deviation.

For example, if the true price is 10 million and the average forecast of models trained on different samples is 8 million, the bias equals \(-2\) million.

6.3. What variance is

Variance characterises how much the prediction changes when the training data changes. For an object \(x\):

\[ \operatorname{Var}(\hat f(x)) =\mathbb E\left[ \left(\hat f(x)-\mathbb E[\hat f(x)]\right)^2 \right]. \]

In simple words:

  1. Obtain forecasts on different training samples.
  2. Compute the mean of these forecasts.
  3. Find the deviation of each forecast from the mean.
  4. Square the deviations.
  5. Average the squares.

If the forecasts are close to each other, the variance is small. If they differ strongly, the variance is large.

6.4. What data noise is

Noise is a random component of the data that the model cannot reliably explain with the available features.

For example, two apartments with the same area, district and number of rooms may be sold at different prices because of factors we do not observe or because of random market fluctuations.

Even an ideal model that knows the whole relationship will not necessarily be able to predict every such deviation exactly.

For a standard regression task with squared error the expected error at a point \(x\) can be represented as:

\[ \mathbb E[(\hat f(x)-y)^2] = \operatorname{Bias}(\hat f(x))^2 +\operatorname{Var}(\hat f(x)) +\sigma_{\text{noise}}^2. \]

Here it is assumed that the observed value consists of the true relationship and random noise with zero mean, and that the noise does not depend on the training procedure.

Let us go through the meaning:

  • the square of the bias — a systematic error;
  • the variance — the instability of the forecasts;
  • the noise variance — a random component that cannot be eliminated by improving the model alone.

The formula helps to understand why a model may have good quality on the training data but poor quality on new data.

6.6. Training and test error

The training set is the data on which the model is trained. The test set is separate data intended for an independent assessment of quality after the model has been chosen.

If the model has fitted the training examples too closely, it may predict their answers excellently but perform worse on new data. This is called overfitting.

Ensembling sometimes helps to reduce instability and overfitting, but it does not guarantee that they are eliminated.

6.7. Why does averaging reduce variance but not necessarily bias?

If the models make mistakes in different ways, averaging can reduce the random fluctuations of their forecasts. However, if all the models systematically underestimate the prices of apartments, the mean may also turn out too low.

Consequently:

  • averaging can reduce the variance;
  • it does not have to eliminate the bias;
  • the general noise of the data also does not disappear automatically.

That is exactly why, before building an ensemble, it is important to understand which problem we are trying to solve.

7. Bagging

7.1. Why bagging is needed

Imagine that we have a single training set of 1000 apartments and a decision tree algorithm.

If several trees are trained on the same data with the same settings and without random elements, they may turn out identical. Combining their predictions will give almost nothing.

How can we obtain several different models if there is only one set of training data? One way is to create different samples from the original set using the bootstrap.

Bagging is short for Bootstrap Aggregating, that is, "bootstrap samples plus combining".

The main idea:

  1. Create several samples from the original training data.
  2. Train an individual model on each sample.
  3. Combine the predictions of the models.

7.2. What a bootstrap sample is

A bootstrap sample is a sample obtained from the original set by randomly selecting objects with replacement. Let us examine the phrase "with replacement".

Imagine that the original sample contains four objects:

\[ A,\ B,\ C,\ D. \]

With ordinary selection without replacement we can choose, for example:

\[ A,\ C,\ D, \]

but we cannot choose A again until we start a new round of selection.

With selection with replacement, after every choice the object is, as it were, returned to the common set. Therefore it can be chosen again.

A bootstrap sample of four choices may look like this:

\[ A,\ C,\ A,\ D. \]

The object A occurred twice while B did not occur at all. This is normal: repeated objects are not new observations but the repeated inclusion of the same training example.

7.3. An example of creating several samples

The original data:

\[ D=\{A,B,C,D,E\}. \]

Let us create three bootstrap samples of five choices each.

Sample The objects obtained Which objects did not get in
1 A, B, A, D, E C
2 B, C, C, E, B A, D
3 A, C, D, D, E B

Each sample contains five positions, just like the original set. But the number of unique objects may be less than five. We train an individual model on each sample:

  • model 1 — on sample 1;
  • model 2 — on sample 2;
  • model 3 — on sample 3.

Now the models have been trained on slightly different data and may produce different forecasts.

A diagram: a card of original data with objects A to E, three sample cards with repeated letters, three tree-model cards, an aggregation box and a prediction card with mean and vote badges
Bagging: samples, models, aggregation. From the original set of five objects ("original data") three bootstrap samples of five positions are drawn: A, B, A, D, E; B, C, C, E, B and A, C, D, D, E — objects repeat and some never appear. A separate model is trained on each sample ("model 1"–"model 3"), their answers converge into the aggregation box, and the result is produced as a mean or a vote ("mean" and "vote" in the prediction card).

7.4. Why can this help?

Some algorithms, especially decision trees, can change their structure substantially in response to a small change in the training data.

Such a model is called unstable with respect to the sample.

Bagging creates several variants of the training set and combines the results of the models. If changes in the sample lead to different errors, averaging can reduce the variance of the final forecast.

At the same time, bagging does not guarantee that the models will differ sufficiently. The effect depends on the algorithm, the data and the parameters.

7.5. The out-of-bag (OOB) estimate

We have noticed that not all the original objects get into a bootstrap sample.

The objects that did not get into the sample of a particular model are called out-of-bag objects for that model.

They can be used to assess the model without using the objects on which it was trained. For example:

  • model 1 was trained on A, B, A, D, E;
  • the object C did not get into its training sample;
  • model 1 can make a prediction for C;
  • this prediction can be compared with the true answer for C.

In this way an OOB score (Out-of-Bag Score) is formed.

For an overall quality estimate, the suitable OOB predictions for the original objects are combined and compared with the true answers.

A three-by-five grid: rows are models and columns are objects, most cells hold light blue tokens and four cells are dashed; on the right a column of amber predictions for the dashed cells, below a final score box and a legend
Out-of-bag: estimating on objects the model has never seen. In the grid the rows are models and the columns are objects: light blue cells mean the object was in that model's bootstrap sample, dashed empty cells mean it was not. For every such cell the model can make a prediction (the amber tokens in the "OOB prediction" column), and all those predictions are collected into a single "OOB score" — it is computed on the objects the model did not use for training. The legend in the lower left corner explains the colours.

Important limitations:

  • not every object will necessarily receive a sufficient number of OOB predictions in a small ensemble;
  • the reliability depends on the volume of the data and the number of models;
  • the OOB estimate should not automatically be considered an error-free replacement for an independent test evaluation.

7.6. What to remember about bagging

  • One original dataset — several bootstrap samples are created from it.
  • Several base models — each model is trained on its own sample.
  • Combining the predictions — for regression the mean is usually used, for classification voting.

8. Random Forest — an overview

Random Forest is an ensemble method based on a set of decision trees.

This is a preliminary introduction: the algorithm, its parameters and the features of its implementation are not examined in detail here.

The main idea combines several mechanisms:

  1. Several trees are trained.
  2. Each tree usually uses its own bootstrap sample.
  3. When searching for a split of a tree node, a random subset of the features is considered, not necessarily all the features.
  4. The predictions of the trees are combined: for classification by voting, for regression by averaging.

Why is randomness in the features needed?

Imagine that one feature is very informative and almost every tree chooses it for the top split. Then the trees may turn out similar to each other.

If at every split only a random subset of the features may be chosen, the trees have more opportunities to build different structures.

This can reduce the similarity of the trees and increase the benefit of combining them.

Three levels: a card with features f1 to f5, three trees with conditions in their roots and three highlighted features above each, below a vote box and an amber prediction card
Random Forest: trees plus random subsets of features. Five features ("features") are shown at the top, and above each tree only three of them are highlighted: for tree 1 these are f1, f2 and f4, for tree 2 f2, f4 and f5, and for tree 3 f1, f3 and f5. Each tree builds its conditions only from the features it was allowed to use: the condition in the root uses one of them. The answers are then combined by voting ("vote") into the final prediction.

Important: Random Forest is a specific algorithm with its own rules for training trees. Bagging is a more general idea that can also be applied to other base models.

Let us stop here. We will return to the detailed structure of the random forest if it is needed in later lectures.

9. Stacking and Blending

Bagging creates diversity by changing the training samples. But there is another approach: a separate model can be trained to decide how to combine the predictions of the other models.

This is called stacking.

9.1. How stacking is arranged

The scheme consists of four steps:

  1. Base models. Model A, model B and model C make their predictions.
  2. The predictions of the base models. For example: 8.0 · 9.0 · 8.5.
  3. The meta-model. It learns to combine the predictions of the base models.
  4. The final forecast. The answer for a new object.
A diagram: a new object card, three base models with different glyphs and output tokens joined by a predictions bracket, a meta-model box with a training card below it and a final prediction card
Stacking: base models and a meta-model. A new object passes through three different base models, and each produces its own prediction; the three predictions are collected into one column ("predictions"). They are then passed to the meta-model, which learns how to combine them — the separate "training" card below it feeds it. The meta-model's answer is the final prediction.

A meta-model is a second-level model that receives the predictions of the base models and learns from them. For example, in regression the base models produce three numbers:

\[ 8.0,\quad9.0,\quad8.5. \]

In a simple case the meta-model may be a linear model that learns to assign different weights to these forecasts.

Unlike an ordinary mean, the meta-model can learn to take into account that one base model usually predicts certain types of object better and another model predicts others better.

9.2. Why data leakage arises

Data leakage is a situation in which information that should not be available to the model in the corresponding process gets into its training or evaluation.

Let us consider stacking.

Suppose a base model was trained on 1000 objects. Then we obtained its predictions on those same 1000 objects and use them as input data for training the meta-model.

What is the problem?

If the base model has fitted the training data well, its predictions on those objects may be much better than its predictions on new data. The meta-model will see an overly optimistic picture of how the base models work and may learn the wrong way of combining them.

It is especially dangerous if the base models have overfitted.

9.3. Out-of-fold predictions

To avoid this problem, out-of-fold predictions (OOF predictions) are used. A fold is one of the parts into which the data is divided during cross-validation.

The principle:

  1. Divide the training data into several parts.
  2. Train the base model on all the parts except one.
  3. Obtain predictions for the excluded part, which the model did not use during training.
  4. Repeat the process, excluding different parts.
  5. Combine the predictions so that every training object has a prediction from a model that was not trained on it.
  6. Use these predictions to train the meta-model.

OOF predictions give the meta-model a more realistic idea of how the base models will perform on new data. At the same time, all the levels of stacking must be trained and evaluated without leaking information from the test set.

9.4. What blending is

Blending is a way of ensembling in which the meta-model is trained on the predictions of the base models for a separate held-out part of the training data.

For example:

  • on the larger part of the data we train the base models;
  • on a separate validation part we obtain their predictions;
  • from these predictions we train the meta-model.

The main difference in general terms:

Method How the data for the meta-model is obtained
Stacking OOF predictions obtained through several splits are often used
Blending Predictions on a separate held-out part of the data are usually used

Blending is simpler to arrange, but part of the data has to be held out for the second level. Stacking uses the data more efficiently, but it requires a more complex training procedure.

Both methods require a careful separation of the data. The mere presence of a meta-model does not make an ensemble automatically good.

10. How to evaluate an ensemble

An ensemble can look convincing on the training data and still perform poorly in real conditions. So what needs to be evaluated is not the elegance of the scheme or the number of models, but the quality of the predictions on data that was not used for training.

10.1. Why is the training set not enough?

Suppose we have trained a model on historical customer data. If it has memorized the characteristics of exactly these customers, quality on the training data will be high.

But when new customers appear, the model may make mistakes. For evaluation, the following are usually used:

  • the training set — for training models;
  • a validation set — for choosing algorithms, parameters and the way of combining them;
  • a test set — for the final independent evaluation of the chosen solution.

The ensemble weights must not be tuned endlessly by looking at the test set: in that case the test stops being an independent estimate.

10.2. What should an ensemble be compared with?

A strong ensemble should be compared not only with a deliberately weak baseline model, but also with a good single model. It is useful to check:

  1. How much the ensemble improves the chosen metric.
  2. Whether the improvement holds on independent data.
  3. Whether the improvement is large enough to justify the additional cost.
  4. Whether other important indicators have got worse.
  5. How much time and memory the solution requires.

For classification you can use the metrics you have already studied, for example accuracy, precision, recall and F1-score. For regression — MAE and MSE.

For example, if an ensemble increased accuracy from 90.0% to 90.1% but requires ten times more computation, such a gain may not be worthwhile. It all depends on the cost of an error and the requirements of the particular system.

10.3. What to consider besides quality?

Criterion Question
Quality Has the prediction become more accurate on new data?
Speed How long does it take to get an answer?
Memory Do all the base models need to be stored?
Training How expensive is it to train the ensemble?
Interpretability Can it be explained why such an answer was produced?
Stability Does the quality hold on different data?

An ensemble is an engineering trade-off. Sometimes a model that is slightly worse on the metric but far simpler is better.

11. A practical end-to-end example

Let us look at a classification task: we need to predict whether a customer will leave the service. Suppose we have three customers, and three models produce the following predictions:

Customer True class Model A Model B Model C
1 Will leave Will leave Will leave Will stay
2 Will stay Will stay Will leave Will stay
3 Will leave Will stay Will leave Will leave

11.1. Combining the predictions

We use hard voting. Customer 1: two votes for "will leave", one for "will stay". The result is "will leave". Correct.

Customer 2: two votes for "will stay", one for "will leave". The result is "will stay". Correct. Customer 3: two votes for "will leave", one for "will stay". The result is "will leave". Correct.

We get three correct predictions out of three.

\[ \text{Accuracy}=\frac{3}{3}=1=100\%. \]

Accuracy is the share of correct predictions among all predictions.

11.2. Comparison with the individual models

Model A correctly predicted the classes of customers 1 and 2: two out of three.

\[ \text{Accuracy}_A=\frac23\approx66.7\%. \]

Model B correctly predicted the classes of 1 and 3:

\[ \text{Accuracy}_B=\frac23\approx66.7\%. \]

Model C correctly predicted the classes of 2 and 3:

\[ \text{Accuracy}_C=\frac23\approx66.7\%. \]

In this example the ensemble turned out better than each individual model.

Two panels showing the spread of predictions around the true value (wide on the left, narrow on the right) and a bar chart of accuracy where three light blue bars are equal and the amber ensemble bar is taller
An ensemble versus a single model. The upper panels show the spread of predictions: for a single model the six forecasts are scattered far from the true value, while for the ensemble they are grouped around it and the amber marker sits exactly on the true line. The lower chart shows accuracy: models A, B and C are all the same height while the ensemble bar is clearly taller. In the example of the section each model predicted 2 out of 3 clients correctly, and the ensemble 3 out of 3.

But note the size of the sample: only three customers. Such an example helps you understand the arithmetic, but it does not allow a reliable conclusion about the quality of a real system.

11.3. What happens if the errors coincide completely?

Suppose all three models make a mistake on the same customer, giving it the wrong class. A majority vote cannot fix that error if the models all choose the same wrong answer together.

That is exactly why, when evaluating an ensemble, it is important to study not only the accuracy of each model but also which objects they make mistakes on.

11.4. A separate bagging example

The original training sample:

\[ D=\{A,B,C,D,E\}. \]

Let us form two bootstrap samples:

\[ D_1=\{A,B,A,D,E\}, \]
\[ D_2=\{B,C,C,D,B\}. \]

Let us train two decision trees:

  • tree 1 on \(D_1\);
  • tree 2 on \(D_2\).

For a new object the first tree predicts "will leave" and the second "will stay".

If we add a third tree trained on another bootstrap sample, and it chooses "will leave", the majority of the three trees gives the answer "will leave".

We have obtained the basic principle of bagging: diversity of training samples, training individual models and combining their predictions.

12. Advantages, limitations and typical mistakes

12.1. Main advantages

  • An ensemble can improve prediction quality.
  • Averaging can reduce the spread of unstable models.
  • Different models can complement each other.
  • Bagging makes it possible to use one training set to create several variants of the training data.
  • Stacking makes it possible to learn to combine predictions in different ways.

12.2. Main limitations

  • Several models have to be stored and run.
  • Training can take longer.
  • The final prediction is often harder to explain.
  • Bad base models do not automatically become good.
  • When the errors are strongly correlated, the benefit of averaging decreases.
  • With a large number of models, additional costs can arise without a noticeable improvement in quality.

12.3. Eight common misconceptions

Misconception 1. The more models, the better. Incorrect. If the errors are strongly correlated, additional models may barely improve the result.

Misconception 2. Any different models give a good ensemble. Incorrect. The diversity must be useful, and the base models must produce sufficiently good predictions.

Misconception 3. Averaging always reduces the error. Incorrect. If all the predictions are wrong in the same direction, the average may remain far from the truth.

Misconception 4. Hard voting and soft voting are the same thing. Incorrect. Hard voting combines the chosen classes, while soft voting combines the class probabilities.

Misconception 5. Bootstrap is simply a random sample without replacement. Incorrect. Bootstrap uses sampling with replacement, so objects can repeat.

Misconception 6. An OOB estimate guarantees quality on any new data. Incorrect. It depends on the data and the training procedure, and also on the number of models and OOB predictions.

Misconception 7. A meta-model can be trained on any predictions of the base models.

Incorrect. If the predictions were obtained on the same objects the base models were trained on, there is a risk of leakage and excessive optimism. To train a meta-model, OOF predictions or a separate held-out part of the data are usually used.

Misconception 8. An ensemble is necessarily better than a single model. Incorrect. The improvement has to be checked on independent data and weighed against the computational costs.

One more useful principle: an ensemble is not a substitute for a sound problem statement, good data and correct evaluation. It will not automatically fix bias, labelling errors or data leakage.

13. Preparing for an ML interview

Below are questions from basic to more complex. The short answer can be used for a spoken interview, and the clarification is there to help you really understand the topic.

Question 1. What is a model ensemble?

Short answer: an ensemble is a method in which the predictions of several models are combined into a single final prediction.

In more detail: the models can be of the same type or different. For classification, voting is used; for regression, averaging; and in stacking a meta-model is trained.

Question 2. Why can several models perform better than one?

Short answer: if the models are good enough and make different errors, combining them can compensate for part of those errors.

In more detail: this is especially useful when the predictions are widely spread. But combining does not fix identical systematic errors.

Question 3. How does hard voting differ from soft voting?

Short answer: hard voting counts votes for classes, while soft voting averages class probabilities. Example: two models barely prefer class A, and one very confidently chooses B. Hard voting may choose A, soft voting B.

Question 4. How are predictions averaged in regression?

Short answer: the mean or weighted mean of the predictions of the base models is computed.

\[ \hat y=\frac1M\sum_{i=1}^{M}\hat y_i. \]

Here \(M\) is the number of models and \(\hat y_i\) is the prediction of model \(i\).

Question 5. What is diversity?

Short answer: diversity is the differences in the predictions or errors of the base models.

In more detail: diversity is useful when the models complement each other. Random or bad predictions do not by themselves make an ensemble good.

Question 6. Why does the correlation of errors matter?

Short answer: the more the models make the same mistakes, the fewer errors averaging can compensate for.

In more detail: with independent errors, averaging usually reduces variance more effectively than with completely coinciding errors.

Question 7. What are bias and variance?

Short answer: bias is a systematic deviation of the model from the correct dependence, and variance is the sensitivity of the predictions to changes in the training data.

In more detail: averaging can reduce variance, but it does not have to eliminate bias.

Question 8. What is bagging?

Short answer: bagging, or Bootstrap Aggregating, is training several models on bootstrap samples and then combining their predictions.

In more detail: it is especially useful for unstable models, for example decision trees.

Question 9. What is a bootstrap sample?

Short answer: a sample obtained by randomly selecting objects from the original set with replacement. Example: from A, B, C, D you can get A, C, A, D. Object A repeats, and B is absent.

Question 10. What does sampling with replacement mean?

Short answer: after each selection the object becomes available again for the next selection. In more detail: that is why one object can appear several times, while another does not make it into the sample.

Question 11. What is an OOB estimate?

Short answer: an estimate of quality on the objects that did not participate in training the corresponding bootstrap model.

In more detail: for the final estimate, the OOB predictions of the models for the original objects are collected and compared with the true answers.

Question 12. How does bagging reduce the spread?

Short answer: it trains several models on slightly different samples and combines the predictions, reducing the influence of the random characteristics of any one sample.

In more detail: the effect is stronger when the base models are unstable and the errors differ enough.

Short answer: Random Forest is an ensemble of decision trees that uses bagging and a random selection of a subset of features for the splits.

In more detail: the randomness in the features helps make the trees less similar to each other.

Question 14. What is stacking?

Short answer: an ensembling method in which a meta-model learns to combine the predictions of the base models. In more detail: the base models form second-level features, and the meta-model produces the final prediction.

Question 15. Why is a meta-model needed?

Short answer: it learns how to combine the predictions of the base models. Example: in regression a meta-model can assign different weights to different predictions.

Question 16. What are out-of-fold predictions?

Short answer: predictions for the objects that were not used to train the corresponding base model.

In more detail: they are obtained by splitting the training data into folds and are used to train the meta-model without a direct leakage of the training answers through the base predictions.

Question 17. Why does data leakage arise in stacking?

Short answer: if the meta-model is trained on the predictions of the base models for the objects those models were trained on, the predictions can be too optimistic.

In more detail: the meta-model will see a quality of the base models that does not correspond to their behaviour on new objects. That is why correct OOF predictions or a separate sample for the second level are needed.

Question 18. What disadvantages do ensembles have?

Short answer: additional computational costs, difficulty of interpretation, dependence on the base models and no guarantee of improved quality.

In more detail: an ensemble is worth using if the gain on independent data justifies its complexity.

14. Tasks for independent solution

First try to solve the tasks on your own. Different levels of difficulty are deliberately included here: from simple arithmetic to reasoning about the quality of an ensemble.

Block A. Hard Voting and Soft Voting

Tasks 1–3

1. Hard voting

Four models classify a review. Their answers are: positive, negative, positive, positive. Which class will hard voting choose? How many votes will each class get?

2. Soft voting

Two models estimate the probability of class A as 0.8 and 0.4, and of class B as 0.2 and 0.6. Compute the average probabilities and the final class.

3. Different results

Three models produced probabilities of class A: 0.51; 0.51; 0.01. The probabilities of class B are 0.49; 0.49; 0.99 respectively. Which class wins under hard voting and under soft voting?

Block B. Averaging in regression

Tasks 4–5

4. The average prediction

Four models predict a price: 100, 110, 90 and 120 thousand roubles. Compute the average prediction.

5. The weighted mean

The first model predicts 20 and the second 50. Their weights are 3 and 1. Compute the final prediction.

Block C. Variance and spread

Tasks 6–7

6. Variance by hand

For the values 2, 4 and 6, compute the mean and the variance with division by \(n\).

7. Independent errors

The error variance of one model equals 16. Suppose the errors of four models are independent, have the same variance and zero mean. What is the variance of the average error?

Block D. Bootstrap and Bagging

Tasks 8–10

8. Sampling with replacement

From the objects A, B, C, D the bootstrap sample A, C, A, D was obtained. Which objects repeat? Which object did not make it into the sample?

9. Training the models

There are 100 original objects and three bootstrap samples of 100 draws each. Must each sample necessarily contain exactly 100 distinct objects? Explain.

10. OOB

A model was trained on the objects A, B, D, E. The original sample also contains the object C. Can C be used for the OOB estimate of this model if the model was not trained on C?

Block E. Stacking and data leakage

Tasks 11–12

11. A mistake in training the meta-model

A base model was trained on 1000 objects. Its predictions on those same objects were passed to the meta-model. Why can this lead to a problem?

12. OOF

Explain why OOF predictions are usually better suited for training a meta-model than the predictions of the base models on their own training objects.

Block F. Choosing a suitable approach

Tasks 13–14

13. Unstable trees

Small changes in the training sample strongly change the structure of a decision tree. Which of the approaches you have studied is especially appropriate to try, and why?

14. Different models and a meta-model

There is a linear model, a decision tree and another model whose predictions complement each other. You need to learn how to choose a combination of their predictions from the data. Which approach should be considered, and what danger must be taken into account?

Show detailed solutions

1. Hard Voting

Three models chose the positive class and one chose the negative class.

\[ V(+)=3,\qquad V(-)=1. \]

Since \(3>1\), the final class is positive.

2. Soft Voting

For class A:

\[ P(A)=\frac{0.8+0.4}{2}=\frac{1.2}{2}=0.6. \]

For class B:

\[ P(B)=\frac{0.2+0.6}{2}=\frac{0.8}{2}=0.4. \]

Since \(0.6>0.4\), we choose class A.

3. Hard Voting versus Soft Voting

Under hard voting each model chooses the class with the higher probability:

  • model 1: A;
  • model 2: A;
  • model 3: B.

The score is two votes for A and one for B. Under soft voting:

\[ P(A)=\frac{0.51+0.51+0.01}{3} =\frac{1.03}{3}\approx0.3433. \]
\[ P(B)=\frac{0.49+0.49+0.99}{3} =\frac{1.97}{3}\approx0.6567. \]

The result: hard voting chooses A, soft voting chooses B.

4. The average prediction

\[ \hat y=\frac{100+110+90+120}{4}. \]

First we add up:

\[ 100+110+90+120=420. \]

We divide by four:

\[ \hat y=\frac{420}{4}=105. \]

Answer: 105 thousand roubles.

5. The weighted mean

\[ \hat y=\frac{3\cdot20+1\cdot50}{3+1}. \]

In the numerator:

\[ 3\cdot20+1\cdot50=60+50=110. \]

In the denominator:

\[ 3+1=4. \]

Consequently:

\[ \hat y=\frac{110}{4}=27.5. \]

Answer: 27.5.

6. Variance

The mean:

\[ \bar x=\frac{2+4+6}{3}=4. \]

The deviations:

\[ 2-4=-2,\qquad4-4=0,\qquad6-4=2. \]

The squared deviations:

\[ (-2)^2=4,\qquad0^2=0,\qquad2^2=4. \]

The variance:

\[ D=\frac{4+0+4}{3}=\frac83\approx2.67. \]

7. Independent errors

With independent errors of equal variance:

\[ \operatorname{Var}(\bar\varepsilon)=\frac{\sigma^2}{M}. \]

Here \(\sigma^2=16\) and \(M=4\).

\[ \operatorname{Var}(\bar\varepsilon)=\frac{16}{4}=4. \]

Answer: the variance of the average equals 4. We obtained this value thanks to the assumption that the errors are independent.

8. Bootstrap

In the sample A, C, A, D the object A repeats twice. The object B did not make it into the sample. This is admissible, because bootstrap uses sampling with replacement.

9. The number of unique objects

No, not necessarily.

Although each bootstrap sample contains 100 draws, some of them may fall on the same object. That is why the number of unique objects can be less than 100.

10. OOB

Yes. The object C did not participate in training this model, so its prediction for C can be used as an OOB prediction. For a reliable overall estimate, a sufficient number of models and enough OOB predictions for each object are needed.

11. Leakage in stacking

The model has already been trained on those 1000 objects. Therefore its predictions on them can be too good, especially if the model has overfitted.

The meta-model will see uncharacteristically optimistic results and may misjudge the usefulness of the base model on new data.

12. OOF predictions

To obtain an out-of-fold prediction, the corresponding object is excluded from the training part of a particular model.

That is why such predictions better reflect the situation in which a base model encounters a previously unseen object. This reduces the risk of leakage associated with using the training answers at the same level.

13. Unstable trees

It is worth trying bagging. It makes it possible to train several trees on bootstrap samples and combine the predictions. If the trees react to the data differently, the average or the vote can reduce the spread.

14. Meta-model

A suitable option is stacking. The meta-model receives the predictions of the base models and learns to combine them. To avoid leakage, OOF predictions or predictions on a separate held-out part of the data are usually used to train it.

15. Glossary of terms

Term Simple explanation Why it is needed
Ensemble Several models combined into one system Improving predictions
Base learner An individual model inside an ensemble Producing the initial predictions
Voting Choosing the final class by votes Combining classifiers
Hard voting Voting by the chosen classes Choosing a class by majority
Soft voting Combining class probabilities Taking the confidence of the models into account
Averaging Computing the mean of the predictions Combining numerical answers
Diversity Differences between predictions and errors Benefiting from combining
Correlated errors Errors that change in a coordinated way Understanding the limitations of an ensemble
Bias A systematic deviation of the predictions Analysing model errors
Variance The sensitivity of predictions to the data Understanding instability
Bootstrap sample A sample obtained with replacement Creating different training sets
Sampling with replacement A selected object can appear again Forming bootstrap samples
Bagging Training on different bootstrap samples and combining the predictions Reducing the spread
OOB score An estimate on the objects not used by a particular model in training Estimating quality without separate retraining on those objects
Random Forest An ensemble of trees with additional randomness in the choice of features Obtaining an ensemble of less similar trees
Stacking Combining through a trainable meta-model Learning to combine predictions
Blending Training a meta-model on a separate held-out sample Combining models at the second level
Meta-model A model that combines the predictions of other models Learning to choose a combination of predictions
Out-of-fold predictions Predictions for objects excluded from training the corresponding model Training a meta-model without direct leakage of training answers
Data leakage Using information unavailable to the model in correct prediction Avoiding dishonest evaluation and overfitting

16. Final summary

16.1. Topic map

  1. Base models

    Each model makes a separate prediction: a class or a number.

  2. The way of combining

    The predictions of the base models are reduced to a single answer, and the way depends on the task:

    • Classification — voting:
      • hard voting chooses the class by majority vote: \(\hat y=\arg\max_c V(c)\);
      • soft voting averages the probabilities: \(P(c\mid x)=\frac1M\sum_{i=1}^{M}P_i(c\mid x)\).
    • Regression — averaging the predictions: \(\hat y=\frac1M\sum_{i=1}^{M}\hat y_i\), weighted if necessary.
  3. Bagging

    Different bootstrap samples → training base models → combining their predictions.

  4. Why this works

    Averaging reduces the spread of unstable models: with independent errors the variance of the average equals \(\operatorname{Var}(\bar\varepsilon)=\frac{\sigma^2}{M}\).

  5. Random Forest

    Bagging of trees plus a random selection of features at the splits: the trees turn out less similar to each other.

  6. OOB estimate

    Each object is tested on the models that did not see it, so quality can be estimated without a separate sample.

  7. Stacking and blending

    Predictions of the base models → meta-model → result. The meta-model is trained on out-of-fold predictions or on a held-out part of the data.

  8. Checking the solution

    The ensemble is compared with a strong single model on data that was not used for training.

16.2. Comparison of methods

Method How it works Strength Limitation
Hard Voting Counting votes for the classes Simplicity Does not take confidence into account
Soft Voting Averaging the probabilities Takes the probability distribution into account Depends on the quality of the probabilities
Averaging The mean of numerical predictions Can reduce the spread Does not automatically fix systematic errors
Bagging Training on bootstrap samples Reducing the spread of unstable models Requires several models
Random Forest An ensemble of trees with randomness in the features Diversity of the trees More computation than a single tree
Stacking A trainable meta-model Can use the strengths of different models Leakage has to be avoided
Blending A meta-model on a held-out part of the data A relatively simple second-level scheme Part of the data is reserved for the meta-model

16.3. Main formulas

1. Hard voting

\[ \hat y=\arg\max_c V(c). \]

We choose the class \(c\) that has collected the maximum number of votes \(V(c)\). 2. Soft voting

\[ P(c\mid x)=\frac1M\sum_{i=1}^{M}P_i(c\mid x). \]

We average the class probabilities from \(M\) models. 3. Averaging regression predictions

\[ \hat y=\frac1M\sum_{i=1}^{M}\hat y_i. \]

We add up the predictions and divide by the number of models. 4. The weighted mean

\[ \hat y=\frac{\sum_i w_i\hat y_i}{\sum_i w_i}. \]

The predictions are multiplied by the weights \(w_i\); a larger weight means a larger contribution. 5. The variance of a set

\[ D=\frac1n\sum_{i=1}^{n}(x_i-\bar x)^2. \]

The mean squared deviation of the values from their mean. 6. The variance of the average of independent errors

\[ \operatorname{Var}(\bar\varepsilon)=\frac{\sigma^2}{M}. \]

With independent errors of equal variance, averaging reduces the variance by a factor of \(M\). 7. Bias, variance and noise

\[ \mathbb E[(\hat f(x)-y)^2] = \operatorname{Bias}^2+\operatorname{Var}+\sigma_{\text{noise}}^2. \]

This formula requires assumptions about the noise model and the way the data is generated, which were discussed in part 6.

16.4. Ten main ideas

  1. An ensemble combines the predictions of several models.
  2. For classification, voting is used; for regression, averaging.
  3. Hard voting combines classes, soft voting combines probabilities.
  4. Diversity is useful when the models complement each other.
  5. Correlated errors reduce the benefit of an ensemble.
  6. Averaging can reduce variance, but it does not guarantee the elimination of bias.
  7. Bagging trains models on bootstrap samples created with replacement.
  8. An OOB estimate uses the objects that did not make it into the training sample of the corresponding model.
  9. Stacking uses a meta-model; OOF predictions help avoid leakage.
  10. Any ensemble must be compared with a strong single model on independent data.

16.5. An answer for an interview

Question: "Why are ensembles needed and how do they work?"

Ensembles are machine-learning methods in which the predictions of several base models are combined into a single final prediction. In classification you can use hard voting by classes or soft voting by probabilities, and in regression, averaging of the predictions. Ensembles can improve quality if the base models are strong enough and make different errors. Bagging creates diversity by training on bootstrap samples, while stacking uses a meta-model that learns to combine the predictions of the base models. At the same time, ensembles require additional computation, do not guarantee an improvement and must be evaluated on data that was not used for training.

What is important to know before the next lecture

The next topic is Lecture 11: "Gradient Boosting I". The main difference that is useful to remember already:

  • Bagging trains several models on different samples and combines their predictions. This helps reduce the spread.
  • Boosting is a family of methods in which models are built successively and the following steps aim to improve the result already obtained.

In this lecture we looked in detail at ensembles in general, bagging, an overview of Random Forest and the basics of stacking. We leave gradient boosting, AdaBoost, XGBoost, LightGBM and CatBoost for the following lectures, where we will be able to work through their mechanism without rushing.

And one more thing: you do not need to memorize all the formulas at once. To begin with it is enough to understand confidently the difference between voting and averaging, the idea of error diversity, the meaning of bagging and the purpose of a meta-model. You can return to the variance formulas and the more complex interview questions gradually — already relying on these basic ideas.

Practice in the interactive lab

Three actions for this lecture: see how one model builds a boundary, change the complexity of the model and work out where the spread of predictions comes from.

  1. Look at the boundary of one model — open "KNN: the K nearest neighbours": the boundary is built by the training objects. An ensemble works with several such models at once: in classification their answers are combined by voting, so the final boundary turns out to be a compromise between the boundaries of the base models.

  2. Change the complexity of the model — open "Polynomial degree: overfitting" and move the degree slider: a model that is too simple underfits, one that is too complex overfits. The same applies to the base models of an ensemble: if each of them is unstable, averaging reduces the spread of their predictions.

  3. Explain where the spread comes from — open "Descent along the loss function": a ball descends along the loss surface, and different starting points lead to different places. Something similar happens with an ensemble: different training samples give different models, and combining their predictions smooths out that spread.

There is no separate demo about ensembles in the lab: these three pages show related ideas — the boundary of one model, overfitting and the spread of predictions.

Check yourself