Skip to content

Lesson 6 · Logistic Regression

⏱ 63 min read

Logistic regression predicts the probability of an event: whether an offer will be accepted, a patient will fall ill, an email is spam. The topic comes up often both in real ML projects and in technical interviews.

We will work through the concepts along the way: first simple intuition, then definitions and formulas with every symbol decoded, then numerical examples.

1. Why logistic regression is needed

1.1. A real task

Imagine there is a mail service. Every day thousands of emails arrive, and you need to determine automatically which of them are spam.

A mail service: emails pass a check and are distributed into the Inbox and Spam folders
Spam filtering is a classification task. Every email is described by a set of features, the model estimates the probability of spam, and the system puts the email into the "Inbox" or "Spam" folder.

Every email has certain characteristics, or features. For example:

  • \(x_1\) — how many times the word "free" occurs in the email;
  • \(x_2\) — whether the email contains a suspicious link;
  • \(x_3\) — whether the word "URGENT" is written in capitals;
  • \(x_4\) — how many recipients are listed in the email.

Based on these features you need to determine which category the email belongs to. In machine learning such categories are called classes.

In this case there are two classes:

  • class 0 — a normal email, not spam;
  • class 1 — spam.

Note that the numbers 0 and 1 here simply denote categories. Class 1 does not mean that the email is "better" or "bigger" than class 0.

Suppose an email has arrived:

Feature Value
The word "free" 3 times
Suspicious link Yes, that is, 1
The word "URGENT" Yes, that is, 1
Number of recipients 12

A human can look at these characteristics and guess that the email is suspicious. But if you need to process thousands of emails automatically, you need a model that does this according to certain rules learned from examples.

This is exactly where the classification task appears.

1.2. What classification is

Classification is a machine learning task in which the model determines the class of an object from its characteristics.

Examples:

Object What we determine Possible classes
Email Whether it is spam Spam / not spam
Loan application Whether it meets the given conditions Approve / reject
Photograph What is shown in it Cat / dog
Transaction Whether it is suspicious Suspicious / normal
User Whether they will open the email Will open / will not open

In each case the object has to be assigned to one of a predefined set of categories.

An important clarification: the model does not have to output the final category right away. It is often more useful to obtain the probability of each outcome of interest first.

For example, for an email the model might output:

  • the probability that it is spam — 0.92;
  • the probability that it is a normal email — 0.08.

The number 0.92 means an estimated probability of 92%. After that another part of the system can make the decision: send the email to the "Spam" folder or leave it in the inbox.

So two results need to be distinguished:

  1. The probability estimate: how likely the model considers a particular outcome.
  2. The predicted class: which category the model assigns the object to after applying the decision rule.

These are related but not identical things.

1.3. How classification differs from regression

The previous lecture studied linear regression. Let us recall its main task.

Regression is a task in which the model predicts a numerical quantity, usually a continuous one.

For example:

  • the price of an apartment — 8,500,000 rubles;
  • tomorrow's temperature — 24.5 °C;
  • delivery time — 37 minutes.

Here the result is a number whose magnitude has a direct meaning. In classification you need to determine a category: spam or not spam, approval or rejection.

But an interesting question arises: can linear regression be used for classification?

Technically you can build such a model and then apply a threshold to its output. However, for probabilistic classification this is usually not the best approach.

Let us look at why.

1.4. Why linear regression is not always suitable for predicting probability

Linear regression uses an expression of the form

\[ \hat y = w_1x_1+w_2x_2+\dots+w_nx_n+b. \]

If the formula looks familiar but not entirely clear yet, that is expected: it has been discussed before, and for now it is enough to recall its meaning.

  • \(x_1,\dots,x_n\) — the features of the object;
  • \(w_1,\dots,w_n\) — the weights, that is, the coefficients of the model;
  • \(b\) — the intercept, or bias;
  • \(\hat y\) — the prediction of the model.

The problem is that the result of such an expression can be any real number. A real number is a number on the ordinary number line: for example, \(-3\), \(0\), \(1.7\), \(25\).

Suppose the output of linear regression is used as the probability of spam. We get:

  • for the first email — 0.7;
  • for the second — 1.4;
  • for the third — \(-0.2\).

The first value can be interpreted as a probability of 70%. But the other two values create a problem:

  • a probability cannot be greater than 1;
  • a probability cannot be less than 0.

For an ordinary probability of an event the condition holds:

\[ 0\leq p\leq 1. \]

Here \(p\) denotes the probability of the event.

Consequently we need a model that can work with features, take their influence into account and at the same time output a meaningful probability estimate in the range from 0 to 1.

That is what logistic regression is used for.

1.5. What logistic regression is

Logistic regression is a machine learning model that, in a binary task, estimates the probability that an object belongs to one of two classes, using a linear combination of features and a special transformation function.

Let us examine the term "binary task". Binary classification is classification in which two classes are considered.

For example:

  • 1 — spam;
  • 0 — not spam.

A logistic regression model first computes a numerical score based on the features and then transforms it into a value from 0 to 1.

This value is used as an estimate of the probability of the positive class — in the example above, the "spam" class. Later we will look in detail at how this transformation is arranged and how the model learns to choose its coefficients.

1.6. The main idea of logistic regression

Imagine you need to estimate the probability of spam from several features of an email. The model has to perform three main operations:

  1. Take the features and their weights into account, obtaining a numerical score.
  2. Transform that score into a value from 0 to 1.
  3. Use the resulting probability to make a decision about the class, if such a decision is required.

For example:

Stage What happens
Features of the email Words, links, number of recipients
Linear combination Combine the features using weights
Sigmoid Transform the number into a value from 0 to 1
Probability estimate The model estimates the probability of spam, for example 92%
Decision about the class For example, assigning the email to spam

So far this is only a general scheme. The value 0.92 here is illustrative: it has not been computed for a specific email yet. The main sentence worth writing down in your notes:

Logistic regression uses the features of an object to estimate the probability that it belongs to a class, and then, if necessary, turns the probability into a decision about the class.


2. How logistic regression relates to linear regression

Before examining the sigmoid, we need to understand what happens before it. Here we rely on the material of Lecture 2, but we will repeat it only as much as necessary.

2.1. Features, weights and the intercept

Suppose we estimate the probability that an email is spam. Let us take two features for now:

  • \(x_1\) — the number of suspicious words;
  • \(x_2\) — the presence of a suspicious link: 1 if the link is there and 0 if it is not.

The model has to combine these features into a single numerical score. But features can influence the result differently. The presence of a suspicious link may matter more than one suspicious word.

For this, weights are used. A weight is a numerical coefficient that determines how the corresponding feature affects the result of the model.

Let us denote the weights as \(w_1\) and \(w_2\). For example:

  • \(w_1=0.4\);
  • \(w_2=1.2\).

In this example the weight of the link is greater than the weight of one suspicious word. But it is important to remember: real weights have to be learned by the model from the data. Here they are set by hand only for the sake of the example.

Besides the weights, the model has an intercept (bias). Let us denote it with the letter \(b\). It allows the result of the model to be shifted independently of the feature values.

2.2. A linear combination of features

A linear combination is an expression in which the features are multiplied by the corresponding coefficients, the results are added, and then the intercept is added if necessary.

The formula:

\[ z=w_1x_1+w_2x_2+\dots+w_nx_n+b \]

Let us go through all the notation.

Symbol Meaning
\(x_i\) The value of a particular feature
\(w_i\) The weight corresponding to that feature
\(n\) The number of features
\(b\) The intercept
\(z\) The result of the linear combination

The index \(i\) is the number of the feature. For example, \(x_1\) is the first feature and \(x_2\) the second. Here \(z\) is a new variable that has been given a name. It stores the result of the computation.

Why use \(z\) rather than \(p\), which denotes probability, straight away? Because at this stage the probability has not been obtained yet.

2.3. Computing on a concrete example

Suppose an email has the following features:

\[ x_1=2,\qquad x_2=1. \]

That is, the email contains two suspicious words and has a suspicious link. Let the parameters of the model be as follows for now:

\[ w_1=0.4,\qquad w_2=1.2,\qquad b=-1. \]

Let us substitute the values into the formula:

\[ z=w_1x_1+w_2x_2+b. \]

Step 1. Multiply the first feature by its weight:

\[ w_1x_1=0.4\cdot2=0.8. \]

Step 2. Multiply the second feature by its weight:

\[ w_2x_2=1.2\cdot1=1.2. \]

Step 3. Add the results and add \(b\):

\[ z=0.8+1.2-1=1. \]

We got \(z=1\).

What does this mean? Only that the linear combination for this email is equal to one. In itself this does not yet mean a probability of 100%, 1% or 50%.

This is exactly where the next task arises: how do we transform an arbitrary value \(z\) into a correct probability estimate? For that we need the sigmoid function.

2.4. What the notation \(w^\top x\) means

In the formulas of logistic regression, a more compact notation is often used instead of the long sum:

\[ z=w^\top x+b. \]

It is worth explaining the symbol \(\top\): it denotes transposition — an operation on a vector or a matrix. For our purpose it is enough to understand the following.

A vector is an ordered set of numbers. For example, the features of one email can be written like this:

\[ x= \begin{bmatrix} 2 \\ 1 \end{bmatrix}, \qquad w= \begin{bmatrix} 0.4 \\ 1.2 \end{bmatrix}. \]

The notation \(w^\top\) means that the weight vector is written as a row:

\[ w^\top= \begin{bmatrix} 0.4 & 1.2 \end{bmatrix}. \]

When this row is multiplied by the column of features, the corresponding numbers are multiplied and the results are added:

\[ w^\top x=0.4\cdot2+1.2\cdot1=2. \]

We add the intercept:

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

This is the same computation that was performed above. The notation has simply become shorter.

It is worth remembering: \(w^\top x\) is a compact way of writing the multiplication of every feature by the corresponding weight followed by the addition of the results. You can read more about this operation in the article on the dot product.


3. The sigmoid function

3.1. Why the sigmoid is needed

We obtained the number \(z=1\). But we need a probability, which must lie between 0 and 1. We need a function that takes an arbitrary real number and transforms it into a number from this range.

Such a function is called the sigmoid function. It is also called the logistic function.

It makes it possible to transform the result of a linear combination of features into a value that can be used to estimate the probability of the positive class.

3.2. The sigmoid formula

\[ \boxed{\sigma(z)=\frac{1}{1+e^{-z}}} \]

It reads like this: "sigma of \(z\) equals one divided by one plus \(e\) to the power of minus \(z\)." Let us go through the formula piece by piece.

  • \(\sigma\) — the Greek letter sigma. Here it is the notation of the function.
  • \(z\) — the number obtained after the linear combination of the features.
  • \(e\) — a mathematical constant approximately equal to \(2.71828\).
  • \(-z\) — the number \(z\) taken with the opposite sign.
  • \(e^{-z}\) — the number \(e\) raised to the power \(-z\).
  • The fraction bar means dividing the numerator by the denominator.

