AI voor Iedereen

Search

Search chapters and demos

๐Ÿ“ˆ Regression

๐Ÿ“ Linear regression

๐Ÿ”ฎ Predicting numbers

Suppose you are looking for a student room (a kot, as students in Leuven call it) and you want to know roughly what rent to expect. You have collected the rent and the floor area of a number of rooms. In the chart below, every point is one room: the x-axis shows the floor area (in mยฒ) and the y-axis the monthly rent (in euros).

Loading demo

Intuitively, you sense that larger rooms are more expensive. But can you make this pattern more precise? Roughly what would a room of 16 mยฒ cost you? And how much more do you typically pay per extra square meter?

This is exactly what linear regression is for: finding a trend line that fits your data points as well as possible, so that you can predict a price for new rooms.

Regression Definition

Regression is a form of supervised learning in which you predict a continuous value (a number) from the features of a data point.

In classification you choose a label from a fixed list (such as "spam" or "not spam"). In regression you predict a number on a continuous scale, such as a price, a temperature, an age or a sales figure.

Linear regression is one of the oldest and most widely used techniques in statistics and machine learning. The idea is simple: you have a number of data points (for example floor area and price) and you draw a straight line through them that fits all those points as well as possible. The technique is simple, easy to interpret and works for a surprising number of practical problems.

๐Ÿงต A trend line through the data

The points do not lie exactly on one line. Some rooms are more expensive or cheaper than you would expect from their size, for example because of the location, the condition of the building or just chance. The goal of linear regression is to find the "best" straight trend line that describes the pattern behind that variation. With that trend line you can then predict a price for a room of which you only know the floor area.

Try it yourself. In the "Adjust the line" panel you can move two sliders: one for the slope of the line (how steep it is) and one for the intercept (where it crosses the y-axis). Move the line until it runs through the middle of the cloud of points as well as possible. The stars and the color of the line show how close you are to the best possible line: behind the scenes, the demo compares the error of your line with that of the optimal line.

Loading demo

Then click Optimal fit to see which line the computer picks as the best. But how exactly does the computer calculate that line? To understand that, we first have to agree on how to express a straight line in numbers.

โœ๏ธ The equation of a straight line

In math, we usually write a straight line as:

y=mx+by = mx + b

In this equation, mm is the slope: how much yy rises when xx increases by 1. The number bb is the y-intercept: the value of yy when x=0x = 0.

Visualization of y = mx + b, in which b (red) shows the y-intercept and m (orange) illustrates the slope as the ratio of rise to run
The slope mm determines how steep the line is (for every step of +1 in the x direction, y rises by mm), while the intercept bb indicates where the line crosses the y-axis.

Concretely, in the student room example:

  • ๐Ÿ  xx is the floor area in mยฒ
  • ๐Ÿ’ถ yy is the predicted rent in euros
  • โ†—๏ธ mm tells you how many euros you pay per extra square meter
  • ๐Ÿ“ bb is a kind of "base price" (although a room of 0 mยฒ is of course not realistic)

Suppose the best line turns out to be y=12x+430y = 12x + 430. Then every extra square meter costs โ‚ฌ12 more per month on average, and the "base rent" (the intercept, for an imaginary room of 0 mยฒ) is โ‚ฌ430. For a room of 25 mยฒ you then predict:

y=12โ‹…25+430=300+430=730y = 12 \cdot 25 + 430 = 300 + 430 = 730

According to the same line, a room of 30 mยฒ costs 5 times โ‚ฌ12 more, so โ‚ฌ790.

Now try to find such a line yourself for a different dataset. Below you see, for a number of Belgian cities, the driving distance from Leuven and the driving time by car. What does the slope tell you here: how many minutes does every extra kilometer cost?

Loading demo

๐Ÿ‹๏ธ Weights

In machine learning we often use a slightly different notation. Instead of mm and bb, we talk about weights, written as w0,w1w_0, w_1, and so on. The equation of the straight line then becomes:

y=w1โ‹…x+w0y = w_1 \cdot x + w_0

Where:

  • ๐ŸŽš๏ธ w1w_1 is the weight that indicates how strongly the feature xx influences the prediction (this is the slope mm)
  • ๐ŸŽš๏ธ w0w_0 is the bias (this is the intercept bb)
