Linear Regression Math

Disclaimer: This Jupyter Notebook contains content generated with the assistance of AI. While every effort has been made to review and validate the outputs, users should independently verify critical information before relying on it. The SELENE notebook repository is constantly evolving. We recommend downloading or pulling the latest version of this notebook from Github.

The Math Behind Linear Regression

As a quick recap, Linear Regression is a fundamental statistical and machine learning model used to understand and predict relationships between variables. It models the relationship between one or more independent variables x1x1, x2x2, ..., xnxn and a dependent variable yy, assuming a linear relationship between them. Mathematically, this relationship is described by the following equation:

yi=w0+w1xi1+w2xi2+w3xi3+⋯+wdxid+ei\large yi = w{0} + w{1}x{i1} + w{2}x{i2} + w{3}x{i3} + \dots + w{d}x{id} + e{i}

with i=1,...,ni = 1,..., n, where

nn is the number of observations (i.e., the number of records in our dataset) yiyi is the ii-th response (e.g., the resale price of an apartment) wkwk is the kk-th coefficient, with w0w0 being the constant term in the model called bias, offset, or intercept xijx{ij} is the jj-th predictor variable (e.g., the size of an apartment, or the floor height) of the ii-th observation eiei is the noise term, disturbance term, or error variable of the ii-th observation

Assuming that the expectation value for the noise terms E(ei)=0E(ei) = 0, we can use a Linear Regression model to calculate the estimatedestimated or predictedpredicted output h^i\hat{h}{i} for the ii-th data records as follows:

y^i=E(yi)=w0+w1xi1+w2xi2+w3xi3+⋯+wdxid\large \hat{y}{i} = E(y{i}) = w{0} + w{1}x{i1} + w{2}x{i2} + w{3}x{i3} + \dots + w{d}x{id}

We saw that training or fitting a Linear Regression model meant to find the weights w={w0,w1,w2,…,wd}\mathbf{w} = \{w0, w1, w2, \dots, wd \} the yield the best predictions y^\hat{y} compared to the true values yy given by a training dataset. To find those best weights, we first introduced a loss function to quantify how well the current set of weights w\mathbf{w} performs. We then looked different ways to find the best weights by minimizing the loss function either analytically using the Normal Equation or iteratively using methods such as Gradient Descent.

In the introductory notebook, we defined the loss function for Linear Regression as the Mean Squared Error (MSE) as well as glossed over the mathematical details such as calculating the derivative of the MSE loss function and the definition of the Normal equation. In this notebook, we look into more detail why the MSE is commonly the loss function of choice, as well look into all the mathematical steps involved to train a Linear Regression model.

Setting up the Notebook

Make Required Imports

This notebook requires the import of different Python packages but also additional Python modules that are part of the repository. If a package is missing, use your preferred package manager (e.g., or ) to install it. If the code cell below runs with any errors, all required packages and modules have successfully been imported.

from src.utils.libimports.linreg import *
from src.utils.plotting.linreg import *
from src.utils.data.files import *

Download Required Data

Some code examples in this notebook use data that first need to be downloaded by running the code cell below. If this code cell throws any error, please check the configuration file config.yaml if the URL for downloading datasets is up to date and matches the one on Github. If not, simply download or pull the latest version from Github.

csi_example, _ = download_dataset("tabular/regression/example-csi-height-prediction.csv")

Output

File 'data/datasets/tabular/regression/example-csi-height-prediction.csv' already exists (use 'overwrite=True' to overwrite it).

---

Choice of Loss Function

Consideration of Alternatives

To motivate the choice of the MSE as a suitable loss function for Linear Regression, we can look at some alternatives and discuss their pros and cons. To this end, we use the CSI example dataset from the introductory notebooks to better illustrate the behavior of different loss functions. As usual, we first load the dataset file using the pandas library.

df = pd.read_csv(csi_example)

df.head()

Output

With the provided auxiliary method plotcsidata() we can also plot the dataset together with the regression line representing the true relationship between the input and the output, as well as the error between the prediction and the true values (dashed black lines). The weights w0=70w0 = 70 and w1=3.6w1 = 3.6 describing the true relationship are the same as used in the introductory notebook.

# Extract the data matrix X and the label vector y from DataFrame
X = df[['shoe print size']].to_numpy()
y = df[['height']].to_numpy().squeeze()

# Define define weights describing true relationship
w_true = [70, 3.6]

# Plot data with regression line and errors
plot_csi_data(X.squeeze(), y, regression_lines=[(w_true, "red", "True Relationship")], show_errors=True)