The sigmoid takes \(z\) as its input and returns \(\sigma(z)\) as its output.

3.3. What \(e\) is and why it appears

The number \(e\) is one of the fundamental mathematical constants. It plays an important role in exponential processes, logarithms and mathematical analysis.

To understand our task it is enough to know that it is a fixed positive number:

\[ e\approx2.71828. \]

The expression \(e^z\) is called the exponential of \(z\). For example:

\[ e^0=1. \]

Why? Any non-zero number raised to the power zero equals one. And if \(z=1\), then:

\[ e^1=e\approx2.71828. \]

If \(z=-1\), then:

\[ e^{-1}=\frac{1}{e}\approx0.3679. \]

A negative power means that the reciprocal is taken:

\[ a^{-1}=\frac{1}{a}. \]

Therefore:

\[ e^{-z}=\frac{1}{e^z}. \]

There is no need to study exponential functions in depth right now. It is only important to understand how to compute the expression in the sigmoid formula.

3.4. Computing the sigmoid at \(z=0\)

Let us start with the simplest case:

\[ \sigma(0)=\frac{1}{1+e^0}. \]

Since \(e^0=1\), we get:

\[ \sigma(0)=\frac{1}{1+1} =\frac12 =0.5. \]

Thus, at a zero value of \(z\) the sigmoid returns 0.5. If the output of the model is interpreted as the probability of the positive class, this corresponds to 50%.

3.5. Computing the sigmoid at \(z=1\)

Let us go back to the email from the example. We have already computed:

\[ z=1. \]

Now we apply the sigmoid:

\[ \sigma(1)=\frac{1}{1+e^{-1}}. \]

It is known that:

\[ e^{-1}\approx0.3679. \]

Substituting:

\[ \sigma(1)\approx \frac{1}{1+0.3679}. \]

First we add up the denominator:

\[ 1+0.3679=1.3679. \]

Now we divide:

\[ \sigma(1)\approx\frac{1}{1.3679} \approx0.7311. \]

We got approximately 0.7311, that is, 73.11%. Interpretation: with the given parameters the model estimates the probability that the email is spam at about 73%.

This does not yet mean that the email is necessarily spam. This is exactly a probability estimate, and the final decision depends on the classification threshold.

3.6. What happens at negative and positive values

Let us see how the sigmoid changes at different values of \(z\).

\(z\) Approximate value of \(\sigma(z)\)
\(-5\) 0.0067
\(-2\) 0.1192
\(-1\) 0.2689
\(0\) 0.5000
\(1\) 0.7311
\(2\) 0.8808
\(5\) 0.9933

3.7. How the sigmoid behaves

The horizontal axis is the value of \(z\), the vertical axis is the output of the sigmoid.

A plot of the sigmoid on the interval from minus 5 to 5: a smooth S-shaped curve, with the value 0.5 at the point 0, approaching 0 at negative values and 1 at positive values
The sigmoid on the interval from −5 to 5. The curve passes smoothly from values near 0 to values near 1. At the point z = 0 the function equals 0.5: for negative z the value is less than 0.5, for positive z greater. The curve never reaches exact zero or exact one for any finite z.

Three important properties are visible here. First: when \(z\) is negative, the sigmoid returns a value less than 0.5.

Second: when \(z=0\), the result is 0.5. Third: when \(z\) is positive, the result is greater than 0.5.

At very large negative values the result approaches zero. At very large positive values it approaches one. At the same time, for a finite value of \(z\) the sigmoid reaches neither exact zero nor exact one.

3.8. Why the result lies between 0 and 1

Let us look at the formula once more:

\[ \sigma(z)=\frac{1}{1+e^{-z}}. \]

The exponential is always positive:

\[ e^{-z}>0. \]

Consequently:

\[ 1+e^{-z}>1. \]

The numerator equals one, and the denominator is always greater than one. Therefore the fraction is positive but less than one:

\[ 0<\sigma(z)<1. \]

This is exactly the property that was required.

There is, however, an important caveat: the sigmoid guarantees the range from 0 to 1, but by itself it does not guarantee that the resulting number will be an exact or well-calibrated probability.

For the interpretation of the model's output as a probability to be useful, the model has to be trained properly on suitable data. Later we will look at how that happens.


4. How the model makes a prediction

Now let us combine the two elements that have already been studied:

  1. The linear combination of features.
  2. The sigmoid function.

4.1. The full prediction formula

\[ \boxed{\hat p=\sigma(w^\top x+b)} \]

It reads: "the predicted probability equals the sigmoid of the linear combination of the features." Let us decode the symbols.

Symbol Meaning
\(\hat p\) The probability of the positive class predicted by the model
\(\sigma\) The sigmoid function
\(w\) The weight vector of the model
\(x\) The feature vector of the object
\(w^\top x\) The sum of the products of the corresponding weights and features
\(b\) The intercept

The symbol \(\hat p\) contains the letter \(p\) with a "hat". This hat is the mathematical notation for an estimate or a prediction. It helps to distinguish the estimate of the model from the true but unknown probability.

In practical tasks the true probability for an individual email is usually unknown. What we have are the features and the observed label: whether the email was spam. The model learns to estimate the probability from this data.

4.2. The whole process on our example

There is an email with the features:

\[ x_1=2,\qquad x_2=1. \]

The parameters are given:

\[ w_1=0.4,\qquad w_2=1.2,\qquad b=-1. \]

Step 1. Compute the linear combination:

\[ z=0.4\cdot2+1.2\cdot1-1=1. \]

Step 2. Pass \(z=1\) into the sigmoid:

\[ \hat p=\sigma(1) =\frac{1}{1+e^{-1}}. \]

Step 3. Obtain:

\[ \hat p\approx0.7311. \]

Step 4. Interpret the result:

\[ \hat p\approx73.11\%. \]

With the given parameters the model estimates the probability that the email belongs to the "spam" class at approximately 73.11%. The whole process can be represented as one chain:

\[ x\longrightarrow w^\top x+b \longrightarrow \sigma(z) \longrightarrow\hat p. \]

First the model receives the features, then it computes the number \(z\), after which it transforms it into a probability estimate.

Four rectangles connected by arrows: coloured bands for the features of an object, a scheme with weights, a sigmoid plot and a probability scale
The path from features to probability. Four steps connected by arrows: the features of the object, the linear combination with the weights, the sigmoid and the probability estimate from 0 to 1. The last card shows the probability, which, if necessary, is compared with a threshold to obtain a decision about the class.

4.3. The true label \(y\) and the prediction \(\hat p\) are not the same thing

This is one of the most important distinctions in the whole lecture. Suppose the training data says that a particular email really was spam.

Then its true label is:

\[ y=1. \]

The letter \(y\) denotes the true class label (target, true label). And the model predicted for this email:

\[ \hat p=0.7311. \]

This is a probability estimate, not a label. Let us compare:

Notation Value What it means
\(y\) 1 In the data the email is marked as spam
\(\hat p\) 0.7311 The model estimates the probability of spam at about 73.11%

If the true label had been \(y=0\) while the model still output \(\hat p=0.7311\), it would be confidently leaning towards the wrong class. How large the error is we will learn to compute in the section on the loss function.

So:

  • \(y\) — what we know about the object from the training data;
  • \(\hat p\) — the probability the model predicts.

During training both values are used to assess the quality of the predictions and to adjust the parameters of the model.


5. From probability to class: the classification threshold

5.1. Why a threshold is needed

Suppose the model estimated the probability of spam at 73.11%. But the mail system has to perform a concrete action: assign the email to spam or leave it in the inbox.

For this, the classification threshold (decision threshold) is used. The threshold is a chosen probability value by which the decision about which class to predict is made.

Let us denote the threshold with the letter \(t\). With the standard threshold \(t=0.5\) the rule looks like this:

\[ \hat y= \begin{cases} 1, & \hat p\geq0.5, \\ 0, & \hat p<0.5. \end{cases} \]

Here \(\hat y\) is the predicted class label. Do not confuse it with \(\hat p\):

  • \(\hat p\) — a probability, for example 0.73;
  • \(\hat y\) — a decision, for example 1.

In this formula, if the predicted probability is not less than 0.5, class 1 is chosen. If it is less than 0.5, class 0 is chosen.

5.2. Applying the threshold to our email

We obtained:

\[ \hat p=0.7311. \]

We compare it with the threshold:

\[ 0.7311\geq0.5. \]

The inequality holds, therefore:

\[ \hat y=1. \]

The model assigns the email to the "spam" class.

But this decision is based on the chosen rule. It does not mean that the probability of 73% has turned into certainty or that the model cannot be wrong.

5.3. Why 0.5 is not a mandatory rule

The threshold 0.5 is common, but it does not have to be used in every task.

Let us look at how the decision for the same email changes with different thresholds. The model estimated the probability of spam at 73.11%.

Threshold \(t\) Comparison Decision of the model
0.3 0.7311 ≥ 0.3 class 1 — spam
0.5 0.7311 ≥ 0.5 class 1 — spam
0.8 0.7311 < 0.8 class 0 — not spam

With a threshold of 0.3 the email from the example will be assigned to spam. With a threshold of 0.8, on the contrary, it will not fall into that class.

Why does this happen? Because the threshold determines how high the probability estimate must be in order to decide on the positive class.

Three identical probability scales: the mark of the predicted probability sits in the same place on all three, while the dashed threshold line shifts left and right; when the threshold is to the left of the mark the decision is positive, when to the right it is negative
One probability — three different thresholds. The dot on the scale is the probability predicted by the model; it is the same in all three cases. The dashed line is the chosen threshold. If the threshold is to the left of the mark, the object is assigned to the positive class; if it is to the right, to the negative one. So the decision can be changed without retraining the model: it is enough to move the threshold.

5.4. What changes when different thresholds are chosen

A low threshold, for example 0.3, makes it possible to assign objects to the positive class more often.

This can be useful if it is important not to miss a suspicious email. But as a result, ordinary emails may also end up in spam more often.

A high threshold, for example 0.8, means that the model has to be more confident in order to make a positive decision. This can reduce the number of ordinary emails mistakenly sent to spam, but it increases the risk of missing genuine spam.

In tasks involving medical tests or fraud detection the consequences of the threshold choice can be even more significant. The specific threshold depends on the task, the cost of different errors and the requirements of the system. Which errors arise in that case is shown by the confusion matrix.