Weight Definition

A weight in machine learning is a numeric value that determines how strongly a particular feature contributes to the final prediction. A larger (absolute) weight means that the feature counts more heavily in the prediction. The learning process of many AI algorithms consists of finding the optimal weights.

๐Ÿ”ข Multiple features

So far we used only one feature (the floor area), but you can extend this principle to many more features. What if you know not only the floor area, but also the distance to the city center and whether the room has a private bathroom? Then you give every feature its own weight and add everything up:

Linear regression with multiple features Rule
y=w0+w1โ‹…x1+w2โ‹…x2+โ€ฆ+wnโ‹…xny = w_0 + w_1 \cdot x_1 + w_2 \cdot x_2 + \ldots + w_n \cdot x_n

The predicted value yy is a weighted sum of all the features x1,x2,โ€ฆ,xnx_1, x_2, \ldots, x_n, each with its own weight w1,w2,โ€ฆ,wnw_1, w_2, \ldots, w_n, plus a bias w0w_0.

Suppose that after learning, the model finds the following weights:

price=400+12โ‹…areaโˆ’5โ‹…distance+50โ‹…bathroom\text{price} = 400 + 12 \cdot \text{area} - 5 \cdot \text{distance} + 50 \cdot \text{bathroom}

This tells you:

  • ๐Ÿ“ Every extra mยฒ raises the price by โ‚ฌ12
  • ๐Ÿšถ Every extra kilometer from the center of Leuven lowers the price by โ‚ฌ5 (a negative weight!)
  • ๐Ÿ› A private bathroom (bathroom = 1, otherwise 0) adds โ‚ฌ50 to the price

To predict the price of a specific room, you simply fill in the features and add everything up. For a room of 20 mยฒ, 1.5 km from the center, without a private bathroom:

price=400+12โ‹…20โˆ’5โ‹…1.5+50โ‹…0=400+240โˆ’7.5+0=632.5\text{price} = 400 + 12 \cdot 20 - 5 \cdot 1.5 + 50 \cdot 0 = 400 + 240 - 7.5 + 0 = 632.5

From the weights you can read right away which features the model considers important and in which direction they work. That readability is one of the great strengths of linear regression.

๐Ÿ“‰ The loss function

But how does the algorithm know which line is the "best"? For that you need a way to measure how well (or badly) a line fits the data.

For every data point you look at the difference between the true value and what the line predicts. That difference is called the residual of that point, or simply the error. In the demo below you see those errors as orange dashed lines between each point and the regression line. Hover over a point with your mouse to see its error; below the stars you also find the mean error of all the points together.

Loading demo

If you simply added up all the errors, positive and negative errors would cancel each other out. A point that is predicted โ‚ฌ100 too high and a point that is predicted โ‚ฌ100 too low together give an error of 0, while you are actually โ‚ฌ200 off! Moreover, you want to penalize big misses extra heavily.

That is why we use the squared error: you take the square of every error. That has two advantages:

  1. โž• All errors become positive, because squaring makes negative numbers positive.
  2. โš–๏ธ Large errors count more heavily than small ones. One error of โ‚ฌ100 gives a square of 10,000, while two errors of โ‚ฌ50 together only give 2ร—2,500=5,0002 \times 2{,}500 = 5{,}000.
Mean squared error Definition

The mean squared error (MSE) is the average of the squared errors over all data points. In plain language: for every point you square how far off your prediction is, and you take the average of that. The lower the MSE, the better the line fits the data.

As a formula, the mean squared error is written as:

MSE=1nโˆ‘i=1n(yiโˆ’y^i)2=1n[(y1โˆ’y^1)2+(y2โˆ’y^2)2+โ€ฆ+(ynโˆ’y^n)2]\begin{align*} \text{MSE} &= \frac{1}{n} \sum_{i=1}^{n} (y_i - \hat{y}_i)^2 \\ &= \frac{1}{n} \left[(y_1 - \hat{y}_1)^2 + (y_2 - \hat{y}_2)^2 + \ldots + (y_n - \hat{y}_n)^2\right] \end{align*}