Output

Notebook output

From the plot we can derive that the line that best fits the overall data distribution is the line that minimizes the errors between the predicted and true values. This means that we are looking for weights that yield predictions close to the true values. To quantify the difference between the predicted values y^\hat{y} and the true values y\mathbf{y} with respect to a current set of weights w\mathbf{w}, we introduced the concept of a loss function L (also called error function or loss function):

L(y^,y)="single value reflecting the difference between estimates/predictions and true values"\large L(\hat{\mathbf{y}}, \mathbf{y}) = \text{"single value reflecting the difference between estimates/predictions and true values"}

Based on this general requirement for a loss function, there are various approaches to actually implement this function. In the following, we will go through some conceivable alternatives to see how suitable they are for application of a loss function for Linear Regression models.

(Simple) Mean Error

The most naive way to calculate the error between the predicted and true values would simply by to calculated the difference between the values, and average the differences across all training data samples:

LME(y^,y)=1n\sumin(y^i−yi)\large L{ME}(\hat{\mathbf{y}}, \mathbf{y}) = \frac{1}{n} \sumi^n (\hat{y}i - yi)

Of course, this causes a problem. Since a true value yiyi can be smaller or larger than the predicted value (^y)i\hat(y)i, the error (y^i−yi)(\hat{y}i - yi) can be positive or negative. This means that we might have very large positive and negative errors (i.e., having a bad model) that can still yield a very low loss because the errors cancel each other out during the summation of the errors. In other words, a small loss is not an indicator for a good model. Therefore, the LMEL{ME} is not an appropriate loss function.

Mean Absolute Error (MAE)

One straightforward way to avoid negative errors is to sum up the absolute values between the predicted and true values:

LMAE(y^,y)=1n\sumin∣y^i−yi∣\large L{MAE}(\hat{\mathbf{y}}, \mathbf{y}) = \frac{1}{n} \sumi^n \left| \hat{y}i - yi \right|

In principle, this is an appropriate loss function as LL is minimized (i.e., L=0L=0) if all predictions y^i\hat{y}i match the true values yiyi; and the larger the differences the larger the loss. The problem with the MAE, however, is that it is mathematically "inconvenient" for the purpose of training a Linear Regression model. To understand this, let's look at the plot of the function f(x)=∣x∣f(x)=|x|:

plt.figure()
x = np.linspace(-5, 5, 1000)
plt.plot(x, np.abs(x));
plt.show()

Output

Notebook output

The problem is that the derivative of function f(x)=∣x∣f(x)=|x| is

∂f∂x=x∣x∣\large \frac{\partial f}{\partial x} = \frac{x}{|x|}

which means that the derivative is not defined for x=0x=0. However, we favor loss function LL that is differentiable (i.e., the derivative of the function exists at all points) for actually minimizing LL. In practice, this special case of x=0x=0 can be handled separately to use the MAE as a loss function. In practice, we can avoid any special treatment by using the next best alternative to ensure only positive errors, which brings us to the Mean Squared Error (MSE).

Mean Squared Error (MSE)

The common alternative to avoid negative errors without using the absolute function is to square the errors, as the square of any number is always positive. This, in fact, is captured by the MSE we introduced as the common loss function to fit Linear Regression Models:

LMSE(y^,y)=1n\sumin(y^i−yi)2\large L{MSE}(\hat{\mathbf{y}}, \mathbf{y}) = \frac{1}{n} \sumi^n (\hat{y}i - yi)^{2}

Compared to LMAEL{MAE}, the LMSEL{MSE} is also differentiable, allowing for finding its minimum without any handling special cases where the derivative of the LMSEL{MSE} would not be defined. We cover the calculation of the derivative in full detail later in this notebook.

Mean Even-Power Error (Mean Even-Power Error)

Given the MSE loss, a possible question might be why not use larger powers (assuming even powers to ensure only positive errors), i.e.:

LMEPE(y^,y)=1n\sumin(y^i−yi)k\large L{MEPE}(\hat{\mathbf{y}}, \mathbf{y}) = \frac{1}{n} \sumi^n (\hat{y}i - yi)^{k}

where k=4,6,8,…k = 4, 6, 8, \dots is an even number larger than 2. As this loss is also differentiable, it could be indeed considered an appropriate loss function. Compared to the MSE loss (using a power of 2), larger powers make the loss more susceptible to outliner, that is, where the difference between the predicted and true values is very large compared to the average. In fact, it can be argued that the MSE loss is already susceptible due to squaring the errors. Let's have a quick look by converting a single data point in our CSI example dataset to an outlier:

# Create copy to preserve the orignal data
y_with_outlier = np.copy(y)

# Increase the value of a data point by 50%
y_with_outlier[15] *= 1.50

We can now train a Linear Regression model using this modified dataset containing the outlier and again plot the regression line.

# Train/fit a Linear Regression model based on data with outlier
model_csi = LinearRegression().fit(X, y_with_outlier)

# Extract the weights for plotting the regression line
w_fit = [model_csi.intercept_, model_csi.coef_[0]]

plot_csi_data(X.squeeze(), y_with_outlier, regression_lines=[(w_fit, "red", "Predicted Relationship")], show_errors=True)

Output

Notebook output

Notice how this change of a single data point "pulls" the regression line upwards. This means that even the MSE loss function makes training a Linear Regression potentially quite sensitive to outliers. However, with an even power larger than 2, this effect would be much more pronounced. So the MSE represents a reasonable trade-off.

Other Loss Functions

In principle, loss functions can be arbitrarily complex as long as they remain appropriate. To give one example here, a commonly used more complex loss function for regression tasks is the so-called Huber Loss Smooth Mean Absolute Error (SMAE). As the name suggests, it is based on the MAE to be less susceptible to outliers. To avoid the problem that the derivative of the MAE is not defined for errors that are 00, the Huber loss integrates the MSE loss for small errors. As such the Huber Loss for a single data point is defined as follows:

LSMAE(y^i,y)={12(y^i−yi)2for ∣y^i−yi∣≤δδ∣y^i−yi∣−12δ2otherwise\large L{SMAE}(\hat{y}i, y) = \begin{cases} \frac{1}{2}(\hat{y}i - yi)^{2} & \text{for } |\hat{y}i - yi| \leq \delta\\[0.75em] \delta |\hat{y}i - yi| - \frac{1}{2}\delta^2 & \text{otherwise} \end{cases}

The definition of the Huber Loss LSMAEL{SMAE} ensures that both cases yield the same gradient going towards ∣y^i−yi∣=δ|\hat{y}i - yi| = \delta from either side.

For a better understanding, we can plot the Huber Loss and compare it with the MAE and MSE loss. In the formula above, you can see that the Huber Loss has a parameter δ\delta to specify the maximum error for the MSE component of the Huber Loss to be used. The code cell below calls an auxiliary method to handle the plotting. You can change the list of deltas to try out different δ\delta values.

plot_huber_loss(deltas=[0.1, 1, 10], show_mae=True, show_mse=True)

Output

Notebook output

You can see that for δ=1\delta = 1, the Huber Loss is of very similar scale as the MAE loss. Increasing δ\delta means that the MSE component of the Huber Loss is used for a larger range of error values. Therefore, the line for δ=10\delta=10 looks like a parabola, only scaled down by a factor of 1/21/2 compared to the line for the MSE loss (notice the factor of 1/21/2 in the formula for LSMAEL{SMAE} above). For small δ\delta values, only a small interval around 0 gets captured by the MSE component. Since the derivatives of the MAE and MSE component must yield the same gradient for ∣y^i−yi∣=δ|\hat{y}i - yi| = \delta, this also means the MAE component becomes very flat for low δ\delta values.

Linear Regression as Statistical Model

So far, we mainly used arguments that the MSE is the most suitable loss function of Linear Regression. The MSE loss is appropriate, differentiable, and not overly susceptible to outliers. However, there is a much more fundamental reason to use the MSE as the loss function when considering Linear Regression as a probabilistic model. Recall that a Linear Regression model was defined as

yi=w0+w1xi1+w2xi2+w3xi3+⋯+wdxid+ei\large yi = w{0} + w{1}x{i1} + w{2}x{i2} + w{3}x{i3} + \dots + w{d}x{id} + e{i}

where we assume that the errors are normally distributed with a mean of 00 constant variance σ2\sigma^2, i.e.:

ei∼N(0,σ2)\large ei \sim N(0, \sigma^2)

This allows to treat as yiyi a random variable drawn from a Normal Distribution with the constant variance σ2\sigma^2 and the mean being the predicted value y^i\hat{y}{i}, i.e., μi=y^i=θTxi\mu{i} = \hat{y}{i} = \theta^{T}\mathbf{x}{i}

yi∼N(wTxi,σ2)\large yi \sim N(\mathbf{w}^{T}\mathbf{x}{i}, \sigma^2)

Using the formula for the Normal Distribution, the probability of yiyi can be written as follows:

P(yi∣μi,σ2)=12πσ2e−12σs(yi−μi)2\large P(yi | \mu{i}, \sigma^2) = \frac{1}{\sqrt{2\pi \sigma^2}} e^{-\frac{1}{2\sigma^s}\left(yi - \mu{i} \right)^2}

With μi=θTxi\mu{i} = \theta^{T}\mathbf{x}{i}, this probability can be further rewritten to

P(yi∣xi;w,σ2)=12πσ2e−12σ2(yi−wTxi)2\large P(yi | \mathbf{xi}; \mathbf{w}, \sigma^2) = \frac{1}{\sqrt{2\pi \sigma^2}} e^{-\frac{1}{2\sigma^2}\left(yi - \mathbf{w}^{T}\mathbf{x}{i} \right)^2}

Maximum Likelihood Estimation

With P(yi∣xi;θ,σ2)P(yi | \mathbf{x}{i}; \theta, \sigma^2) we can calculate probability of observing the response yiyi given input xi\mathbf{xi} and the parameters W\mathbf{W} and σ2\sigma^2. However, what we are really interested in are the values for the weights w\mathbf{w} that maximize the probability. This expressed by the likelihood L(θ∣xi,yi;σ2)\mathcal{L}(\theta|\mathbf{x}{i}, yi; \sigma^2) - that is, the likelihood that model with parameters w\mathbf{w} and σ2\sigma^2 produced response yiyi from input xi\mathbf{x}{i}.

The likelihood function L\mathcal{L} is equal to the probability density function parameterized by the weights w\mathbf{w}:

L(w∣xi,yi;σ2)=P(yi∣xi;w,σ2)=12πσ2e−12σ2(yi−wTxi)2\large L(\mathbf{w}|\mathbf{x}{i}, yi; \sigma^2) = P(yi | \mathbf{x}{i}; \mathbf{w}, \sigma^2) = \frac{1}{\sqrt{2\pi \sigma^2}} e^{-\frac{1}{2\sigma^2}\left(yi - \mathbf{w}^{T}\mathbf{x}{i} \right)^2}

We can extend the likelihood for a single data point to the the likelihood over all data points in a dataset:

L(w∣X,y;σ2)=∏i=1n12πσ2e−12σ2(yi−wTxi)2\large L(\mathbf{w}|\mathbf{X}, \mathbf{y}; \sigma^2) = \prod{i=1}^{n} \frac{1}{\sqrt{2\pi \sigma^2}} e^{-\frac{1}{2\sigma^2}\left(yi - \mathbf{w}^{T}\mathbf{x}{i} \right)^2}

Let's modify this formula in two ways. Firstly, we apply the logarithm to the product. Using the logarithm rule log⁡mn=log⁡m+log⁡n\log{mn} = \log{m}+\log{n}, we can convert the product into a sum. This makes calculating the derivative much easier. Note that we can do this because the logarithm is a monotonically increasing function. This means that the minima or maxima of a function will be at the same input values before and after the application of the logarithm. And secondly, notice that we want to maximize the likelihood. However, we typically consider loss functions to be minimized. Therefore, although not required, we add a minus sign to the likelihood. Both these modifications give us the so-called Negative Log-Likelihood NLLNLL:

NLL(w∣X,y;σ2)=−log⁡[∏i=1n12πσ2e−12σ2(yi−wTxi)2]=−∑i=1nlog⁡[12πσ2e−12σ2(yi−wTxi)2] \begin{align} \large NLL(\mathbf{w}|\mathbf{X}, \mathbf{y}; \sigma^2) &= \large - \log \left[ \prod{i=1}^{n} \frac{1}{\sqrt{2\pi \sigma^2}} e^{-\frac{1}{2\sigma^2}\left(yi - \mathbf{w}^{T}\mathbf{x}{i} \right)^2}\right] \\[1.25em] &= \large - \sum{i=1}^{n} \log \left[ \frac{1}{\sqrt{2\pi \sigma^2}} e^{-\frac{1}{2\sigma^2}\left(yi - \mathbf{w}^{T}\mathbf{x}{i} \right)^2}\right] \\[1.25em] \end{align}

We can further simplify this formula by more repeated applications of the logarithm rules log⁡mn=log⁡m+log⁡n\log{mn} = \log{m}+\log{n} as well as log⁡(mk)=klog⁡m\log{\left(m^k \right)} = k\log{m}. For even we assume that the logarithm is the natural logarithm, we can also apply the rule log⁡e(ek)=k\log{e}{\left(e^k \right)} = k, this "bringing down" the exponent of the function of the Normal Distribution:

NLL(w∣X,y;σ2)=−∑i=1nlog⁡[12πσ2e−12σ2(yi−wTxi)2]=−∑i=1n[12log⁡12πσ2−12σ2(yi−wTxi)2]=−N2log⁡12πσ2−12σ2∑i=1n(yi−wTxi)2=−N2log⁡12πσ2−12σ2RSS(w) \begin{align} \large NLL(\mathbf{w}|\mathbf{X}, \mathbf{y}; \sigma^2) &= \large - \sum{i=1}^{n} \log \left[ \frac{1}{\sqrt{2\pi \sigma^2}} e^{-\frac{1}{2\sigma^2}\left(yi - \mathbf{w}^{T}\mathbf{x}{i} \right)^2}\right] \\[1.25em] &= \large - \sum{i=1}^{n} \left[ \frac{1}{2} \log \frac{1}{\sqrt{2\pi \sigma^2}} - \frac{1}{2\sigma^2} \left(yi - \mathbf{w}^{T}\mathbf{x}{i} \right)^2 \right] \\[1.25em] &= \large - \frac{N}{2} \log \frac{1}{\sqrt{2\pi \sigma^2}} - \frac{1}{2\sigma^2} \sum{i=1}^{n} \left(yi - \mathbf{w}^{T}\mathbf{x}{i} \right)^2 \\[1.25em] &= \large - \frac{N}{2} \log \frac{1}{\sqrt{2\pi \sigma^2}} - \frac{1}{2\sigma^2} RSS(\mathbf{w}) \\[1.25em] \end{align}

where RSS(w)=∑i=1n(yi−wTxi)2=∑i=1n(yi−y^i)2RSS(\mathbf{w}) = \sum{i=1}^{n} \left(yi - \mathbf{w}^{T}\mathbf{x}{i} \right)^2 = \sum{i=1}^{n} \left(yi - \hat{y}{i} \right)^2 is the Residual Sum of Squares.

Notice that similarity to the Mean Squared Error MSE(w)=1n\sumin(yi−wTxi)2MSE(\mathbf{w}) = \frac{1}{n}\sumi^n \left(yi - \mathbf{w}^{T}\mathbf{x}{i} \right)^2. In other words, the MSE is the RSS normalized by the number data samples nn. The MSE is in practice often more useful as it allows comparison of different Linear Regression models across different datasets of various sizes. However, note that fitting the weights w\mathbf{w} — that is, finding the best values for w\mathbf{w} that minimize the NLLNLL function does not depend on the constant value 1n\frac{1}{n}.

---

Fitting w\mathbf{w} to Train a Linear Regression Model

To find the best values for the weight w\mathbf{w} that minimize the NLLNLL function, we need to calculate the partial derivative of NLL with respect to w\mathbf{w} and set it to the zero vector 0\mathbf{0}:

∂NLL∂w=!0\large \frac{\partial NLL}{\partial \mathbf{w}} \stackrel{!}{=} \mathbf{0}

We then can solve for w\mathbf{w} to find the function that calculates the best θ\theta values.

However, we can first simplify things. Notice that we only need to consider RSS(w)RSS(\mathbf{w}), since −N2log⁡12πσ2 - \frac{N}{2} \log \frac{1}{\sqrt{2\pi \sigma^2}} is a constant term and −12σ2- \frac{1}{2\sigma^2} a constant factor. As such, we can do

∂RSS∂w=!0\large \frac{\partial RSS}{\partial \mathbf{w}} \stackrel{!}{=} \mathbf{0}

and solve for w\mathbf{w}. Again, keep in mind that RSS(w)=∑i=1n(yi−y^i)2RSS(\mathbf{w}) = \sum{i=1}^{n} \left(yi - \hat{y}{i} \right)^2 is almost same as MSE(w)=1n\sumin(yi−wTxi)2MSE(\mathbf{w}) = \frac{1}{n}\sumi^n \left(yi - \mathbf{w}^{T}\mathbf{x}{i} \right)^2, with only exception being the constant factor of 1/n1/n. While this means that the derivative of RSS and MSE will also slightly be different, once we would set either derivative to 00 and solve for w\mathbf{w}, this constant factor will no longer matter. Hence, in the following, we consider the RSS as the (part of the) loss function we want to minimize with respect to w\mathbf{w}.

So how do we calculate ∂RSS∂w\frac{\partial RSS}{\partial \mathbf{w}}?

Calculating the Derivative

Just for the sake practice, we will calculate the derivative ∂RSS∂w\frac{\partial RSS}{\partial \mathbf{w}} in two different ways, where the difference is only regarding the mathematical notation used to the fine the loss function:

Without matrix notation: Here, we first calculate the partial derivatives ∂RSS∂wk\frac{\partial RSS}{\partial wk}, and then generalize to the complete weight vector w\mathbf{w}.

With matrix notation: Here, we calculate ∂RSS∂w\frac{\partial RSS}{\partial \mathbf{w}} directly by using matrix derivation rules.

Both approaches are completely equivalent.

Without Matrix Notation

We start with the basic definition of RSS(w)RSS(\mathbf{w}) from above but transform the equation to explicitly express all weights w0,w1,w2,…,wdw0, w1, w2, \dots, wd:

RSS(w)=∑i=1n(yi−wTxi)2=∑i=1n(yi−∑j=0dwjxij)2=∑i=1n(yi−w0xi0−w1xi1−⋯−wdxid)2 \begin{align} \large RSS(\mathbf{w}) &= \large \sum{i=1}^n (y{i} - \mathbf{w}^T\mathbf{x}{i} )^2 \\ &= \large \sum{i=1}^n \left( y{i} - \sum{j=0}^d w{j}x{ij} \right)^2 \\ &= \large \sum{i=1}^n \left( y{i} - w{0}x{i0} - w{1}x{i1} - \dots - w{d}x{id} \right)^2 \end{align}

Now we can directly start calculating the derivative ∂RSS∂wk\frac{\partial RSS}{\partial wk} for a single parameter value wkwk. Firstly notice that we can ignore the outer sum since the derivative of a sum is the sum of the individual derivatives. For calculating the derivative with respect to a single weight wkwk, we need the chain rule. As a quick refresher. The chain rule is a rule for finding the derivative of a composite function. If yy is a function of uu, and uu is a function of ww, then yy is ultimately a function of wkwk, and we write:

y=f(u) and u=g(w)⇒y=f(g(wk)).\large y=f(u)\ \text{and} \ u=g(w) \Rightarrow y = f(g(wk)).

The chain rule states that the derivative of yy with respect to wkwk is:

dydwk=dydu⋅dudwk\large \frac{dy}{dwk} = \frac{dy}{du}\cdot \frac{du}{dwk}

If we consider y=(yi−w0xi0−w1xi1−⋯−wdxid)2y = \left( y{i} - w{0}x{i0} - w{1}x{i1} - \dots - w{d}x{id} \right)^2, we can define u=(yi−w0xi0−w1xi1−⋯−wdxid)u = \left( y{i} - w{0}x{i0} - w{1}x{i1} - \dots - w{d}x{id} \right) so that y=u2y = u^2. This allows use to calculate the derivatives dydu\frac{dy}{du} and dudw\frac{du}{dw}:

dydu=2uanddudwk=−xik\large \frac{dy}{du} = 2u \quad \text{and}\quad \frac{du}{dwk} = -x{ik}

This gives as for the derivative dydwk\frac{dy}{dwk}:

dydwk=−2xiku=−2xik(yi−w0xi0−w1xi1−⋯−wdxid)\large \frac{dy}{dwk} = -2x{ik}u = -2x{ik}\left( y{i} - w{0}x{i0} - w{1}x{i1} - \dots - w{d}x{id} \right)

We can now simplify this formula by bringing moving the negative sign into the parenthesis and express the weights sum use a dot product

dydwk=2xik(w0xi0+w1xi1+⋯+wdxid−yi)=2xik(wTxi−yi) \begin{align} \large \frac{dy}{dwk} &= \large 2x{ik}\left(w{0}x{i0} + w{1}x{i1} + \dots + w{d}x{id} - y{i} \right)\\[0.5em] &= \large 2x{ik}\left(\mathbf{w}^T\mathbf{x}{i} - y{i} \right) \end{align}

To get the final derivative with respect to all data samples xixi, we only need to "bring back" the outer sum; and we can move the constant factor of 22 in front of the sum, giving us:

∂RSS∂wk=2∑i=1nxik(wTxi−yi)\large \frac{\partial RSS}{\partial wk} = 2 \sum{i=1}^n x{ik} \left(\mathbf{w}^T\mathbf{x}{i} - y{i} \right)

We now have the partial derivative with respect to a single wiwi. We can now vectorize it further to get the partial derivative with respect to w\mathbf{w}.

∂RSS∂w=2XT(Xw−y) \large \frac{\partial RSS}{\partial \mathbf{w}} = 2\mathbf{X}^T(\mathbf{X}\mathbf{w} - \mathbf{y})

With Matrix Notation

Now, ∥x∥2=∑i=1nxi2\lVert \mathbf{x} \rVert^2 = \sum{i=1}^n xi^2 is the squared vector norm, summing up the squares of all vector elements. This allows us to rewrite LL as follows:

RSS(w)=∑i=1n(yi−wTxi)2=(Xw−y)T(Xw−y) \begin{align} \large RSS(\mathbf{w}) &= \large \sum{i=1}^n (y{i} - \mathbf{w}^T\mathbf{x}{i} )^2 \\ &= \large (\mathbf{X}\mathbf{w} - \mathbf{y})^T(\mathbf{X}\mathbf{w} - \mathbf{y}) \end{align}

Note that with x=(Xw−y)\mathbf{x} = (\mathbf{X}\mathbf{w} - \mathbf{y}) both formulations are indeed equivalent.

Now we can apply various matrix algebra rules to further simplify the formula. Applying (A−B)T=AT−BT(\mathbf{A}-\mathbf{B})^T = \mathbf{A}^T - \mathbf{B}^T (with A\mathbf{A}, B\mathbf{B} being matrices), we can write

RSS(w)=((Xw)T−yT)(Xw−y)\large RSS(\mathbf{w}) = ((\mathbf{X}\mathbf{w})^T - \mathbf{y}^T)(\mathbf{X}\mathbf{w} - \mathbf{y})

We can now multiply both parts to get rid of the product of sums.

RSS(w)=(Xw)TXw−(Xw)Ty−yT(Xw)+yTy\large RSS(\mathbf{w}) = (\mathbf{X}\mathbf{w})^T\mathbf{X}\mathbf{w} - (\mathbf{X}\mathbf{w})^{T}\mathbf{y} - \mathbf{y}^T(\mathbf{X}\mathbf{w}) + \mathbf{y}^T\mathbf{y}

We can now apply the rule (AB)T=BTAT(\mathbf{AB})^T = \mathbf{B}^T\mathbf{A}^T. Also note that yT(Xw)=(Xw)Ty\mathbf{y}^T(\mathbf{X}\mathbf{w}) = (\mathbf{X}\mathbf{w})^T\mathbf{y}. y\mathbf{y} and Xw\mathbf{X}\mathbf{w} are just vectors, so multiplying them either way yields the same results.

RSS(w)=wTXTXw−2(Xw)Ty+yTy\large RSS(\mathbf{w}) = \mathbf{w}^T\mathbf{X}^T\mathbf{X}\mathbf{w} - 2(\mathbf{X}\mathbf{w})^{T}\mathbf{y} + \mathbf{y}^T\mathbf{y}

This is as much as we can simplify RSSRSS. Now we can calculate ∂RSS∂w\frac{\partial RSS}{\partial \mathbf{w}}. Since we have a sum of 3 parts, we can look at all parts individually. Let's start at the back. With respect to θ\theta, yTyy^Ty is a constants, so

∂yTy∂w=0\large \frac{\partial \mathbf{y}^T\mathbf{y}}{\partial \mathbf{w}} = \mathbf{0}

For the middle part, we can apply the rule from matrix calculus stating that ∂Ax∂x=AT\frac{\partial \mathbf{A}\mathbf{x}}{\partial \mathbf{x}} = \mathbf{A}^T. As such,

∂2(Xw)Ty∂w=2XTy\large \frac{\partial 2(\mathbf{X}\mathbf{w})^{T}\mathbf{y}}{\partial \mathbf{w}} = 2\mathbf{X}^T\mathbf{y}

The first part is a bit less obvious and might require actually writing out the individual equations. However, at the end on can apply the following rule ∂xTx∂x=2x\frac{\partial \mathbf{x}^T\mathbf{x}}{\partial \mathbf{x}} = 2\mathbf{x}, giving us

∂wTXTXw∂w=2XTXw\large \frac{\partial \mathbf{w}^T\mathbf{X}^T\mathbf{X}\mathbf{w}}{\partial \mathbf{w}} = 2\mathbf{X}^T\mathbf{X}\mathbf{w}

Putting everything together we finally get:

∂RSS∂w=2XTXw−2XTy\large \frac{\partial RSS}{\partial \mathbf{w}} = 2\mathbf{X}^T\mathbf{X}\mathbf{w} - 2\mathbf{X}^T\mathbf{y}

If we want, we could factor out 2XT2\mathbf{X}^T to get the formula:

∂RSS∂w=2XT(Xw−y)\large \frac{\partial RSS}{\partial \mathbf{w}} = 2\mathbf{X}^T(\mathbf{X}\mathbf{w} - \mathbf{y})

Solving for w\mathbf{w}

Lastly, to get the Normal Equation, setting ∂RSS∂w=0\frac{\partial RSS}{\partial \mathbf{w}} = \mathbf{0} and solving for w\mathbf{w} is comparatively straightforward.

2XT(Xw−y)=!0\large 2\mathbf{X}^T(\mathbf{X}\mathbf{w} - \mathbf{y}) \stackrel{!}{=} \mathbf{0}

First, we can ignore the constant factor 22. Note that this would also include the constant factor 1/n1/n we would have used the derivative of MSE instead of RSS. Let's also factor in XT\mathbf{X}^T and move the terms around:

XTXw−XTy=0XTXw=XTy \begin{align} \large \mathbf{X}^T\mathbf{X}\mathbf{w} - \mathbf{X}^T\mathbf{y} &= \mathbf{0} \\[0.5em] \large \mathbf{X}^T\mathbf{X}\mathbf{w} &= \large \mathbf{X}^T\mathbf{y} \end{align}

Of course, we want to have w\mathbf{w} alone on one side. For this, we can utilize the matrix rule that multiplying the inverse of a matrix with the matrix itself results in the identity matrix, i.e, A−1A=I\mathbf{A}^{-1}\mathbf{A} = \mathbf{I}. Since we would like to get rid of XTX\mathbf{X}^T\mathbf{X} on the left-hand side, let's multiply both sides by (XTX)−1\left(\mathbf{X}^T\mathbf{X} \right)^{-1}:

(XTX)−1XTXw=(XTX)−1XTy\large \left(\mathbf{X}^T\mathbf{X} \right)^{-1}\mathbf{X}^T\mathbf{X}\mathbf{w} = \left(\mathbf{X}^T\mathbf{X} \right)^{-1}\mathbf{X}^T\mathbf{y}

Based on the matrix rule as stated above, the left side of the equation simplifies to w\mathbf{w}:

w=(XTX)−1XTy\large \mathbf{w} = \left(\mathbf{X}^T\mathbf{X} \right)^{-1}\mathbf{X}^T\mathbf{y}

We now have derived that Normal Equation that allows us to analytically find the best values for weights w\mathbf{w} that minimize the loss function for Linear Regression. Often the Normal Equation is written as

w=X†y\large \mathbf{w} = \mathbf{X}^{\dagger}\mathbf{y}

with X†=(XTX)−1XT\mathbf{X}^{\dagger} = \left(\mathbf{X}^T\mathbf{X} \right)^{-1}\mathbf{X}^T called the pseudo inverse of X\textbf{X}. It's called a "pseudo" inverse because it serves as a substitute for the true inverse but does not always satisfy all the properties of a conventional inverse. In particular, for an arbitrary matrix X\mathbf{X}, the pseudo-inverse X†\mathbf{X}^\dagger satisfies these conditions:

XX†X=X\large \mathbf{X}\mathbf{X}^{\dagger}\mathbf{X} = \mathbf{X} X†XX†=X†\large \mathbf{X}^{\dagger}\mathbf{X}\mathbf{X}^{\dagger} = \mathbf{X}^{\dagger} (XX†)T=XX†\large \left(\mathbf{X}\mathbf{X}^{\dagger} \right)^{T} = \mathbf{X}\mathbf{X}^{\dagger} (X†X)T=X†X\large \left(\mathbf{X}^{\dagger}\mathbf{X} \right)^{T} = \mathbf{X}^{\dagger}\mathbf{X}

These conditions ensure that X†\mathbf{X}^{\dagger} minimizes the loss function for cases where the system of equations does not have a unique solution or is over- or under-determined.

---

Summary

The Mean Squared Error (MSE) loss function is one of the most commonly used metrics to evaluate the performance of Linear Regression models. It measures the average squared difference between the predicted values y^\hat{y} and the actual target values yy in a dataset. The squaring operation ensures that all errors are non-negative and amplifies larger deviations, making the model more sensitive to outliers.

In the context of Linear Regression, the MSE serves both as a measure of model accuracy and as the objective function to be minimized during training. Minimizing the MSE ensures that the regression line fits the data as closely as possible, reducing the overall error. One advantage of the MSE is its straightforward gradient calculation, which facilitates optimization techniques like Gradient Descent. However, it can be sensitive to outliers since large errors have a disproportionately high impact on the loss value. Despite this, MSE remains a widely used and effective loss function in many regression problems.