It is important not to confuse two actions:

  • Training the model — choosing the weights and the intercept.
  • Choosing the threshold — defining the rule by which a probability estimate turns into a class label.

These are different stages. Changing the threshold does not by itself change the weights of the model or recompute its probabilities.


6. Probability and odds

This is one of the most important sections. Here we will gradually approach the concept of logit, which explains why logistic regression is arranged the way it is.

6.1. The probability of an event

Let us start with a concept you already know. Probability is a numerical estimate of how likely some event is.

Let us denote it with the letter \(p\). For example, if the probability that an email is spam equals 0.8, this corresponds to 80%.

Probability lies between 0 and 1:

\[ 0\leq p\leq1. \]

If \(p=0.8\), the probability of the event is 80%, and the probability of the opposite event is:

\[ 1-p=1-0.8=0.2. \]

That is, the probability of not being spam in this example is 20%. Here two mutually exclusive outcomes are considered: the email is either spam or it is not.

6.2. What odds are

Odds are the ratio of the probability that an event will happen to the probability that it will not happen. This is not the same as probability.

The formula:

\[ \boxed{\operatorname{odds}=\frac{p}{1-p}} \]

Let us decode the notation:

  • \(p\) — the probability of the event we are interested in;
  • \(1-p\) — the probability of the opposite event;
  • the fraction bar — division;
  • \(\operatorname{odds}\) — the odds of the event.

Note that the numerator is the probability of the event itself, and the denominator is the probability that it will not happen.

6.3. Computing odds for several probabilities

Example 1. The probability equals 0.5. The event and the opposite outcome are equally likely:

\[ p=0.5,\qquad 1-p=0.5. \]

Then:

\[ \operatorname{odds}=\frac{0.5}{0.5}=1. \]

The odds are 1:1. For every one expected outcome of the event there is one expected outcome of the opposite event, in the sense of the ratio of probabilities.

Example 2. The probability equals 0.8.

\[ p=0.8,\qquad 1-p=0.2. \]

Consequently:

\[ \operatorname{odds}=\frac{0.8}{0.2}=4. \]

The odds are 4:1. The probability of the event is four times the probability of the opposite outcome. Example 3. The probability equals 0.2.

\[ p=0.2,\qquad 1-p=0.8. \]

We get:

\[ \operatorname{odds}=\frac{0.2}{0.8}=0.25. \]

This is a ratio of 1:4: the probability of the event is four times less than the probability of the opposite outcome. Let us collect the results in a table.

Probability \(p\) Probability \(1-p\) Odds \(p/(1-p)\) Ratio
0.2 0.8 0.25 1:4
0.5 0.5 1 1:1
0.8 0.2 4 4:1
0.9 0.1 9 9:1

Why is this useful? Probability shows the share of the expected event, while odds express the ratio of the event to its opposite.

At the same time, odds are not limited to one. They can be greater than 1 if the event is more likely than its opposite, and less than 1 if it is less likely.

6.4. What a logarithm is

Now we need one more concept — the logarithm.

If a power shows to what power the base has to be raised, then the logarithm answers the inverse question: to what power must the base be raised to obtain a given number?

For example:

\[ 2^3=8. \]

Consequently:

\[ \log_2(8)=3. \]

It reads: "the logarithm of 8 to base 2 equals 3". Why? Because 2 has to be raised to the third power to obtain 8.

In logistic regression the natural logarithm is especially important; it is denoted \(\ln\). Its base is the number \(e\), approximately equal to 2.71828.

For example:

\[ \ln(e)=1, \]

because \(e^1=e\). Another useful example:

\[ \ln(1)=0, \]

because \(e^0=1\).

At this stage it is enough to remember that the logarithm transforms numbers according to a certain mathematical rule. Later we will see why this is needed when working with odds.

6.5. What logit is — the logarithm of the odds

Logit is the natural logarithm of the odds of an event. The formula:

\[ \boxed{\operatorname{logit}(p)= \ln\left(\frac{p}{1-p}\right)} \]

Inside the logarithm are the odds:

\[ \frac{p}{1-p}. \]

And then the natural logarithm of this ratio is taken.

The concept of logits is related to this term — the raw outputs of the model, from which a probability distribution is then obtained.

Let us go through several examples. If \(p=0.5\):

\[ \operatorname{logit}(0.5) =\ln\left(\frac{0.5}{0.5}\right) =\ln(1)=0. \]

If \(p=0.8\):

\[ \operatorname{logit}(0.8) =\ln\left(\frac{0.8}{0.2}\right) =\ln(4) \approx1.3863. \]

If \(p=0.2\):

\[ \operatorname{logit}(0.2) =\ln\left(\frac{0.2}{0.8}\right) =\ln(0.25) \approx-1.3863. \]

Note the symmetry: the probabilities 0.8 and 0.2 give opposite logit values. This happens because their odds are the reciprocals of each other:

\[ \frac{0.8}{0.2}=4,\qquad \frac{0.2}{0.8}=\frac14. \]

The logarithm of a reciprocal number has the opposite sign.

6.6. Why logit can be any real number

Probability is limited to the range from 0 to 1. But logit can take any finite real value. Let us see why.

If \(p=0.5\), then logit equals 0. If \(p\) is greater than 0.5, the odds are greater than 1, so the natural logarithm of the odds is positive.

If \(p\) is less than 0.5, the odds are less than 1, so the logarithm of the odds is negative. When the probability approaches zero, the odds approach zero, and the logarithm of the odds goes to minus infinity.

When the probability approaches one, the odds grow without bound, and the logarithm of the odds goes to plus infinity. We get the following correspondence:

Probability \(p\) Logit
Close to 0 A large negative number
Equal to 0.5 0
Close to 1 A large positive number

So logit makes it possible to move from a bounded probability to a quantity that can vary along the whole number line.

Three vertical scales connected by horizontal dashed lines: a short probability scale, a longer odds scale and a log-odds scale running beyond the edges of the figure
Probability, odds and the logarithm of the odds. The same quantity on three scales: probability is limited to the interval from 0 to 1, odds grow from 0 to infinity, and the logarithm of the odds can take any real value. The dashed lines connect values that correspond to each other: for example, the probability 0.5 corresponds to a logit equal to zero.

Now we can write down the key equality:

\[ \boxed{\operatorname{logit}(p)=w^\top x+b} \]

This is one of the fundamental formulas of logistic regression. What does it mean?

The right-hand side is the linear combination of the features:

\[ w^\top x+b. \]

The left-hand side is the logarithm of the odds of the event:

\[ \ln\left(\frac{p}{1-p}\right). \]

Consequently, the model assumes that the logarithm of the odds of the positive class depends linearly on the features.

This is more precise than saying that the probability itself depends linearly on the features. The probability is obtained after the inverse transformation with the sigmoid.

From the equality we can obtain the formula we have already met:

\[ p=\sigma(w^\top x+b). \]

Logistic regression uses the linear combination of features to describe the logarithm of the odds, and the sigmoid transforms that combination into a probability.


7. How the model is trained

Until this point the values of the weights and the intercept were set by hand. In a real ML project the model has to find them from the data.

7.1. Where the weights come from

Suppose there are a thousand emails. For every email the features and the correct label are known:

  • 1 — spam;
  • 0 — not spam.

Such examples form the training dataset (training dataset). Our task is to find the values \(w_1,w_2,\dots,w_n\) and \(b\) at which the model predicts the labels of these emails well.

But what does "well" mean? For this, a loss function is introduced.

A loss function is a mathematical expression that assesses how unsuccessfully the model predicts the result for an object or a set of objects. More on loss functions in the article "Loss functions".

Usually we aim to minimise this function: the smaller the loss, the better the predictions according to the chosen criterion.

Important: small losses on the training data do not by themselves guarantee good performance on new emails — this is a question of generalization. Later we will discuss overfitting and the limitations of the model.

7.2. Why correct and incorrect predictions must be assessed differently

Suppose the true label of an email is 1 — it really is spam. Let us compare three options:

Predicted probability of spam What the model thinks Quality from the point of view of the label
0.99 Almost sure it is spam A good prediction
0.60 Leaning towards spam, but not very sure A less confident correct prediction
0.01 Almost sure it is not spam A confident incorrect prediction

If the model is trained on labelled data, the loss function must help to distinguish these situations. When the model confidently predicts the correct outcome, the loss must be small.

When the model confidently predicts the opposite outcome, the loss must be large.

Why is this important? Because training must not merely output numbers from 0 to 1. It must push the parameters of the model towards values that agree better with the observed labels.

7.3. What exactly changes during training

For every object the model computes:

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

and then:

\[ \hat p=\sigma(z). \]

After that the predicted probability \(\hat p\) is compared with the true label \(y\) using the loss function. If the loss is large, the model receives a signal that the current parameters do not explain the training data well enough.

Then the training algorithm changes the weights and the intercept in order to reduce the loss. As a result, training can be represented as a repeating cycle:

  1. Obtain the features of the object.
  2. Compute the probability.
  3. Assess the prediction error.
  4. Change the parameters of the model.
  5. Repeat the process.

One such pass over the data is called an epoch, and a single update of the parameters an iteration.

What remains is to choose a suitable loss function. Why is log-loss usually used for logistic regression rather than the mean squared error? The following sections are devoted to this.


8. Why MSE is not enough

8.1. A reminder: MSE

The lecture on linear regression studied the mean squared error — Mean Squared Error (MSE). It measures the average square of the difference between the true values and the predictions of the model.

For \(N\) objects:

\[ \operatorname{MSE} =\frac{1}{N}\sum_{i=1}^{N}(\hat y_i-y_i)^2. \]

Here:

  • \(N\) — the number of objects;
  • \(y_i\) — the true value for object \(i\);
  • \(\hat y_i\) — the prediction of the model for object \(i\);
  • \(\sum\) — the summation sign: we add up the errors of all objects;
  • the square makes every error non-negative and gives more weight to large deviations.

For example, if the true value is 1 and the prediction is 0.7, then the square of the error is:

\[ (0.7-1)^2=(-0.3)^2=0.09. \]

MSE can certainly be computed for predicted probabilities. Mathematically it is not forbidden for classification.

However, logistic regression usually uses a different loss function, one that is directly connected with the probabilistic model and the principle of maximum likelihood.

8.2. What the advantage of log-loss is

Suppose the true label is 1. The model predicts the probability of the positive class:

  • 0.9 — a fairly confident correct prediction;
  • 0.6 — a correct but less confident one;
  • 0.01 — a confident incorrect prediction.

MSE assesses the square of the difference between the probability and the label. Log-loss is arranged differently: it uses the logarithm of the probability of the outcome actually observed.

Thanks to this, log-loss punishes especially strongly those situations in which the model assigns a very small probability to the true outcome.