Where:

  • ๐Ÿ“Š nn is the number of data points
  • ๐ŸŽฏ yiy_i is the true value of data point ii
  • ๐Ÿ”ฎ y^i\hat{y}_i is the value predicted by the model (the "hat" on the yy stands for "predicted")

The sum โˆ‘\sum simply adds up the squared error of every data point, and 1n\frac{1}{n} divides by the number of points to get the average.

So the goal of linear regression is: find the weights w0,w1,โ€ฆ,wnw_0, w_1, \ldots, w_n for which the mean squared error is as small as possible. Such a measure of "how badly is the model doing" is called a loss function. Almost every model you will get to know in the next chapters is trained by making a loss function as small as possible.

In the demo below you can choose a dataset and edit the data right away: editing mode is on from the start. The best line is already in place for you. Drag a data point to a spot where it deviates strongly from the rest (an outlier): the line immediately shifts toward it. That is because you minimize the square of the error: as a result, a single outlier weighs extremely heavily in the MSE.

Loading demo

๐Ÿ”๏ธ Gradient descent

So how does the computer find the line with the smallest error? For simple linear regression there is a formula that calculates the optimal weights directly. With many features that formula still exists, but it becomes expensive to compute, and for more complicated models such as neural networks there is none. Then AI systems use an optimization algorithm: a procedure that adjusts the weights until the error is as small as possible. The best-known one is gradient descent.

The idea is simple: start with random weights and adjust them step by step in the direction that makes the error smaller. You already did this yourself in the demos above: you moved a slider a little, checked whether the error got smaller, and kept moving in that direction.

Below, the algorithm does this for you on the student room prices. The model starts completely blank (slope and intercept both 0, so every room costs โ‚ฌ0) and the error is huge. Click Next step or let it play with โ–ถ๏ธ, and watch how the line moves toward the cloud of points while the error in the chart next to it drops step by step.

Loading demo

Every step works the same way:

  1. ๐Ÿ“Š Calculate the current error (the MSE) with the current weights.
  2. ๐Ÿ“‰ For every weight, determine in which direction the error decreases: "if I increase this weight a little, does the error get larger or smaller?"
  3. ๐Ÿ”ง Adjust every weight by a small step in the direction that lowers the error.
  4. ๐Ÿ” Repeat until the error no longer drops noticeably.

The direction in which the error rises fastest is called the gradient. You always step the other way, and that is why the technique is called gradient descent.

The size of that step is set by the learning rate. Try out the three settings in the demo. With a small learning rate, the line crawls painfully slowly toward the data and you need more than a hundred steps. With a large learning rate, the line overshoots the target every time and swings back and forth around the best line before it settles down. The trick is to choose a learning rate that is large enough to make progress, but small enough not to overshoot the target.

๐Ÿ—บ๏ธ The error landscape

You can think of gradient descent as a blindfolded walk through a hilly landscape. That landscape is not literal: every position stands for a combination of weights (w0,w1,โ€ฆw_0, w_1, \ldots), and the height at that position is the error (MSE) you get with those weights. The goal is to find the lowest point, because that is where the error is smallest.

Gradient descent: a ball rolls step by step to the minimum of a valley, with every small step reducing the error
Gradient descent finds the minimum by taking small steps in the direction that reduces the error. The ball starts high up on the left of the landscape and gradually rolls down to the valley where the error is smallest.

Blindfolded, you cannot see the valley, but you can feel how the ground slopes (the gradient, which points uphill), and you keep taking a small step the other way, downhill. That way you end up in the valley automatically: those are the best weights for your model. In linear regression the error landscape is always a smooth bowl with a single valley, so with a learning rate that is not too large you are guaranteed to reach the lowest point. In more complex models such as neural networks, the landscape often has several valleys, and you can get stuck in a valley that is not the lowest one.

This step-by-step adjusting is how most machine learning algorithms "learn": they start with a guess, measure how large the error is, and keep adjusting the weights a little.

๐Ÿ“ˆ Logistic regression

๐Ÿท๏ธ From numbers to label probabilities

Linear regression works well for predicting continuous values, such as prices, temperatures or scores. But what if you want to make a yes/no decision in a similar way, and also want to know how sure the model is?

