Lesson 2 · Linear Regression
⏱ 21 min read
Linear regression is the simplest machine learning model and the best way to see how everything fits together: from data and features to the loss function and gradient descent.
In this lecture:
- how a linear model is arranged and what each coefficient means;
- what a loss function is and why regression uses MSE;
- why a derivative is needed and how gradient descent follows from it;
- what training looks like step by step, with a numerical example;
- what overfitting is and how regularization deals with it;
- how linear regression relates to logistic regression.
The main chain of this lecture:
And if the model fits the training data too well:
1. What a machine learning model actually does
Let us start with the most important thing. A machine learning model is a mathematical function that tries to produce the answer we need from input data.
For example, suppose we have information about apartments:
| Area | Rooms | Price |
|---|---|---|
| 40 | 1 | 4 M |
| 50 | 2 | 5 M |
| 70 | 3 | 7 M |
| 90 | 3 | 9 M |
We want to teach the computer to predict the price of a new apartment. It looks like this:
flowchart TD
N1["apartment data"] --> N2["model"] --> N3["predicted price"]
For example:
flowchart TD
N1["70 m², 3 rooms"] --> N2["model"] --> N3["7.2 M"]
Important: a model does not have to give an absolutely correct answer — it looks for a pattern in the data and uses that pattern to make a prediction.
What "training a model" means
Before training, the model does not yet know exactly how to connect inputs to an answer. We want to tune its internal parameters so that predictions are as close as possible to the known correct answers.
Therefore:
Training a model is the search for suitable model parameters over the training data.
For linear regression, those parameters are the coefficients \(w\) and the intercept \(b\).
2. Objects, features and the target
Here it is important to learn to speak the language of ML.
Object
An object is a single instance from our dataset. For example:
one apartment.
Or:
one customer.
Or:
one photograph.
Or:
one row of a table.
Feature
Feature — a characteristic of an object that we use as input to the model.
For an apartment:
- area;
- number of rooms;
- floor;
- distance to the subway.
For example:
apartment No. 17:
| Feature | Value |
|---|---|
| area | 70 |
| rooms | 3 |
| floor | 5 |
| These are features. |
Target
The target is the quantity the model has to predict. In our example:
That is:
flowchart TD
N1["features"] --> N2["price"]
In the literature you may come across:
- target;
- target variable;
- response;
- dependent variable;
- \(y\).
In this lecture we will mostly use:
where:
- \(X\) — features;
- \(y\) — target.
3. The linear model
Now we can build the model itself. For a single feature:
This is our famous straight line. Let us go through every symbol.
- \(x\) — the input feature; for example, \(x=70\) is the area of the apartment.
- \(w\) — the weight, or the coefficient of the feature: it shows how much the prediction changes when \(x\) changes by one unit.
- \(b\) — the intercept, or bias term: an additional offset of the model.
- \(\hat y\) — the model's prediction; the "hat" means that this is not the real \(y\), but the value the model predicted.
Several features
If there are several features:
For example:
where:
- \(x_1\) — area;
- \(x_2\) — number of rooms;
- \(x_3\) — floor.
4. Model parameters and what each coefficient means
Model parameters are the values the model has to find during training.
For:
the parameters are:
They are learned from the data.
What \(w_1\) means
Suppose the model is \(\hat y=100000x_1+500000\). Then:
- with \(x_1=50\) we get \(\hat y=100000\cdot50+500000=5\,500\,000\);
- with \(x_1=51\) we get \(\hat y=100000\cdot51+500000=5\,600\,000\).
So the coefficient \(100000\) means:
increasing the area by one unit increases the prediction by 100,000, provided the other features are held fixed.
What \(b\) means
If \(\hat y=wx+b\) and \(x=0\), then \(\hat y=b\). Geometrically, \(b\) is where the line crosses the \(y\)-axis.
An important caveat
You should not automatically read \(b\) as some meaningful real-world quantity. For example, an apartment with an area of 0 m² does not exist.
So the mathematical value of \(b\) can still be useful to the model, even if such an object is physically meaningless.
5. Prediction
A prediction is the output of the model. After training we already have the parameters that were found:
A new object arrives. For example:
We plug them in:
We get a number. That is the prediction.
A very important distinction
There is: \(y\) — the true value. And: \(\hat y\) — the prediction. For example:
The model was wrong. And now we need to measure that error somehow.
6. The intuitive and geometric meaning of linear regression
For a single feature: \(\hat y=wx+b\) — this is a straight line. We have points:
Price
↑
| ●
| ●
| ●
| ●
| ●
+----------------------→ Area
The model tries to draw the line that best describes the overall trend:
Price
↑
| ●
| ╱
| ● ╱
| ● ╱
| ●╱
| ╱
+----------------------→ Area
It does not have to pass through every point. On the contrary, real data almost always contains noise.
What noise is
Noise is random or unaccounted-for factors that affect the data.
For example, two apartments of the same area may cost different amounts because of:
- renovation;
- neighborhood;
- condition of the building;
- the view from the window;
- how urgently the seller needs to sell.
But our simple model knows nothing about these factors. So it is impossible to hit every point perfectly.
7. The loss function
Now a fundamental concept appears. A loss function is a mathematical function that tells us:
how badly the model is currently predicting the answers.
That is:
flowchart TD
N1["prediction"] --> N2["compare with reality"] --> N3["loss"]
The worse the predictions, the larger the loss. The better they are, the smaller it is. Our goal:
8. MSE: the formula, the meaning of each element, and why we square
Linear regression very often uses MSE — Mean Squared Error, the mean squared error. For a general overview of different loss functions, see the article “Loss Functions”.
The formula:
Now let us go through it piece by piece.
\(n\)
The number of objects. For example, we have 100 apartments:
\(i\)
The index of the object. If:
we are looking at the first apartment. If:
the second one. And so on.
\(y_i\)
The true target for object \(i\). For example:
\(\hat y_i\)
The model's prediction:
\(y_i-\hat y_i\)
The error. For example:
Why square it?
If we simply add the errors up:
Positive and negative errors can cancel each other out. Squaring solves the problem: \((+200\,000)^2\) and \((-200\,000)^2\) are both positive.
On top of that, squaring punishes large errors hard
Let us compare:
an error of 2:
an error of 10:
The error grew 5 times, but the contribution to MSE grew 25 times. That is why MSE is especially sensitive to large errors.
Why the mean?
Because we want a single measure of the model's quality over the whole dataset. For example:
the errors after squaring:
The mean:
9. Why training a model becomes a minimization problem
Now we put everything together. We have a model:
It depends on the parameters:
And quality is measured by MSE:
But \(\hat y_i\) depends on \(w\) and \(b\). Consequently:
MSE also depends on the model parameters.
So in effect we have:
And the problem becomes:
This is an optimization problem.
10. What optimization is
Optimization is the search for the best option among the possible ones.
In our case:
find the model parameters for which the error is minimal.
For example, suppose we have just one parameter \(w\). Imagine that:
| \(w\) | MSE |
|---|---|
| 0 | 100 |
| 1 | 49 |
| 2 | 16 |
| 3 | 4 |
| 4 | 9 |
| 5 | 25 |
The minimum is around:
So we need to find that minimum.
11. The derivative — first in plain words
Here we will need some mathematics. But first, the human meaning.
The derivative shows how fast a function is changing at a given moment.
Imagine a car. There is the car's position \(s(t)\). The derivative of position with respect to time:
gives the speed. That is:
how fast the position changes as time changes.
Even simpler
There is a function:
We changed \(x\) a little. The derivative tells us:
roughly what will happen to \(y\) if we change \(x\) a little, and in which direction it will go.
Example
Let:
The derivative:
If:
then:
This means that near the point \(x=3\) the function grows with a steepness of 6.
12. How the derivative connects to ML
We have an error function:
We need to make it smaller. The derivative:
tells us:
if we change \(w\) a little, how will the error change?
For example:
A positive value means that increasing \(w\) makes the error grow at this point. So to reduce the error, it makes sense to move \(w\) in the opposite direction.
If:
then increasing \(w\) reduces the loss.
13. The gradient — what it is and how it differs from the derivative
This is where it is easy to get confused.
Derivative
When a function has one variable:
we can compute:
That is the derivative.
What if there are several parameters?
For example:
Now we need to know:
- how the loss changes when \(w_1\) changes;
- how the loss changes when \(w_2\) changes;
- how the loss changes when \(b\) changes.
We get several derivatives:
Together they form the gradient:
Very briefly
A derivative is the change of a function with respect to one variable. Gradient is the set of derivatives with respect to all parameters of a multivariate function.
You can think of it like this:
flowchart TD
A["one parameter"] --> B["derivative"]
flowchart TD
C["many parameters"] --> D["gradient"]
14. Gradient descent
Now we can put it all together.
Gradient Descent is an algorithm for finding the minimum of a function.
The name is literal:
- gradient — gradient;
- descent — descent.
That is:
we walk in the direction that reduces the error.
Intuition
Imagine we are standing on the slope of a mountain, with the minimum down below. We do not know the whole map. But we can figure out:
“Which way does the slope go down right now?”
And take a small step. Then look at the slope again. And take another step.
●
/
/
●
/
●
/
● ← minimum
15. The gradient descent formula
For a single parameter:
Let us go through absolutely everything:
| Symbol | What it means |
|---|---|
| \(w_{old}\) | the current value of the parameter |
| \(Loss\) | the error function |
| \(\frac{dLoss}{dw}\) | the derivative: it shows the direction in which the error grows |
| \(\alpha\) | the learning rate |
| the minus sign | we go against the direction of growth, that is, toward a smaller error |
The minus sign in front of the derivative is exactly what "against the growth" means: we step not where the error grows, but in the opposite direction.
16. A numerical example of gradient descent
Suppose:
And we computed:
Let:
Then:
We took a step toward a smaller loss. Then we compute the gradient again. And update again.
17. The step-by-step training algorithm
Gradient descent can be laid out like this:
1. Initialize the parameters
For example:
2. Make predictions
3. Compute the loss
For example:
4. Compute the gradient
We find out how each parameter affects the error.
5. Update the parameters
6. Repeat
Until the error becomes small enough or some other stopping condition is met.
18. Learning rate
Learning rate is the step size used when changing the parameters.
It is denoted \(\alpha\), or sometimes \(\eta\).
Learning rate too small
For example, with \(\alpha=0.000001\) we will move toward the minimum in tiny steps. The upside:
we may move very slowly.
Too large
For example, with \(\alpha=10\) we may overshoot the minimum:
minimum
↓
───────●───────●───────●──────
← →
Instead of gradually approaching the minimum, the algorithm may:
- jump back and forth;
- converge poorly;
- diverge altogether.
A good learning rate
Should let us move:
fast enough, but without overshooting the minimum.
19. The analytical solution of linear regression
Now a very important difference. For linear regression there is not only gradient descent. The problem can also be solved analytically. That is, we can obtain the parameters that minimize MSE directly, mathematically.
In the simple case
For a single feature there are formulas for the optimal \(w\) and \(b\). For the multivariate case we use matrix notation:
This is called the normal equation. But right now it is more important for us to understand the meaning than to memorize matrix algebra.
What is happening here conceptually
Gradient descent
flowchart TD
A1["start somewhere"] --> A2["take a step"] --> A3["look at the gradient"]
flowchart LR
B1["another step"] --> B2["minimum"]
Analytical solution
flowchart TD
N1["take a mathematical expression"] --> N2["solve the minimization problem"] --> N3["obtain the optimal parameters"]
When the analytical solution is convenient
When the problem is relatively small and matrix computations are acceptable. But with a very large number of features, computing it directly can be expensive.
Gradient methods can handle far larger problems.
20. Centering: why we subtract the mean
Now we can work out why data is centered in linear regression. We introduce the centered value of the feature:
where:
That is, the mean is subtracted from every value. For example:
The mean:
The centered data:
Its mean:
We do the same for \(y\). We get:
and:
After that, for centered data, mathematics gives:
That is, the intercept disappears.
The main point:
This is not a new model. It is the same principle of linear regression after the data has been centered beforehand.
21. Overfitting and underfitting
Now we move from:
“how well does the model explain the training data”
to a more important question:
“how well does it work on new data?”
Underfitting
The model is too simple for the pattern in the data. For example, the real relationship:
•
• •
• •
• •
and we try to describe it with an unsuitable, overly simple model. The model performs poorly:
- on train;
- on new data.
Overfitting
Here the problem is the opposite. The model has fitted the training data too closely. It may perform very well on train:
but poorly on new data:
The main idea
We are not interested in:
“How well did the model memorize train?”
But in:
“How well does the model work on data it has never seen before?”
This is called generalization.
22. Regularization: why we need it
Regularization is a way to constrain the model so that it does not fit the training data too closely.
We add an extra penalty to the loss function. Before:
After:
Now the model has to do two things at once:
- predict well;
- keep the parameters from growing too large.
23. L2 regularization
L2 adds the sum of the squared parameters. For example:
Where:
- \(w_j\) — the model's weights;
- \(w_j^2\) — the square of a weight;
- \(\sum\) — we add up the squares of all the weights;
- \(\lambda\) — the strength of regularization.
What \(\lambda\) does
If:
there is no regularization. If we increase \(\lambda\):
the penalty for large weights becomes stronger.
So the model tries to make the coefficients smaller.
Intuitively
Without regularization:
“Fit the model to the data as well as you can.”
With L2:
“Fit the model to the data, but don't use enormous coefficients.”
24. Why the square specifically?
Because:
is always positive and heavily penalizes large values. For example:
but:
A large coefficient becomes expensive.
25. L1 regularization
L1 uses absolute values instead of squares:
For example:
The main difference between L1 and L2
L2 usually shrinks the weights, but does not necessarily make them exactly zero. L1 has the property of often driving some weights exactly to zero.
For example:
before:
w1 = 3.2
w2 = 0.4
w3 = -2.7
w4 = 0.1 after L1:
w1 = 2.8
w2 = 0
w3 = -2.3
w4 = 0
This makes L1 useful for feature selection.
26. L1 vs L2 — very briefly
| L1 | L2 | |
|---|---|---|
| Penalty | \(\sum \lvert w \rvert\) | \(\sum w^2\) |
| What it does | shrinks weights | shrinks weights |
| Zero weights | often appear | usually not |
| Effect | can discard features | tends to spread influence across features |
We will come back to L1/L2 in more detail later. For now it is enough to understand:
27. The link between linear and logistic regression
For now, only conceptually. They share a common foundation:
both use a linear combination of features.
Linear regression:
and uses it directly as the prediction:
Logistic regression also computes:
but then transforms \(z\) with a special function to obtain a value related to the probability of a class. So, roughly:
flowchart TD
A["features"] --> B["linear combination"] --> C["linear regression<br/>number"]
B --> D["logistic regression<br/>probability / class"]
We will not go into logistic regression here — that really is the next topic.
28. What you need to be able to explain in an ML interview
You do not have to start with the formula. A good answer starts with the idea.
Question: “What is linear regression?”
You can answer:
Linear regression is a model that predicts a numeric target variable as a linear combination of input features. During training, the model's coefficients are tuned so as to minimize a loss function, often MSE.
Formula: \(\hat y = w_1x_1+\ldots+w_dx_d+b\)
“What is MSE?”
Mean squared error. It is computed as the mean of the squared differences between the true values and the predictions. Squaring removes the sign of the error and penalizes large errors more heavily.
Formula:
“What is gradient descent?”
It is an iterative optimization algorithm that changes the model parameters in the direction that decreases the loss function. The step size is determined by the learning rate.
Formula: \(w \leftarrow w - \eta\,\nabla L(w)\)
“What is a gradient?”
The gradient is a vector of partial derivatives of a function with respect to all of its parameters. It points in the direction of the fastest growth of the function, so to minimize the loss we move in the opposite direction.
Formula:
“Why do we need a learning rate?”
It determines the step size when updating the parameters. A learning rate that is too small makes training slow; one that is too large can overshoot the minimum or cause instability.
Formula: the step size is \(\Delta w = -\eta\,\nabla L\), and the coefficient \(\eta\) sets its magnitude.
“What is overfitting?”
A situation where the model fits the training data too closely and performs worse on new data. It is a matter of poor generalization.
“Why regularization?”
To limit the complexity of the model and reduce the risk of overfitting. A penalty on the size of the parameters is added to the loss function.
Formula: \(L_{\text{reg}} = L + \lambda R(w)\)
“How does L1 differ from L2?”
L1 penalizes the sum of the absolute values of the weights and can zero out individual coefficients. L2 penalizes the sum of the squared weights and usually merely shrinks them, without such pronounced zeroing.
Formula: \(R_{L1}(w)=\sum_i\lvert w_i\rvert\) and \(R_{L2}(w)=\sum_i w_i^2\)
29. What is especially important not to mix up here
Error
For a single object:
Loss
A function that aggregates errors and turns them into a single number describing the model's quality. For example:
Optimization
The process of searching for the parameters at which the loss is minimal.
Gradient
Information about how the loss changes when all the parameters change.
Gradient descent
An algorithm that uses the gradient to reduce the loss.
30. The whole cause-and-effect chain
This diagram is really worth remembering.
- Data — objects with features \(X\) and the target \(y\).
- Model — a linear combination of features with parameters \(w_1, w_2, \ldots, b\).
- Prediction — the model produces an answer for each object.
- Comparison with the target — how far the prediction is from the correct answer \(y\).
- Error — a numerical measure of the difference.
- Loss function — the errors are combined into one value, for example MSE.
- Goal of training — to reduce the loss.
- Optimization — there are two routes: an analytical solution and gradient descent.
- Gradient — shows in which direction and by how much to change the parameters.
- Parameter update — the steps repeat until the loss becomes small enough. 11. Trained model — the finished model is applied to new data.
- Generalization — quality on data the model has never seen.
And if the model starts to fit too closely:
flowchart TD
N1["overfitting"] --> N2["regularization"] --> N3["L1 / L2"]
31. Self-check
Answer each question for yourself, then open the answer and compare — first without peeking. You do not have to answer perfectly — the goal is to see where the gaps are.
Question 1
There is a model \(\hat y=3x+2\). What is the prediction when \(x=4\)?
Show answer
We substitute \(x=4\) into the model: \(\hat y=3\cdot4+2=14\).
Question 2
In the same model \(\hat y=3x+2\). What does the coefficient 3 mean?
Show answer
The coefficient \(3\) is the slope of the line: when \(x\) increases by one, the prediction grows by \(3\).
Question 3
The true value \(y=10\). The prediction \(\hat y=7\). What is the error \(e=y-\hat y\)? And what is its square?
Show answer
The error: \(e=y-\hat y=10-7=3\). The square of the error: \(e^2=3^2=9\).
Question 4
There are three errors \(2,-2,1\). Why can't we simply take their sum?
What do we get if we use MSE?
Show answer
The sum \(2+(-2)+1=1\): the positive and the negative error cancel each other out, so the sum does not show the magnitude of the error. MSE computes the mean of the squares:
Question 5
Why can training a linear regression be written as \(\min Loss(w,b)\)? What exactly are we minimizing, and what are we looking for?
Show answer
Training is a minimisation task: the loss function is minimised (for example MSE computed over all the objects of the training set), and the quantities being sought are the parameters of the model — the weights \(w\) and the intercept \(b\).
Question 6
What does a positive derivative roughly mean \(\frac{dLoss}{dw}>0\)? If we want to reduce the loss, roughly which way should we move \(w\)?
Show answer
A positive derivative \(\frac{dLoss}{dw}>0\) means that when \(w\) increases, the loss function grows. To make the loss decrease, the parameter is moved in the opposite direction — \(w\) is decreased.
Question 7
How does a derivative differ from a gradient?
Show answer
A derivative describes the rate of change of a function with respect to one variable. A gradient generalises this concept to several variables: it combines the partial derivatives with respect to all the parameters and defines the direction of the steepest growth of the function.
Question 8
What happens if the learning rate is made very small?
And if it is made very large?
Show answer
With a very small learning rate the steps become tiny, and training requires a very large number of iterations. With a very large learning rate the step jumps over the minimum, the loss may grow, and training may become unstable.
Question 9
What is the conceptual difference between:
the analytical solution
and
gradient descent?
Show answer
The analytical solution gives the answer in one formula: \(\theta=(X^TX)^{-1}X^Ty\) — without choosing a step and without iterations. Gradient descent searches for the minimum gradually: at every step the parameters are moved against the gradient by an amount set by the learning rate. The analytical solution is convenient for small tasks, and gradient descent when there is a lot of data or many parameters.
Question 10
A model has \(Loss_{train}=0.01\)
and on new data \(Loss_{test}=4.2\). What might this mean?
Show answer
The model describes the training data almost perfectly (\(Loss_{train}=0.01\)) but is badly wrong on new data (\(Loss_{test}=4.2\)). This is a sign of overfitting: the model has fitted the training set and generalises poorly.
Question 11
Why is regularization added to MSE?
Show answer
Regularization limits the magnitude of the parameters and reduces the risk of overfitting: a penalty for large weights is added to MSE, so the model chooses more moderate solutions.
Question 12
How do these differ: \(\lambda\sum |w_j|\) and \(\lambda\sum w_j^2\) ?
Show answer
\(\lambda\sum \lvert w_j \rvert\) is the L1 penalty: it is imposed on the absolute values of the weights and can zero out individual coefficients. \(\lambda\sum w_j^2\) is the L2 penalty: it is imposed on the squares of the weights and reduces them smoothly, without pronounced zeroing.
Question 13 — the big one
Explain the whole chain in your own words:
data → model → prediction → error → loss → optimization → parameters → new data
If you can explain the chain without formulas, then the foundation of this lecture has really sunk in.
Show answer
The chain describes the whole path of a model. Data — objects with features and known answers. Model — a formula with parameters, for example a linear combination of features. Prediction — the prediction of the model for an object. Error — the difference between the true answer and the prediction. Loss — a number that sums up the errors over the whole sample, for example MSE. Optimization — the search for the parameters at which the loss is minimal (analytically or by gradient descent). Parameters — the weights and the intercept that have been found. New data — a check of how well the model generalises: a good model works not only on the training set.
32. A compact cheat sheet
Linear model
\(x\) — features
\(y\) — the true target
\(\hat y\) — the prediction
\(w\) — weights
\(b\) — the intercept
Prediction
We plug the features into the trained model:
Error
MSE
Squaring:
- removes the sign;
- penalizes large errors more heavily.
Training
Derivative
Shows how a function changes when one variable changes.
Gradient
The set of partial derivatives with respect to all parameters:
It points in the direction of the fastest growth of the function.
Gradient Descent
We go against the gradient, because we want to reduce the loss.
Learning rate
The step size. Too small → slow. Too large → we may overshoot the minimum / training becomes unstable.
Analytical solution
For linear regression, the minimization problem can be solved directly. In matrix form:
This is the normal equation.
Generalization
A good model should work not only on train, but also on new data.
Underfitting
The model is too simple. It performs poorly even on the training data.
Overfitting
The model has fitted train too closely. Good on train → noticeably worse on new data.
Regularization
We add a penalty:
To constrain parameters that are too large or too complex and help the model generalize better.
L1
It can zero out individual weights.
L2
It usually shrinks weights without zeroing them out so aggressively.
Centering
After centering:
If \(X\) and \(y\) are centered, then in the corresponding linear regression problem the optimal intercept is zero:
The shortest version of the whole lecture
If only 10 lines were left of this lecture, they would be these:
- Linear regression predicts a number as a linear combination of features.
-
The model:
\[ \hat y=w_1x_1+\ldots+w_dx_d+b \] -
\(w\) and \(b\) are parameters that the model learns from the data.
- The prediction is compared with the true \(y\).
- The difference between them is the error.
-
The errors are combined by a loss function, for example MSE:
\[ MSE=\frac1n\sum_i(y_i-\hat y_i)^2 \] -
Training = finding the parameters at which the loss is minimal.
- To find the minimum you can use the analytical solution or gradient descent.
-
Gradient descent changes the parameters:
\[ \theta\leftarrow\theta-\alpha\nabla Loss \] -
A good model should not merely work well on train, but generalize to new data; L1/L2 regularization helps fight overfitting.
If these ten points are genuinely clear, then the core of linear regression is already in place. Everything else in this lecture is a detailed explanation of why those points work the way they do.
🧪 Practice
- Fit a line by hand — residuals from every point, live MSE and the parabola of “MSE versus slope”: you can see that the minimum is unique and that both gradient descent and the least-squares formula arrive at it.
- Polynomial degree: overfitting — the same question about model complexity, but on polynomials: the curve on the left, the training and new-data errors on the right, with a minimum.
- Descent over the loss function — how gradient descent works and why the step size matters so much.
- Optimizer race — SGD, Momentum and Adam start from the same point and head for the minimum.
Check yourself
📚 Further reading
- Loss Functions — an overview of loss functions.
- Overfitting and regularization — more on L1/L2.