Two loss plots: on the left a decreasing curve with a large loss at a small predicted probability, on the right an increasing curve with a large loss near one; under the marked points there are bars whose height equals the loss
How the loss grows with a confident mistake. On the left the loss for an object with the true label 1: it is large when the model gives this class a small probability, and almost zero when the probability is close to one. On the right the loss for an object with the true label 0: it is large when the model confidently predicts one. The height of the bars under the marked points equals the loss in these examples.

This is an important property of probabilistic classification: it is not enough simply to guess the class. It is also useful to assess how well the predicted probabilities agree with the real outcomes.


9. Log-loss and binary cross-entropy

9.1. What log-loss means

Log-loss is short for logarithmic loss, that is, the logarithmic loss function. In binary classification it is often called binary cross-entropy (BCE).

In the standard formulation of binary logistic regression these names usually refer to one and the same loss function. First let us look at the formula for a single object:

\[ \boxed{ L(y,\hat p)=- \left[ y\ln(\hat p)+(1-y)\ln(1-\hat p) \right] } \]

At first glance the formula may seem complicated. But we will go through it piece by piece, and then we will see that for a concrete object it simplifies a great deal.

9.2. Decoding each symbol

  • \(L\) — loss, the error according to the chosen criterion.
  • \(y\) — the true label of the object: 0 or 1.
  • \(\hat p\) — the predicted probability of the positive class.
  • \(1-y\) — a number equal to 1 if \(y=0\) and to 0 if \(y=1\).
  • \(\ln(\hat p)\) — the natural logarithm of the probability of the positive class.
  • \(\ln(1-\hat p)\) — the natural logarithm of the probability of the negative class.
  • The minus in front of the brackets changes the sign of the result.

Why are there two terms in the formula? Because the true class can be either 1 or 0. Each term is responsible for one of the two outcomes.

9.3. Case one: the true label \(y=1\)

If the email really is spam, then:

\[ y=1. \]

We substitute one into the original formula:

\[ L=-\left[ 1\cdot\ln(\hat p) +(1-1)\ln(1-\hat p) \right]. \]

We compute \(1-1=0\):

\[ L=-\left[ \ln(\hat p)+0\cdot\ln(1-\hat p) \right]. \]

The second term equals zero. Therefore what remains is:

\[ \boxed{L=-\ln(\hat p)} \]

So, when the true label is 1, the loss depends on what probability the model assigned to the positive class. The higher \(\hat p\), the smaller the loss.

9.4. Case two: the true label \(y=0\)

Now suppose the email is not spam:

\[ y=0. \]

We substitute it into the original formula:

\[ L=-\left[ 0\cdot\ln(\hat p) +(1-0)\ln(1-\hat p) \right]. \]

Since \(1-0=1\), we get:

\[ L=-\left[ 0+\ln(1-\hat p) \right]. \]

Consequently:

\[ \boxed{L=-\ln(1-\hat p)} \]

In this case the loss depends on the probability of the negative class, which equals \(1-\hat p\). If the true class is 0, then a high probability of the positive class means a bad prediction.

9.5. Why there is a minus in front of the brackets

Recall that the natural logarithm of a number between 0 and 1 is negative. For example:

\[ \ln(0.5)\approx-0.6931. \]

And if we take the minus in front of the logarithm:

\[ -\ln(0.5)\approx0.6931. \]

We obtain a positive loss. In the general case, for a probability \(q\) lying between 0 and 1:

\[ -\ln(q)\geq0. \]

When \(q\) approaches 1, the value of \(-\ln(q)\) approaches zero. When \(q\) approaches zero, the value of \(-\ln(q)\) grows without bound.

This is exactly the behaviour we need: a correct outcome with a high predicted probability gives a small loss, while an outcome with a very small probability gives a huge one.

9.6. Computing log-loss for concrete numbers

Suppose the true label is 1. So the email really is spam. Let us compare three predictions.

Prediction 1: \(\hat p=0.9\)

The model estimated the probability of spam at 90%.

\[ L=-\ln(0.9)\approx0.1054 \]

A small loss: the model confidently predicted the correct class.

Prediction 2: \(\hat p=0.6\)

The model estimated the probability of spam at 60%.

\[ L=-\ln(0.6)\approx0.5108 \]

The loss is larger: the prediction is correct but less confident.

Prediction 3: \(\hat p=0.01\)

The model estimated the probability of spam at only 1%.

\[ L=-\ln(0.01)\approx4.6052 \]

A large loss: the model is almost sure of the wrong outcome. You can see that the loss at \(\hat p=0.01\) is considerably larger than at \(\hat p=0.6\) or \(\hat p=0.9\).

This allows training to react more strongly to confident incorrect predictions.

9.7. What if the true label is zero?

Now the true class is not spam:

\[ y=0. \]

For such an object we use the formula:

\[ L=-\ln(1-\hat p). \]

If the model predicted \(\hat p=0.1\), we get:

\[ L=-\ln(1-0.1) =-\ln(0.9) \approx0.1054. \]

This is a small loss: the model estimated the probability of spam at only 10%, and the email really is not spam. If, however, the model predicted \(\hat p=0.99\), then:

\[ L=-\ln(1-0.99) =-\ln(0.01) \approx4.6052. \]

The loss is huge: the model is almost sure that the email is spam, although the true label is 0.

9.8. How the loss is computed over the whole dataset

So far a single object has been considered. But the training set usually contains many objects. For \(N\) objects the average loss equals:

\[ \boxed{ J=-\frac{1}{N}\sum_{i=1}^{N} \left[ y_i\ln(\hat p_i) +(1-y_i)\ln(1-\hat p_i) \right] } \]

Here:

  • \(N\) — the number of training objects;
  • \(i\) — the number of the object;
  • \(y_i\) — the true label of object \(i\);
  • \(\hat p_i\) — the predicted probability of the positive class for object \(i\);
  • \(\sum\) — the summation of the losses of all objects;
  • \(\frac{1}{N}\) — dividing the sum by the number of objects, that is, computing the mean;
  • \(J\) — the average loss function that we want to minimise.

Note that the formula has a minus in front of the sum. It is necessary because the logarithms of probabilities are usually non-positive.

So the model makes predictions for all training objects, we compute their log-loss and average the losses.

Now a fundamental question arises: why does this particular loss function have this form, and how is it connected with the probabilistic model? The answer is given by the principle of maximum likelihood.


10. Maximum likelihood estimation

10.1. What likelihood is

Likelihood is a quantity that shows how well particular parameters of a probabilistic model explain data that has already been observed.

Here it is important to distinguish probability from likelihood. Suppose we toss a coin. Let \(\theta\) denote the probability of heads.

If \(\theta=0.5\), then for a fair coin the probability of heads is 0.5. But now imagine the coin has already been tossed 100 times and produced 80 heads.

We need to understand which value of \(\theta\) explains the observed result better: 0.5, 0.7, 0.8 or something else? For every possible value of \(\theta\) we can compute the likelihood of the observed data.

  • Probability answers the question: how likely is the result given the model?
  • Likelihood answers the question: how well do the given parameters of the model explain the result already observed?

The mathematical expression may be the same in both cases. The difference lies in what we treat as given and what we vary.

10.2. The idea of maximum likelihood

Maximum likelihood estimation (MLE) is estimation by the maximum likelihood method.

The essence of the method is simple: we choose the parameters of the model at which the observed data receives the maximum possible likelihood within the chosen model.

In logistic regression those parameters are the weights \(w\) and the intercept \(b\). For every object the model outputs a probability:

\[ \hat p_i=\sigma(w^\top x_i+b). \]

If the true label of an object is 1, the model must assign a sufficiently high probability to the positive class. If the true label is 0, the model must assign a sufficiently high probability to the negative class:

\[ 1-\hat p_i. \]

Thus the likelihood depends on what probabilities the model assigns to the labels actually observed.

10.3. The likelihood formula for one object

For binary classification the probability of the observed label can be written like this:

\[ P(y_i\mid x_i)= \hat p_i^{y_i}(1-\hat p_i)^{1-y_i}. \]

This may look unusual for now, so let us consider both possible cases. If \(y_i=1\), then:

\[ P(y_i\mid x_i) =\hat p_i^1(1-\hat p_i)^0 =\hat p_i. \]

That is, the probability of the observed class equals the probability of the positive class. If \(y_i=0\), then:

\[ P(y_i\mid x_i) =\hat p_i^0(1-\hat p_i)^1 =1-\hat p_i. \]

Now the expression returns the probability of the negative class. Why is this notation used? Because it makes it possible to combine both cases in a single formula.

Here \(P(y_i\mid x_i)\) means the probability of the label \(y_i\) given the known features \(x_i\), according to the model.

10.4. The likelihood of several objects

Let the training set contain \(N\) objects. Assume that the labels of the objects are independent of each other given the features and the parameters of the model.

This is the standard assumption for writing the likelihood in this formulation. Then the joint probability of the observed labels is expressed by the product:

\[ \boxed{ \mathcal L(w,b)= \prod_{i=1}^{N} \hat p_i^{y_i}(1-\hat p_i)^{1-y_i} } \]

The symbol \(\mathcal L\) denotes the likelihood function, and \(\prod\) is the product sign. It means that the expressions for all objects must be multiplied together.

Why are the probabilities multiplied? For independent events, the probability that each of several given outcomes occurs equals the product of the probabilities of those outcomes.

So the likelihood is large if the model assigns high probabilities to the labels we actually observed.

10.5. Why the logarithm of the likelihood is used

The likelihood contains a product of many probabilities. With a large number of objects such products can become very small numbers.

To simplify the computations, the natural logarithm of the likelihood is used:

\[ \ln\mathcal L(w,b). \]

The logarithm has an important property:

\[ \ln(a\cdot c)=\ln(a)+\ln(c). \]

That is, the logarithm of a product equals the sum of the logarithms. For example:

\[ \ln(0.5\cdot0.2) =\ln(0.1). \]

On the other hand:

\[ \ln(0.5)+\ln(0.2) =\ln(0.1). \]

Therefore the logarithm of the likelihood turns the product of probabilities into a sum:

\[ \ln\mathcal L(w,b) = \sum_{i=1}^{N} \left[ y_i\ln(\hat p_i) +(1-y_i)\ln(1-\hat p_i) \right]. \]

This formula resembles the log-loss formula we examined earlier. The difference lies in the sign.

10.6. Why MLE is equivalent to minimising log-loss

The logarithm is an increasing function. Therefore, if one positive number is greater than another, its logarithm will be greater too.

Consequently, maximising the likelihood is equivalent to maximising the logarithm of the likelihood. We want to maximise:

\[ \ln\mathcal L(w,b). \]