Such a yes/no question is a binary classification problem: the outcome is one of two possible categories, as we already saw with naive Bayes, nearest neighbors and decision trees. Can we adapt the linear regression model for that?

The model then no longer has to predict an arbitrary number, but a number between 0 and 1 that you can read as a probability. With a threshold, for example 0.5, you turn that probability into a label: above the threshold you predict "yes", below it "no". We already chose such a threshold with naive Bayes, where you saw that the choice of the threshold determines what kind of errors you make.

๐Ÿงฌ The sigmoid function

A first attempt: simply use the straight line of linear regression, with label 0 for "no" and 1 for "yes". If the prediction is closer to 1, you say "yes"; closer to 0 means "no".

But that goes wrong. A straight line keeps rising or falling without limit, so the prediction soon becomes smaller than 0 or larger than 1. A probability of 130% or of โˆ’20% means nothing. You need something that always keeps the outcome neatly between 0 and 1.

The solution is an extra step at the end. You first calculate the weighted sum w0+w1x1+w2x2+โ€ฆw_0 + w_1 x_1 + w_2 x_2 + \ldots as in linear regression, and then send that result through a function that "squashes" everything between 0 and 1. That function is called the sigmoid function (also the logistic function, hence the name "logistic regression"). It looks like a stretched-out S.

Sigmoid function: maps every real number to a value between 0 and 1
The sigmoid function turns every number into a value between 0 and 1.

The sigmoid function has exactly the properties you are looking for:

  • ๐Ÿ”ป If the weighted sum is very negative, the output is almost 0.
  • ๐Ÿ”บ If the weighted sum is very positive, the output is almost 1.
  • ๐ŸŽฏ If the weighted sum is exactly 0, the output is 0.5: maximum uncertainty.
  • ๐ŸŒŠ The transition between the two extremes is gradual and smooth: the familiar "S-curve".

This model is called logistic regression. So despite the name "regression", you mainly use it for classification!

Logistic regression Definition

Logistic regression is a classification algorithm that predicts the probability that a data point belongs to a particular class. It first calculates a weighted sum of the features, just like linear regression, and then squashes it with the sigmoid function into a probability between 0 and 1:

P(yes)=ฯƒ(w0+w1x1+โ€ฆ+wnxn)P(\text{yes}) = \sigma(w_0 + w_1 x_1 + \ldots + w_n x_n)

๐ŸŒŠ The sigmoid formula

Mathematically, the sigmoid function is defined as:

ฯƒ(z)=11+eโˆ’z\sigma(z) = \frac{1}{1 + e^{-z}}

Here zz is the input: the weighted sum w0+w1x1+โ€ฆ+wnxnw_0 + w_1 x_1 + \ldots + w_n x_n.

The number ee is a mathematical constant, approximately equal to 2.718: the base of the natural logarithm. The notation eโˆ’ze^{-z} is a power with a negative exponent, in other words 1ez\frac{1}{e^z}: so e0=1e^{0} = 1 and eโˆ’2=1e2โ‰ˆ0.14e^{-2} = \frac{1}{e^2} \approx 0.14.

Look at what happens:

  • If zz is very large (positive), eโˆ’ze^{-z} becomes almost 0 and the fraction is roughly 1/(1+0)=11 / (1 + 0) = 1.
  • If zz is very negative, eโˆ’ze^{-z} becomes huge and the fraction goes to 0.
  • If zz is exactly 0, then e0=1e^{0} = 1 and the fraction is 1/(1+1)=0.51 / (1 + 1) = 0.5: the tipping point.

Written out in full, logistic regression thus predicts:

P(y=1โˆฃx)=ฯƒ(w0+w1x1+โ€ฆ+wnxn)=11+eโˆ’(w0+w1x1+โ€ฆ+wnxn)P(y = 1 \mid \mathbf{x}) = \sigma(w_0 + w_1 x_1 + \ldots + w_n x_n) = \frac{1}{1 + e^{-(w_0 + w_1 x_1 + \ldots + w_n x_n)}}

๐Ÿšง Fitting the decision boundary

Let's start with one feature. Suppose you want to predict whether a student passes the final exam, based only on the number of hours that student studied.

In the chart below you see students as points on a line: on the left those who studied little, on the right those who studied a lot. The color shows the result: green for passed, red for failed. The brighter the green or red, the surer the model is of passing or failing.

Adjust the weight w1w_1 (for study time) and the bias w0w_0 so that the decision boundary separates the two groups as well as possible.

Loading demo

The color bar follows the sigmoid curve: a smooth transition from "probably failed" (probability below 0.5) to "probably passed" (probability above 0.5). With one feature, the decision boundary is simply one point on the x-axis: there the probability is exactly 50%. To the left of it you predict "failed", to the right "passed". The weight w1w_1 determines how steep the transition is, and together with the bias w0w_0 also where the tipping point lies.

โœ‚๏ธ Two features: a 2D decision boundary

Of course, passing does not depend on study time alone. In the demo below you know two features of every student: the score out of 20 on a mock exam (which does not count toward the real exam) and the number of hours of study for the final exam. Every student is now a point in a plane, and the decision boundary becomes a straight line through that plane.

Set the weights for both features and the bias so that this line separates the two classes as well as possible.

Loading demo

After training, the model finds a positive weight for both features: both a higher mock exam score and more studying increase the probability of passing. For a strong student (high mock exam score, many hours of study), that gives for example a probability of about 87% of passing, for a weaker student only about 5%.

๐Ÿ”ข Calculating the probability: step by step

After training, the model finds roughly these weights (the same as with Optimal fit in the demo above):

  • w0=โˆ’7.54w_0 = -7.54 (bias)
  • w1=0.306w_1 = 0.306 (weight for the mock exam)
  • w2=0.205w_2 = 0.205 (weight for study time)

Student A: Mock exam = 14/20, Study time = 25 hours

Step 1: Calculate the linear score (zz):

z=โˆ’7.54+0.306โ‹…14+0.205โ‹…25=โˆ’7.54+4.28+5.13=1.87z = -7.54 + 0.306 \cdot 14 + 0.205 \cdot 25 = -7.54 + 4.28 + 5.13 = 1.87

Step 2: Apply the sigmoid function:

P(pass)=11+eโˆ’1.87=11+0.15โ‰ˆ0.87=87%P(\text{pass}) = \frac{1}{1 + e^{-1.87}} = \frac{1}{1 + 0.15} \approx 0.87 = 87\%

Student B: Mock exam = 8/20, Study time = 10 hours

z=โˆ’7.54+0.306โ‹…8+0.205โ‹…10=โˆ’7.54+2.45+2.05=โˆ’3.04z = -7.54 + 0.306 \cdot 8 + 0.205 \cdot 10 = -7.54 + 2.45 + 2.05 = -3.04P(pass)=11+e3.04=11+20.9โ‰ˆ0.05=5%P(\text{pass}) = \frac{1}{1 + e^{3.04}} = \frac{1}{1 + 20.9} \approx 0.05 = 5\%

The negative bias (w0=โˆ’7.54w_0 = -7.54) makes sure that the probability only rises noticeably once you have enough hours of study and/or points.

๐ŸŽฏ Working out a test point

Below, click the "Test point" tab at the top and see for yourself how the calculation and the sigmoid curve change when you adjust the mock exam score and the study time of the test point.

You can also switch to the larger "Loan application" example to see how logistic regression assesses a loan application.

Loading demo

โš™๏ธ How does the model learn its weights?

Above, you set the weights yourself, with the Optimal fit button as a cheat sheet. The computer does it just as in linear regression: with gradient descent on a loss function. But here the mean squared error is not a good choice. What you mainly want to penalize in a classification model is a prediction that is confident and wrong, for example a 99% probability of passing for a student who fails. For that there is a separate loss function, the binary cross-entropy (also called log loss), which penalizes such a confident miss much more heavily than a borderline case. How exactly it works is explained in the in-depth section below. For what follows, it is enough to know that here too the model makes its loss function as small as possible, step by step.

๐ŸŒ€ Binary cross-entropy