But when training logistic regression the problem is usually formulated as minimising the negative logarithm of the likelihood:

\[ -\ln\mathcal L(w,b). \]

Substituting the expression for the logarithm of the likelihood, we get:

\[ -\ln\mathcal L(w,b) = -\sum_{i=1}^{N} \left[ y_i\ln(\hat p_i) +(1-y_i)\ln(1-\hat p_i) \right]. \]

If this sum is divided by \(N\), the average log-loss is obtained:

\[ J(w,b)=-\frac1N\ln\mathcal L(w,b). \]

Dividing by the positive constant \(N\) does not change the parameters at which the minimum is reached.

Thus, maximising the likelihood and minimising the average log-loss lead to the same problem of choosing the parameters in the standard formulation of logistic regression.

This is not a coincidence. Log-loss arises naturally from the probabilistic model if we train it by maximum likelihood.


11. How the parameters are optimised

We have found that the training of logistic regression can be formulated as minimising the average log-loss.

Now let us recall how a function can be minimised in general — for this we will need optimization from Lectures 3–4.

11.1. What we want to minimise

Let us denote the average log-loss by \(J(w,b)\). The notation means that the value of the function depends on the weights \(w\) and the intercept \(b\).

Our task:

\[ \boxed{\min_{w,b}J(w,b)} \]

The symbol \(\min\) means that we are looking for the smallest value of the function by varying the parameters of the model. For example, with some weights the average log-loss may equal 0.9, with others 0.5, and with yet others 0.2.

In that case the third option is better according to the chosen criterion. The concrete values here are illustrative. In a real task the loss function is computed from the training data.

11.2. A reminder: what a gradient is

Gradient is a vector of partial derivatives of a function with respect to its parameters.

If a function depends on several parameters, for example on \(w_1,w_2\) and \(b\), then the gradient shows how the function changes when each parameter changes slightly.

For a loss function it contains information about the direction in which the loss changes when the weights and the intercept change.

Gradient descent uses this information to change the parameters in the direction of decreasing loss function.

11.3. Updating the parameters

The general idea of gradient descent:

\[ \boxed{\theta_{\text{new}} =\theta_{\text{old}}-\eta\nabla J(\theta)} \]

Let us decode the notation:

  • \(\theta\) — a parameter or a set of parameters of the model;
  • \(\theta_{\text{old}}\) — the current value of the parameter;
  • \(\theta_{\text{new}}\) — the new value after the update;
  • \(J\) — the loss function;
  • \(\nabla J\) — the gradient of the loss function;
  • \(\eta\) — learning rate.

The minus sign means that we move in the direction opposite to the gradient, since we want to reduce the loss function.

If the gradient is positive with respect to a particular parameter, then, all else being equal, we decrease that parameter. If the gradient is negative, we increase it.

The learning rate determines the step size. A step that is too large can prevent the loss from decreasing steadily, while a step that is too small can slow down training.

Variants of this method — stochastic gradient descent, mini-batch and Momentum — are examined in Lectures 3–4.

11.4. The gradient of log-loss for logistic regression

For one object the loss function has the form:

\[ L=-\left[y\ln(\hat p)+(1-y)\ln(1-\hat p)\right]. \]

The predicted probability depends on the linear combination:

\[ \hat p=\sigma(z),\qquad z=w^\top x+b. \]

If the loss function is differentiated with respect to the linear combination \(z\), we get:

\[ \boxed{\frac{\partial L}{\partial z}=\hat p-y} \]

Here \(\partial\) denotes a partial derivative, and \(\partial L/\partial z\) shows how the loss changes when \(z\) changes. Why does exactly \(\hat p-y\) come out? The derivation uses two facts:

\[ \frac{d\sigma(z)}{dz}=\sigma(z)(1-\sigma(z)) \]

and the rule for differentiating a logarithm. If the derivative of the sigmoid is substituted consistently into the derivative of log-loss and the expression is simplified, the factors \(\hat p(1-\hat p)\) cancel, leaving \(\hat p-y\).

Now, since:

\[ z=w^\top x+b, \]

we obtain the derivatives with respect to the parameters:

\[ \boxed{\frac{\partial L}{\partial w_j} =(\hat p-y)x_j} \]

and

\[ \boxed{\frac{\partial L}{\partial b}=\hat p-y}. \]

Here \(w_j\) is the weight of the feature \(x_j\).

These formulas show that the magnitude of the prediction error is connected with the change of every parameter, and the influence of a particular weight also depends on the value of the corresponding feature.

For a set of \(N\) objects the gradients of the average log-loss are averaged over all objects:

\[ \frac{\partial J}{\partial w_j} =\frac1N\sum_{i=1}^{N} (\hat p_i-y_i)x_{ij}, \]
\[ \frac{\partial J}{\partial b} =\frac1N\sum_{i=1}^{N}(\hat p_i-y_i). \]

Here \(x_{ij}\) is the value of feature \(j\) for object \(i\).

These are already concrete formulas that connect the predictions of the model with the updating of the parameters. We do not need to go through the whole optimisation course again: it is enough to understand that the gradient makes it possible to compute the direction in which the weights and the intercept should change, and then to take a step towards reducing the log-loss.


12. The geometric meaning of logistic regression

12.1. What a decision boundary is

A decision boundary is the boundary between the regions in which the model predicts different classes. Imagine that every object is described by two features:

  • \(x_1\) — the number of suspicious words;
  • \(x_2\) — the number of suspicious links.

Every email can be depicted as a point on a plane. The horizontal axis will be \(x_1\) and the vertical one \(x_2\). The model has to divide the feature space into regions where it predicts class 0 and class 1.

12.2. Why, with a threshold of 0.5, the boundary corresponds to \(z=0\)

We know that with the standard threshold 0.5 the positive class is predicted if:

\[ \hat p\geq0.5. \]

And the predicted probability equals:

\[ \hat p=\sigma(z). \]

The sigmoid takes the value 0.5 exactly at \(z=0\). Consequently the boundary between the class regions corresponds to the condition:

\[ z=0. \]

We substitute the expression for \(z\):

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

This is the equation of the decision boundary in standard binary logistic regression with a threshold of 0.5.

12.3. One feature

If we have only one feature, the equation of the boundary looks like this:

\[ w_1x_1+b=0. \]

If \(w_1\neq0\), the boundary can be expressed in terms of the feature:

\[ x_1=-\frac{b}{w_1}. \]

This is a single point on the number line. On different sides of it the model can predict different classes.

12.4. Two features

With two features the equation takes the form:

\[ w_1x_1+w_2x_2+b=0. \]

If \(w_2\neq0\), let us express \(x_2\):

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

This is the equation of a straight line.

Thus, in standard logistic regression with two original features the decision boundary is a straight line, provided the parameters define a non-degenerate boundary.

A plane with two clouds of differently coloured points separated by a diagonal line, and below it a number line with points of two classes and a vertical boundary in the middle
The decision boundary. On the feature plane the points of the two classes are separated by a straight line: on one side of it the model predicts class 0, on the other class 1, and on the line itself the probability equals 0.5. At the bottom the same idea is shown for one feature: the boundary turns into a point on the number line.

With a larger number of features the analogous boundary is called a hyperplane — a generalisation of a line or a plane to a space of higher dimensionality.

An important clarification: the linear boundary refers to the feature space in which the linear combination is applied. If the features are transformed beforehand, for example by adding non-linear combinations, the boundary in the original coordinates may look non-linear.

13. Interpreting the coefficients

In logistic regression the weights do not simply participate in computing a probability. They can be interpreted through the logarithm of the odds.

13.1. A positive coefficient

Recall:

\[ \operatorname{logit}(p)=w^\top x+b. \]

If the coefficient of a feature is positive, then when that feature increases by one unit and the other features stay the same, the log-odds of the positive class increases.

For example, if the weight of the feature "number of suspicious words" is positive, then a larger number of such words is associated with an increase in the predicted odds of spam.

This statement describes the model, not necessarily a cause-and-effect relationship in the real world.

13.2. A negative coefficient

If the coefficient is negative, then an increase in the corresponding feature decreases the log-odds of the positive class, all else being equal.

This means that the model associates an increase in this feature with a decrease in the predicted odds of the positive class.

13.3. Why a coefficient can be linked to the odds ratio

Suppose one feature increases by one unit while the others remain unchanged. The original log-odds:

\[ \operatorname{logit}(p)=w_jx_j+c, \]

where \(c\) combines the contribution of the other features and the intercept. After increasing \(x_j\) by one:

\[ \operatorname{logit}(p')=w_j(x_j+1)+c. \]

Expanding the brackets:

\[ \operatorname{logit}(p')=w_jx_j+w_j+c. \]

Subtracting the original expression:

\[ \operatorname{logit}(p')-\operatorname{logit}(p)=w_j. \]

Since the logit is the natural logarithm of the odds, we get:

\[ \ln(\operatorname{odds}')-\ln(\operatorname{odds})=w_j. \]

Using the property of logarithms:

\[ \ln\left(\frac{\operatorname{odds}'}{\operatorname{odds}}\right)=w_j. \]

Applying the exponential to both sides gives:

\[ \boxed{\frac{\operatorname{odds}'}{\operatorname{odds}}=e^{w_j}}. \]

This means that increasing the feature by one unit multiplies the odds of the positive class by \(e^{w_j}\), with the other features unchanged.

For example, if \(w_j=\ln(2)\), then \(e^{w_j}=2\). The odds double. But the probability does not necessarily double: it is related to the odds by a non-linear transformation.

13.4. Why the weights cannot simply be compared

Suppose a model has two features:

  • the user's age in years;
  • the number of suspicious words in an email.

If one coefficient is 0.2 and the other is 2, this does not automatically mean that the second feature is ten times more important.

The reason is the scale of the features. An increase in age by one unit means one year, while an increase in the number of words by one unit means one word. In addition, the ranges and distributions of the features can differ greatly.

That is why the absolute values of the coefficients, without taking the scale of the features into account, cannot be used as a universal measure of importance.

14. Regularization

14.1. Why a model needs to be limited

If a model has many parameters or the training data contains noise, the model can fit the particular training examples too closely.

This is called overfitting. With overfitting, the model can perform well on the training data but worse on new objects.

One way to reduce this risk is regularization.

14.2. The idea of regularization

Without regularization we minimize the average log-loss:

\[ J(w,b). \]

With regularization, a penalty for large weight values is added to the loss function. The general idea:

\[ J_{\text{reg}}(w,b)=J(w,b)+\lambda R(w). \]

Here:

  • \(J(w,b)\) — the original loss function;
  • \(R(w)\) — the regularization penalty;
  • \(\lambda\) — the coefficient that determines the strength of the penalty.

The larger \(\lambda\), the more strongly the penalty affects training.

In the standard formulation the penalty is usually applied to the weights, while the intercept is not penalized, although a particular implementation may have its own settings.

14.3. L2 regularization

With L2 regularization a penalty in the form of the sum of squared weights is used:

\[ R(w)=\sum_{j=1}^{n}w_j^2. \]

Then:

\[ J_{\text{reg}}=J+\lambda\sum_{j=1}^{n}w_j^2. \]

Weights that are large in absolute value increase the penalty. So the model has an incentive not to use excessively large coefficients without need.

14.4. L1 regularization

With L1 regularization the sum of the absolute values of the weights is used:

\[ R(w)=\sum_{j=1}^{n}\lvert w_j \rvert. \]

Accordingly:

\[ J_{\text{reg}}=J+\lambda\sum_{j=1}^{n}\lvert w_j \rvert. \]

L1 regularization can cause some coefficients to become exactly zero. This sometimes helps obtain a sparser model.

Both types of regularization change the training problem: we now strive not only to reduce the error on the data but also to take the complexity of the model's parameters into account.

Three bar charts: the weights without regularization, the same weights after L2 regularization with pale outlines of the original height, and the weights after L1 regularization where almost all the bars have become short
How regularization shrinks the weights. On the left the weights without a penalty. In the middle L2 regularization: all the coefficients have decreased, and the pale outlines show their original magnitude. On the right L1 regularization with a strong penalty: almost all the weights have become close to zero, and only a few remain non-zero.

However, excessive regularization is harmful too: if the penalty is too large, the model can turn out too simple and describe the patterns in the data poorly.

15. Multiclass classification

So far we have considered binary classification: two classes, for example "spam" and "not spam".

But real tasks may have more than two classes. For example, you may need to determine whether an email is advertising, work correspondence, a personal message or spam.

There are ways to extend logistic regression to such tasks.

15.1. One-vs-rest

One-vs-rest (OvR) is the "one against the rest" approach. If there are four classes, four binary classifiers can be trained:

  • the first distinguishes class 1 from all the others;
  • the second distinguishes class 2 from all the others;
  • the third distinguishes class 3 from all the others;
  • the fourth distinguishes class 4 from all the others.

Each model produces a probability estimate for its own class. The system then chooses the class with the highest estimate. In this approach each classifier solves a binary problem, although the overall task is multiclass.

A subtlety: independently trained OvR classifiers do not necessarily produce probabilities that sum to one. Their scores can be compared in order to choose a class, but they do not always form a consistent probability distribution over all the classes.

15.2. Softmax

Softmax is a function that transforms a set of numerical scores into a set of non-negative values whose sum is one.

For \(K\) classes, the formula for the probability of class \(k\):

\[ \boxed{p_k=\frac{e^{z_k}}{\sum_{j=1}^{K}e^{z_j}}} \]

Here:

  • \(K\) — the number of classes;
  • \(z_k\) — the model's score for class \(k\);
  • \(e^{z_k}\) — the exponential of the class score;
  • \(\sum_{j=1}^{K}e^{z_j}\) — the sum of the exponentials of the scores of all classes;
  • \(p_k\) — the result of softmax for class \(k\).

The denominator normalizes the values: each value becomes a share of the total. As a result:

\[ \sum_{k=1}^{K}p_k=1. \]

For example, if the model has to choose one of three classes, it may produce:

  • class A — 0.7;
  • class B — 0.2;
  • class C — 0.1.

The sum is one, that is, 100%.

Two diagrams: on the left four bars of different heights with class scores, on the right a single bar divided into parts of the same proportions
Several scores — one distribution. On the left four model scores for four classes: they are not bounded above and do not have to sum to one. On the right the same values after softmax: they have become shares of a single whole, that is, a probability distribution with a sum equal to one.

15.3. How sigmoid differs from softmax

Property Sigmoid Softmax
Typical scenario Binary classification Multiclass classification
Input A single number for a binary model A set of class scores
Output A value from 0 to 1 A set of values from 0 to 1
Sum of outputs Does not have to equal 1 if several independent sigmoid outputs are considered Equals 1
Interpretation The probability of the positive class in a binary model A probability distribution over the classes

In multiclass logistic regression with softmax, the model usually chooses the class with the highest probability.

This is an extension of the main topic. To understand binary logistic regression it is enough to know the sigmoid, the probability of the positive class and the classification threshold confidently.

16. Evaluating classification quality

A model can output probabilities, but we need to understand how well it classifies objects. For this, quality metrics are used.

16.1. The four basic outcomes of classification

First let us define four situations. Suppose class 1 means "spam".

  • True Positive (TP) — a true positive result: the email really is spam, and the model correctly predicted spam.
  • True Negative (TN) — a true negative result: the email is not spam, and the model correctly predicted that it is not spam.
  • False Positive (FP) — a false positive result: the email is not spam, but the model mistakenly classified it as spam.
  • False Negative (FN) — a false negative result: the email is spam, but the model did not recognize it.

These four values form the basis of the confusion matrix.

16.2. An example of a confusion matrix

Suppose the model processed 100 emails.

Actual class Predicted: spam Predicted: not spam
Actually spam TP = 30 FN = 10
Actually not spam FP = 5 TN = 55

The table shows:

  • 30 spam emails were recognized correctly;
  • 10 spam emails were missed;
  • 5 ordinary emails were mistakenly sent to spam;
  • 55 ordinary emails were recognized correctly.
A square made of four parts: a cloud of blue points in the top-left corner, a cloud of orange points in the top-right, a small cloud of orange points in the bottom-left, and the largest cloud of blue points in the bottom-right
The four outcomes of classification. Each quadrant is one of the situations: correctly found spam (TP), missed spam (FN), an ordinary email mistakenly classified as spam (FP), and a correctly recognized ordinary email (TN). The size of each cloud of points shows how many objects fell into the category: there are noticeably more correct decisions than errors.

Total objects:

\[ 30+10+5+55=100. \]

Now let us calculate the metrics.

16.3. Accuracy — the share of correct predictions

Accuracy is the share of objects for which the model predicted the correct class.

Formula:

\[ \boxed{\operatorname{Accuracy}=\frac{TP+TN}{TP+TN+FP+FN}} \]

Substituting the values:

\[ \operatorname{Accuracy}=\frac{30+55}{100}=\frac{85}{100}=0.85. \]

Accuracy equals 85%. That is, the model correctly classified 85 out of 100 emails.

16.4. Precision — the accuracy of positive predictions

Precision shows what share of the objects predicted as the positive class actually belong to that class.

Formula:

\[ \boxed{\operatorname{Precision}=\frac{TP}{TP+FP}} \]

Substituting:

\[ \operatorname{Precision}=\frac{30}{30+5}=\frac{30}{35}\approx0.857. \]

Precision is approximately 85.7%. This means that among the emails the model sent to spam, about 85.7% really were spam.

16.5. Recall

Recall shows what share of all real objects of the positive class the model managed to detect.

Formula:

\[ \boxed{\operatorname{Recall}=\frac{TP}{TP+FN}} \]

Substituting:

\[ \operatorname{Recall}=\frac{30}{30+10}=\frac{30}{40}=0.75. \]

Recall equals 75%. That is, the model detected 30 out of 40 emails that really were spam.

Two diagrams with overlapping circles: on the left the circle of predicted positive objects is outlined boldly, with points outside the overlap; on the right the circle of real positive objects is outlined boldly, with hollow points for the missed ones
What stands in the denominator of precision and recall. On the left the set of objects that the model predicted as positive is highlighted: it includes both the correctly found spam and the false alarms — this is the quantity that TP is compared with when computing precision. On the right the set of all objects that really were spam is highlighted, including the missed ones — this is what TP is compared with when computing recall.

16.6. Why accuracy is sometimes not enough

Imagine there are 1000 emails, of which only 10 are spam. A model that always predicts "not spam" will get:

\[ \operatorname{Accuracy}=\frac{990}{1000}=99\%. \]

Formally the value of the metric is high, but the model has not detected a single spam email.

So high accuracy does not always mean that the model is useful. You need to take the class distribution and the relative cost of different errors in the particular task into account.

Precision helps you understand how reliable positive predictions are. Recall shows how many real positive objects were detected.

These metrics are often used together, because an improvement in one is not always accompanied by an improvement in the other. For an overall score the F1 score is sometimes used, and the quality of ranking by predicted probabilities is characterized by ROC-AUC.

17. Assumptions and limitations of logistic regression

17.1. What the linearity of the model means

The main assumption of logistic regression is that the logarithm of the odds depends linearly on the features:

\[ \operatorname{logit}(p)=w^\top x+b. \]

This does not mean that the probability has to change along a straight line.

The probability itself is obtained through the sigmoid, so the dependence of the probability on the linear combination has an S-shape.

Two graphs connected by an arrow: on the left a straight line with three marked points, on the right an S-shaped curve with the same points
From logit space to probability. On the left the logarithm of the odds depends linearly on the feature: it is a straight line that goes up and down without bounds. On the right the same dependence, after the sigmoid, turns into an S-shaped curve that stays between 0 and 1. The marked points correspond to the same objects on both graphs.

17.2. What happens if the dependence is more complex

Imagine that the probability of spam rises sharply only when several particular features occur at the same time. A simple linear combination of the original features may not describe such a pattern well enough.

In some cases the representation of the data can be improved: add new features, interactions between features, or transformations of the original quantities.

For example, instead of two separate features you can introduce an additional feature equal to their product:

\[ x_3=x_1x_2. \]

After that the model remains linear in its parameters, but the dependence on the original features becomes more flexible.

This is an important distinction: being linear in the parameters does not mean that the model has to be linear in every original feature after any transformations.

17.3. Outliers

An outlier is an observation that differs greatly from the bulk of the data.

For example, if emails usually have from 1 to 10 recipients and one email has 100,000, that object may differ noticeably from the others.

Outliers can influence training, especially if they cause large changes in the linear combination or reflect a data error.

However, logistic regression does not necessarily handle every outlier badly. It all depends on how unusual the outlier is, which class it belongs to and how it affects the loss function.

17.4. Multicollinearity

Multicollinearity is a situation in which some features are strongly related to each other. For example, the data may contain both:

  • a person's age in years;
  • the number of months lived.

These features carry almost the same information.

In that case the model may have difficulty determining the individual coefficients: different combinations of weights can give similar predictions.

This does not necessarily mean that the quality of the predictions will be poor, but interpreting the coefficients separately can become harder.

17.5. Dependence on data quality

Logistic regression, like any model, depends on the training data.

If the labels are wrong, the features contain systematic errors, or the training set does not reflect future objects, quality can drop.

That is why it is useful to check:

  • the correctness of the labels;
  • missing values;
  • the ranges and scales of the features;
  • the balance between the classes;
  • the quality of the model on data that was not used to train it.

17.6. When logistic regression is a good choice

Logistic regression is often useful when:

  • you need to solve a binary classification problem;
  • a relatively simple and understandable model is required;
  • the interpretation of the coefficients matters;
  • you need to obtain class probability estimates;
  • the dependence is well described by a linear combination of the features or by a suitable transformation of them.

It can also serve as a baseline model — a starting point against which more complex methods are compared.

18. A complete example: from data to result

Now let us assemble the concepts we have studied into one small example. This time we will have three emails and one feature, so that all the calculations can be done by hand.

18.1. The training data

Suppose the feature \(x\) is the number of suspicious words in an email. The true label \(y\):

  • 1 — spam;
  • 0 — not spam.
Email Number of suspicious words \(x\) True label \(y\)
A 0 0
B 1 0
C 2 1

This is a very small and conventional dataset. It is needed to demonstrate the arithmetic, not to build a full spam filter.

18.2. Prediction with given parameters

Suppose at some stage we have the parameters:

\[ w=2,\qquad b=-2. \]

These are given model parameters. For now we do not claim that they are optimal. The linear combination for one feature:

\[ z=wx+b. \]

The probability:

\[ \hat p=\sigma(z)=\frac{1}{1+e^{-z}}. \]

Email A: \(x=0\). First:

\[ z=2\cdot0-2=-2. \]

Then:

\[ \hat p=\sigma(-2)\approx0.1192. \]

The model estimates the probability of spam at about 11.92%. Email B: \(x=1\).

First:

\[ z=2\cdot1-2=0. \]

Then:

\[ \hat p=\sigma(0)=0.5. \]

The model estimates the probability of spam at 50%. Email C: \(x=2\).

First:

\[ z=2\cdot2-2=2. \]

Then:

\[ \hat p=\sigma(2)\approx0.8808. \]

The model estimates the probability of spam at about 88.08%.

18.3. Applying the threshold

We use a threshold of 0.5: if \(\hat p\geq0.5\), we predict class 1.

Email True class Predicted probability of spam Predicted class
A 0 0.1192 0
B 0 0.5000 1
C 1 0.8808 1

Email A was classified correctly. Email C was classified correctly too. Email B was assigned to spam, although its true label is 0.

In this example the rule equates the probability 0.5 with the positive class, because we chose the condition \(\hat p\geq0.5\).

18.4. Calculating the log-loss

For email A the true label is 0:

\[ L_A=-\ln(1-\hat p_A). \]

Substituting:

\[ L_A=-\ln(1-0.1192)=-\ln(0.8808)\approx0.1269. \]

For email B the true label is also 0:

\[ L_B=-\ln(1-\hat p_B). \]

Substituting:

\[ L_B=-\ln(1-0.5)=-\ln(0.5)\approx0.6931. \]

For email C the true label is 1:

\[ L_C=-\ln(\hat p_C). \]

Substituting:

\[ L_C=-\ln(0.8808)\approx0.1269. \]

The average log-loss for the three objects:

\[ J=\frac{L_A+L_B+L_C}{3}. \]

Substituting the approximate values:

\[ J\approx\frac{0.1269+0.6931+0.1269}{3}. \]

Adding up:

\[ 0.1269+0.6931+0.1269=0.9469. \]

Dividing by three:

\[ \boxed{J\approx0.3156}. \]

This is the average loss for the chosen parameters on our small sample.

18.5. How training changes the result

Now imagine that the training algorithm tries other values of \(w\) and \(b\). For each new pair of parameters it recomputes the probabilities of all the emails and then calculates the average log-loss.

If the new parameters reduce the average log-loss, then by this criterion they describe the training data better. The algorithm keeps updating the parameters in an effort to find the minimum of the loss function.

But here it is important to distinguish two processes:

  • Prediction: the parameters are already set, and the model computes the probability for a new object.
  • Training: the parameters are changed on the basis of the training data in order to reduce the loss function.

These are not the same thing. During ordinary prediction the model does not have to be retrained on every email.

How the parameters are changed is described in more detail in the article on gradient descent.

19. Logistic regression and linear regression: a comparison

Both models use a linear combination of features, but they solve different problems.

Characteristic Linear regression Logistic regression
Typical task Predicting a numerical quantity Classification
Model output An arbitrary real number In a binary task, a probability from 0 to 1
Main formula \(\hat y=w^\top x+b\) \(\hat p=\sigma(w^\top x+b)\)
Transformation In the standard model there is no additional transformation function Sigmoid
Typical loss function MSE Log-loss / BCE
Interpretation A predicted numerical quantity An estimate of the class probability
Example Forecasting the price of an apartment Determining the probability of spam

Why is logistic regression called regression if it is used for classification?

The name is connected with the mathematical form of the model and its relationship to the linear model. But in typical machine-learning tasks it is used for classification.

The main difference: linear regression directly predicts a numerical value, while logistic regression in the binary formulation transforms a linear combination of features into an estimate of the class probability.

20. Logistic regression at an ML interview

Below are questions that will help you not only recall definitions but also learn to explain how the model works.

Basic level

Question 1. What is logistic regression?

Answer. It is a machine-learning model that, in a binary task, estimates the probability of the positive class. It computes a linear combination of the features and then applies the sigmoid function:

\[ \hat p=\sigma(w^\top x+b). \]

The resulting probability estimate can be used to choose a class by means of a threshold.

A typical mistake: saying that logistic regression directly outputs only the label 0 or 1. In fact its standard output is a probability, and the label is obtained after applying the classification rule.

Question 2. What is the sigmoid and why is it needed? Answer. The sigmoid is a function that transforms any finite real number into a value between 0 and 1:

\[ \sigma(z)=\frac{1}{1+e^{-z}}. \]

It allows transforming a linear combination of features into an estimate of the probability of the positive class.

A typical mistake: thinking that the sigmoid itself trains the model. It only transforms a value. The weights and the intercept are chosen during training.

Question 3. Why is logistic regression not the same as linear regression?

Answer. Both models can use a linear combination of features, but logistic regression applies the sigmoid to it and is usually trained with log-loss. Linear regression usually predicts a numerical quantity directly.

A typical mistake: saying that the models differ only in name or in the way they are interpreted. They differ in their output function and in the typical training task.

Question 4. What is the classification threshold?

Answer. It is the probability value by which the model chooses a class. For example, with a threshold of 0.5 a probability of at least 0.5 means a prediction of the positive class.

A typical mistake: thinking that the threshold must necessarily be 0.5. It is chosen with regard to the task and the consequences of errors.

Intermediate level

Question 5. What is log-loss and why is it used? Answer. Log-loss evaluates the probability that the model assigned to the true label. In binary classification:

\[ L=-[y\ln(\hat p)+(1-y)\ln(1-\hat p)]. \]

If \(y=1\), the loss equals \(-\ln(\hat p)\). If \(y=0\), the loss equals \(-\ln(1-\hat p)\).

The loss is small if the model assigns a high probability to the correct outcome, and very large if the model almost rules out the outcome that was actually observed.

A typical mistake: claiming that log-loss measures only the correctness of the predicted label. It also evaluates the probabilities themselves.

Question 6. How are maximum likelihood and log-loss related?

Answer. The maximum likelihood method chooses the parameters under which the observed labels are most probable according to the model. If you take the negative logarithm of the likelihood and average it over the objects, you get the standard average log-loss.

Therefore maximizing the likelihood is equivalent to minimizing the average log-loss.

A typical mistake: treating these two approaches as independent training methods. In standard logistic regression they are two ways of writing the same optimization problem.

Question 7. What does a logistic regression coefficient mean?

Answer. The coefficient shows how much the logarithm of the odds of the positive class changes when the corresponding feature increases by one unit, if the other features are unchanged.

The exponential of the coefficient, \(e^{w_j}\), shows by what factor the odds change with such an increase.

A typical mistake: saying that the coefficient directly shows a change in probability by a certain number of percentage points. The relationship between the coefficient and the probability is non-linear.

Question 8. What is regularization? Answer. Regularization adds a penalty to the loss function that limits large coefficient values. It can help reduce overfitting.

L1 regularization uses the sum of the absolute values of the weights, and L2 regularization the sum of their squares. A typical mistake: thinking that regularization always improves quality. Too strong a penalty can lead to underfitting.

Advanced level

Question 9. Why does the logit depend linearly on the features while the probability does not? Answer. The model sets a linear dependence for the logarithm of the odds:

\[ \operatorname{logit}(p)=w^\top x+b. \]

The probability is recovered with the sigmoid:

\[ p=\frac{1}{1+e^{-(w^\top x+b)}}. \]

The sigmoid is non-linear, so the probability does not change linearly with each feature.

A typical mistake: saying that logistic regression is a linear model in every sense. The linearity refers to the linear combination of features and the logit.

Question 10. Why is the decision boundary linear?

Answer. With a threshold of 0.5 the boundary corresponds to a probability of 0.5. The sigmoid takes that value at \(z=0\), therefore:

\[ w^\top x+b=0. \]

This is a linear equation in the original features, so the boundary is a straight line in two-dimensional space and a hyperplane in a higher-dimensional space.

A typical mistake: claiming that the boundary is always linear, even after a non-linear transformation of the features. In the original coordinates it may look non-linear.

Question 11. Why do confident mistakes get a large loss?

Answer. Log-loss uses the negative logarithm of the probability of the observed class. When that probability tends to zero, the negative logarithm grows without bound.

So predicting a probability of 0.001 for an event that actually happened is penalized far more heavily than predicting a probability of 0.4.

A typical mistake: thinking that all incorrect predictions have the same cost. Log-loss takes the model's degree of confidence into account.

Question 12. Why can high accuracy be insufficient?

Answer. With a strong class imbalance the model can classify most objects correctly simply by always choosing the majority class. At the same time it may miss the rare class completely.

That is why you need to look at the confusion matrix, precision and recall, and also at other metrics depending on the task.

A typical mistake: evaluating a classifier by a single metric without taking the class ratio and the cost of different errors into account.

21. Practice tasks

First try to solve the tasks on your own. They are arranged from simple to more difficult. The solutions are given separately below.

Tasks for independent work

Try to do the calculations on paper first. You can tick off the tasks you have completed.

1. Linear combination

Given: \(x_1 = 2\), \(x_2 = 1\), \(w_1 = 0.5\), \(w_2 = 1\), \(b = -0.5\). Compute \(z = w_1x_1 + w_2x_2 + b\).

2. Sigmoid

Compute \(\sigma(0)\). Then explain why the result comes out exactly like that.

3. Probability

The model predicted \(\hat p = 0.82\) for the class "spam". What probability does it assign to the opposite class in a binary model?

4. Classification threshold

The model predicted \(\hat p = 0.42\). Which class will it choose with a threshold of 0.5? And with a threshold of 0.3?

5. Log-loss

True label \(y = 1\), predicted probability \(\hat p = 0.8\). Compute \(L = -\ln(\hat p)\). Use \(\ln(0.8) \approx -0.2231\).

6. Accuracy

The model correctly classified 72 objects out of 90. Compute the accuracy.

7. Coefficient

The weight of a feature equals \(\ln(3)\). By what factor will the odds of the positive class change when the feature increases by one unit, if the other features are unchanged?

8. A combined task

A model has \(w = 1\), \(b = -1\) and one feature \(x = 2\). Compute \(z\), the probability through the sigmoid, the class at a threshold of 0.5 and the log-loss if the true label is \(y = 0\).

Show detailed solutions

1. Substitute the values into the linear combination: \(z = w_1x_1 + w_2x_2 + b = 0.5 \cdot 2 + 1 \cdot 1 + (-0.5) = 1 + 1 - 0.5 = 1.5\).

2. \(\sigma(0) = \frac{1}{1 + e^{0}} = \frac{1}{1 + 1} = 0.5\). At \(z = 0\) the exponential equals one (\(e^{0} = 1\)), so the denominator equals two and the result is one half.

3. In a binary model the probabilities of the two classes complement each other up to one: \(1 - 0.82 = 0.18\).

4. With a threshold of 0.5 the condition \(\hat p \geq 0.5\) does not hold, because \(0.42 < 0.5\), so class 0 is chosen. With a threshold of 0.3 the condition \(\hat p \geq 0.3\) holds, because \(0.42 \geq 0.3\), so class 1 is chosen.

5. The loss for the true label \(y = 1\) equals \(L = -\ln(\hat p) = -\ln(0.8) \approx 0.2231\).

6. \(\operatorname{Accuracy} = \frac{72}{90} = 0.8\), that is, 80%.

7. The odds are multiplied by \(e^{w_j}\). Here \(w_j = \ln(3)\), therefore \(e^{w_j} = e^{\ln(3)} = 3\): the odds of the positive class increase threefold.

8. Linear combination: \(z = wx + b = 1 \cdot 2 - 1 = 1\). Probability: \(\hat p = \sigma(1) = \frac{1}{1 + e^{-1}} \approx 0.7311\). With a threshold of 0.5 the condition \(\hat p \geq 0.5\) holds, so class 1 is predicted. With the true label \(y = 0\) the loss equals \(L = -\ln(1 - \hat p) = -\ln(0.2689) \approx 1.3133\).

22. Typical mistakes and misconceptions

Misconception How to reason correctly
"Logistic regression is ordinary linear regression under a different name" It uses a linear combination, but applies the sigmoid and is usually trained with log-loss.
"The sigmoid trains the model itself" The sigmoid only transforms a number. The parameters are chosen by the training algorithm.
"A probability above 0.5 means the object definitely belongs to the class" It is the model's estimate, not a guarantee. The model can be wrong.
"The threshold of 0.5 cannot be changed" The threshold is chosen depending on the task, the metrics and the cost of errors.
"The larger the coefficient, the more important the feature in any situation" You need to take the scale of the feature, the other features and the way importance is measured into account.
"Accuracy is enough for any classifier" With class imbalance accuracy can be misleading.
"Logistic regression cannot overfit" It can overfit, especially with a large number of features and limited data. Regularization helps control that risk.
"Maximum likelihood and minimizing log-loss are unrelated" In the standard formulation they are equivalent ways of stating the training problem.
"The sigmoid guarantees well-calibrated probabilities" It guarantees the output range, but the quality of the probability estimates depends on the data, the model and the training.
"The decision boundary is always linear in the original data" It is linear in the feature space of the standard model. After feature transformations the boundary in the original coordinates may look non-linear.

23. The final map of the topic

23.1. The whole of logistic regression in one chain

  1. Features of an object

    \[ x_1, x_2, \dots, x_n \]
  2. Linear combination

    \[ z = w^\top x + b \]
  3. Sigmoid

    \[ \sigma(z) = \frac{1}{1 + e^{-z}} \]
  4. Probability

    \[ \hat p = \sigma(z) \]
  5. Classification threshold

    For example, \(0.5\)

  6. Predicted class

    \(\hat y = 0\) or \(\hat y = 1\)

  7. Loss function

    We compare the probability with the true label \(y\)

  8. Training the parameters

    We minimize the log-loss by changing the weights and the intercept

23.2. Where odds, logit and maximum likelihood sit in this chain

  • Odds: the ratio of the probability of an event to the probability of the opposite event:

    \[ \operatorname{odds}=\frac{p}{1-p}. \]
  • Logit: the natural logarithm of the odds:

    \[ \operatorname{logit}(p)=\ln\left(\frac{p}{1-p}\right). \]
  • The relationship of the logit to the features:

    \[ \operatorname{logit}(p)=w^\top x+b. \]
  • Log-loss: measures how well the predicted probability matches the true label.

  • Maximum likelihood: justifies the choice of log-loss as the training function in the standard probabilistic formulation.

  • Gradient descent: changes the weights and the intercept in order to reduce the loss function.

23.3. A short summary for revision

  1. Logistic regression is usually used for classification.
  2. First the model computes a linear combination of the features: \(z=w^\top x+b\).
  3. The sigmoid transforms it into a value from 0 to 1.
  4. The output of the model, \(\hat p\), is an estimate of the probability of the positive class.
  5. The threshold turns the probability estimate into a predicted class label.
  6. The odds of an event equal \(p/(1-p)\).
  7. The logit is the logarithm of the odds, which in logistic regression depends linearly on the features.
  8. Log-loss penalizes the model for a low probability of the true class, especially when the model is confident in the opposite outcome.
  9. Minimizing the average log-loss is equivalent to maximizing the likelihood in the standard formulation.
  10. Gradient descent tunes the weights and the intercept.
  11. Regularization adds a penalty for large coefficients and can reduce the risk of overfitting.
  12. The quality of a classifier must be evaluated with suitable metrics, not only with accuracy.

23.4. The main formulas

Purpose Formula
Linear combination \(z=w^\top x+b\)
Sigmoid \(\sigma(z)=1/(1+e^{-z})\)
Predicted probability \(\hat p=\sigma(w^\top x+b)\)
Odds \(\operatorname{odds}=p/(1-p)\)
Logarithm of the odds \(\operatorname{logit}(p)=\ln(p/(1-p))\)
Relationship of logit and features \(\operatorname{logit}(p)=w^\top x+b\)
Log-loss for an object \(L=-[y\ln\hat p+(1-y)\ln(1-\hat p)]\)
Average log-loss \(J=\frac{1}{N}\sum_{i=1}^{N}L_i\)
Decision boundary at a threshold of 0.5 \(w^\top x+b=0\)
Parameter update \(\theta_{\text{new}}=\theta_{\text{old}}-\eta\nabla J\)
L1 regularization \(R(w)=\sum_j\lvert w_j \rvert\)
L2 regularization \(R(w)=\sum_jw_j^2\)
Accuracy \((TP+TN)/(TP+TN+FP+FN)\)
Precision \(TP/(TP+FP)\)
Recall \(TP/(TP+FN)\)

23.5. Glossary of terms

Term Simple explanation
Classification Assigning an object to a class
Binary classification Classification with two classes
Feature A characteristic of an object
Weight The coefficient of a feature
Bias / intercept The free term of the linear combination
Sigmoid A function that maps a number to the interval from 0 to 1
Probability A number from 0 to 1 showing how likely an event is
Odds The ratio of the probability of an event to the probability of the opposite event
Logit The logarithm of the odds
Threshold The probability value used to choose a class
Decision boundary The line or surface separating the regions of different classes
Loss function A measure of how bad the model's predictions are
Log-loss The logarithmic loss function
Binary cross-entropy Another name for the same loss in binary classification
Likelihood How probable the observed data is under given parameters
Maximum likelihood estimation Choosing the parameters that make the observed data most probable
Gradient The vector of partial derivatives used to update the parameters
Learning rate The step size of the parameter update
Regularization A penalty for large coefficients
Overfitting Fitting the training data so closely that quality on new data drops
Multicollinearity Strong mutual dependence of the features
Accuracy The share of correct predictions
Precision The share of correct answers among positive predictions
Recall The share of real positive objects that were detected
Confusion matrix A table of the four classification outcomes
Softmax A function that turns scores into a probability distribution over the classes
One-vs-rest The "one class against the rest" approach

23.6. What you should be able to explain at an interview

It is useful to be able to answer the following questions in your own words:

  • How does classification differ from regression?
  • Why is a linear combination of features not a probability by itself?
  • How does the sigmoid work, and why is its output between 0 and 1?
  • How does the true label \(y\) differ from the predicted probability \(\hat p\)?
  • What are odds, and how do they differ from probability?
  • What does the logit mean, and why does it depend linearly on the features?
  • Why does log-loss punish confident wrong predictions?
  • How are maximum likelihood and minimizing log-loss related?
  • How does gradient descent train logistic regression?
  • Why can the coefficients not be interpreted as a direct change in probability?
  • What is regularization and why is it needed?
  • Why is accuracy sometimes insufficient for evaluating the quality of a classifier?

23.7. What to review first

If the material still seems large, you do not need to try to memorize all the formulas at once. It is recommended to review them in the following order:

  1. The basis of the model: \(z=w^\top x+b\), then the sigmoid and the probability.
  2. Decision making: the classification threshold, the difference between a probability and a label.
  3. The probabilistic part: odds and logit.
  4. Training: the loss function, log-loss, maximum likelihood.
  5. The practical part: the decision boundary, coefficients, regularization and quality metrics.

The main thing is not to memorize the formulas mechanically but to understand what problem each of them solves and how they are connected.

Logistic regression seems complicated because it brings together linear algebra, the exponential, logarithms, probabilities and optimization. But now we have a single scheme in which every element plays its own role.

If you cannot yet reproduce all the derivations on your own, that is expected: that is exactly what a sequential course is for — first understand the general idea, then learn to work through simple examples, and then explain the mathematical details confidently.

Practice in the interactive lab

Three actions for this lecture: look at the data, change the representation, explain the result.

  1. Look at the data — open "Threshold" and move the slider: the probabilities of the objects do not change, but the decisions do.

  2. Change the representation — in the same place, switch the dataset from separable to overlapping and see what happens to the confusion matrix and the metrics.

  3. Explain the result — open "Logistic loss" and compare the log-loss surface with the MSE surface on the same data.

Check yourself