Can't you simply use the MSE for logistic regression? Technically you can, but it does not work well. Probabilities and labels both lie between 0 and 1, so even a huge blunder (a 99% probability of passing for a student who fails) gets an error of at most about 1 with the squared error: the penalty stops growing, however confident the model is. That is why we use a loss function that is built for this: the binary cross-entropy.

Binary cross-entropy Definition

The binary cross-entropy measures how well the predicted probabilities match the actual yes/no labels. In plain language: it rewards predictions that are confident and correct with a low error, and punishes predictions that are confident but wrong with a very high error. The lower the binary cross-entropy, the better the model.

As a formula, the binary cross-entropy is written as:

Binaryย cross-entropy=โˆ’1nโˆ‘i=1n[yilogโก2(y^i)+(1โˆ’yi)logโก2(1โˆ’y^i)]=โˆ’1n[y1logโก2(y^1)+(1โˆ’y1)logโก2(1โˆ’y^1)+โ€ฆ+ynlogโก2(y^n)+(1โˆ’yn)logโก2(1โˆ’y^n)]\begin{align*} \text{Binary cross-entropy} &= -\frac{1}{n} \sum_{i=1}^{n} \left[ y_i \log_2(\hat{y}_i) + (1 - y_i) \log_2(1 - \hat{y}_i) \right] \\ &= -\frac{1}{n} \left[ y_1 \log_2(\hat{y}_1) + (1 - y_1) \log_2(1 - \hat{y}_1) + \ldots + y_n \log_2(\hat{y}_n) + (1 - y_n) \log_2(1 - \hat{y}_n) \right] \end{align*}

Where:

  • ๐ŸŽฏ yiy_i is the true label (0 or 1)
  • ๐Ÿ”ฎ y^i\hat{y}_i is the predicted probability (between 0 and 1)
  • ๐Ÿ“‰ The logarithm makes sure that confident wrong predictions are punished heavily

The formula contains two terms: yโ‹…logโก2(y^)y \cdot \log_2(\hat{y}) and (1โˆ’y)โ‹…logโก2(1โˆ’y^)(1-y) \cdot \log_2(1-\hat{y}). Depending on the true label (y=0y=0 or y=1y=1), one of the two always drops out, because the factor yy or (1โˆ’y)(1-y) is then equal to 0. That way a single formula neatly handles both classes.

๐Ÿงพ The calculation step by step

Let's make this concrete with three students. For each of them the model predicts the probability of passing, and you know the actual result:

StudentTrue label (yy)Predicted probability (y^\hat{y})Correct?Error
Anna1 (passed)0.9โœ… Correct, confidentlow (0.15)
Bert1 (passed)0.3โŒ Wrong, and fairly confidenthigh (1.74)
Clara0 (failed)0.2โœ… Correct, fairly confidentlow (0.32)

For each student one term drops out, and the other one gives that student's contribution:

Anna (y=1y=1, y^=0.9\hat{y}=0.9):

โˆ’[1โ‹…logโก2(0.9)+0โ‹…logโก2(0.1)]=โˆ’logโก2(0.9)โ‰ˆ0.15-[1 \cdot \log_2(0.9) + 0 \cdot \log_2(0.1)] = -\log_2(0.9) \approx 0.15

Low error: the model was confident and correct.

Bert (y=1y=1, y^=0.3\hat{y}=0.3):

โˆ’[1โ‹…logโก2(0.3)+0โ‹…logโก2(0.7)]=โˆ’logโก2(0.3)โ‰ˆ1.74-[1 \cdot \log_2(0.3) + 0 \cdot \log_2(0.7)] = -\log_2(0.3) \approx 1.74

High error: the model thought Bert would fail, but he passed.

Clara (y=0y=0, y^=0.2\hat{y}=0.2):

โˆ’[0โ‹…logโก2(0.2)+1โ‹…logโก2(0.8)]=โˆ’logโก2(0.8)โ‰ˆ0.32-[0 \cdot \log_2(0.2) + 1 \cdot \log_2(0.8)] = -\log_2(0.8) \approx 0.32

Low error: the model was fairly confident and correct.

The average binary cross-entropy over all the students is:

Binaryย cross-entropy=0.15+1.74+0.323โ‰ˆ0.74\text{Binary cross-entropy} = \frac{0.15 + 1.74 + 0.32}{3} \approx 0.74

Look how Bert's confident wrong prediction pushes the total error up considerably. Had the model been even more confidently wrong about Bert (for example y^=0.1\hat{y}=0.1 instead of 0.30.3), his contribution would have been โˆ’logโก2(0.1)โ‰ˆ3.32-\log_2(0.1) \approx 3.32: almost double. That is exactly the behavior you want: the more confidently the model is wrong, the stronger the signal to correct it.

Adjust the predicted probabilities yourself below and see how the binary cross-entropy changes. What happens when Bert's predicted probability drops to 0.1?

Loading demo

๐Ÿ“‰ Why the MSE falls short here

Besides the overly mild penalty, there is a second, more technical problem. If you combine the sigmoid function with the MSE, the error landscape becomes very flat at the extremes. If the model gives a wrong answer with great confidence, the gradient there is almost zero: the model hardly "feels" any urge to improve, even though it is completely wrong. With the binary cross-entropy the gradient stays large in exactly that case, so gradient descent takes a big step precisely then. Moreover, the error landscape of the binary cross-entropy is again a smooth bowl with a single valley, while that of the sigmoid with the MSE can have several valleys.

๐ŸŽฏ Lowest error is not always highest accuracy

The weights with the lowest binary cross-entropy do not always give the highest accuracy. That seems contradictory, but it follows from how the binary cross-entropy works: it punishes the model not only for wrong predictions, but also for uncertain correct predictions. If the model correctly classifies a student as "passed" with 55% confidence, it still gets a higher error than with 95% confidence.

As a result, the model sometimes mainly tries to make existing correct predictions more confident, instead of correcting borderline cases around the threshold. Imagine:

  • ๐ŸŽ“ Student A actually passed. The model goes from a 90% to a 99% probability (more correct and more confident).
  • ๐Ÿ“‰ Student B actually failed. The model goes from a 49% to a 51% probability (now just wrong, because it is over the threshold).

The accuracy then drops from 2/2 to 1/2, while the average cross-entropy can still go down.

In practice you usually still minimize the binary cross-entropy, because:

  1. ๐ŸŒŠ It is a smooth function that works well with gradient descent.
  2. ๐ŸŽฏ Confidence in predictions is often valuable too.
  3. ๐Ÿ“Š On large datasets the difference is usually small.

So "lowest error" and "highest accuracy" do not always coincide!

๐Ÿ—‚๏ธ Multiple classes

What if we have more than two categories? For example: what type of document is this (invoice, contract, letter or form)?

Logistic regression can be extended to multinomial logistic regression (also called softmax regression). Instead of calculating a single probability, you calculate a probability for every possible class. Together, those probabilities add up to 1.

P(classย k)=ezkโˆ‘j=1Kezj=ezkez1+ez2+โ€ฆ+ezK\begin{align*} P(\text{class } k) &= \frac{e^{z_k}}{\sum_{j=1}^{K} e^{z_j}} \\ &= \frac{e^{z_k}}{e^{z_1} + e^{z_2} + \ldots + e^{z_K}} \end{align*}

Where:

  • ๐Ÿ“Š zkz_k is the linear score for class kk
  • ๐Ÿ”ข KK is the total number of classes

This is called the softmax function: it normalizes the scores so that they form valid probabilities. You then choose the class with the highest probability as the prediction.

ใ€ฝ๏ธ From straight line to curve

If the data follows a curved pattern, you can still keep using linear regression by adding polynomial features. Besides xx, you also give the model x2x^2 (and possibly x3x^3, x4x^4, ...) as an extra feature, each with its own weight:

y=w0+w1โ‹…x+w2โ‹…x2y = w_0 + w_1 \cdot x + w_2 \cdot x^2

With that one extra term, the line can already bend into an arc. This is called polynomial regression, and the highest power you add is called the degree of the model.

Try it below. The points follow a wavy pattern (the gray dashed line) with some noise on top. The degree starts at 1: that is the ordinary straight line, and it cannot follow the wave. Turn the degree up and watch the curve fit the points better and better.

Loading demo

If you turn the degree all the way up (10 or more), the curve goes through almost every training point, but between the points it swings wildly up and down. The open circles are new points that the model did not get to see during training, and the wild curve lies far from them. A degree that is too low is too stiff to capture the pattern: that is called underfitting. A degree that is too high also learns every bit of random noise in the training data: that is called overfitting. You can recognize both by the message next to the chart.

So the degree is a dial for the complexity of your model, and you look for the middle ground between too simple and too complex. How you find it, by measuring on data the model has not seen yet, is explained under overfitting and underfitting in the chapter on model evaluation.

The same trick works for logistic regression: if you also give the model x2x^2 and x3x^3, the decision boundary no longer has to be a straight line and can follow curves and waves (and become too wild there as well).

๐Ÿ“ Why this is still linear regression

The curve is bent, but the model stays linear in the weights: yy is still a weighted sum of features, only those features are now xx, x2x^2, x3x^3, ... You calculate those powers beforehand as extra columns in your dataset, and then the same method as in ordinary linear regression finds the weights. With nn data points, a polynomial of degree nโˆ’1n-1 can even go exactly through all the training points: the training error is then 0, but the model has then memorized the data instead of learning the pattern.

๐Ÿ›ก๏ธ Strengths and limitations

๐Ÿ’ช Strengths

Linear and logistic regression are strong mainly for the following reasons:

  • โšก Fast and efficient: Both training and making predictions (simply calculating a weighted sum) are very fast, even with millions of data points and thousands of features.

  • ๐Ÿ” Interpretable: You can see exactly which features matter by looking at the weights. A weight of +10 for "income" and โˆ’5 for "debt" tells you right away what the model "thinks".

  • ๐Ÿ“Š Works well with little data: Because of the simplicity of the model, there is less risk of overfitting on small datasets.

  • ๐Ÿงฎ Mathematically well understood: There is an extensive theory around linear models, including statistical tests and confidence intervals.

  • ๐Ÿ› ๏ธ Good baseline: Often the first model to try. If more complex models do not perform significantly better, simplicity is preferable!

๐Ÿšจ Limitations

Both techniques also have clear weaknesses:

  • ๐Ÿ“ Linear assumption: The model can only learn straight-line relationships. If the true relationship is a curve or a more complex pattern, the model misses it, unless you add polynomial features yourself.

  • ๐Ÿ”— No interactions: Standard linear regression does not capture interactions between features, because every feature counts separately in the weighted sum. If the effect of "education" on "salary" depends on "work experience", you have to add this by hand.

  • ๐Ÿ“‰ Sensitive to outliers: Outliers can strongly influence the regression line, as you saw earlier in the demo: the squared error gives them a lot of weight.

  • ๐ŸŽฏ Decision boundary is always linear: In logistic regression, the boundary between classes is always a straight line (or plane). For a curved boundary you have to add extra features yourself (as in polynomial regression) or choose another algorithm.

๐Ÿช› When to use them?

Linear regression is suitable for:

  • ๐Ÿ  Price prediction (houses, products, services)
  • ๐Ÿ“ˆ Trend analysis and forecasting
  • ๐Ÿ”ฌ Scientific research where interpretability matters
  • ๐Ÿ“Š As a baseline to compare more complex models with

Logistic regression is suitable for:

  • ๐Ÿ“ง Binary classification (spam/not spam, buy/not buy)
  • ๐Ÿฅ Risk assessment in medical applications
  • ๐Ÿ’ณ Credit scoring and fraud detection
  • ๐ŸŽฒ When you want probabilities as well as labels

Less suitable for:

  • ๐Ÿ–ผ๏ธ Complex patterns such as image recognition
  • ๐Ÿ”„ Strongly non-linear relationships
  • ๐Ÿงฉ Data with complex interactions between features

๐Ÿ•น๏ธ Demos

๐Ÿ—ฃ๏ธ Feedback

Just like machine learning algorithms, we also love learning from your feedback to improve the course.

Let us know how informative and how difficult you found this chapter, and where it could be better.

How informative did you find this chapter?
Was the difficulty of this chapter right for your level of knowledge and skill? This chapter was...
Anonymous with random ID