# Linear Regression Algorithm in Practice

Jun 23 · 6 min read

What the linear regression algorithm is and how it is used in regression tasks.

# Introduction

Regression analysis is a process of predicting a response variable given an explanatory variable. The response variable is also called a dependent variable and an explanatory variable is known as an independent variable. Given a problem statement, when there are multiple explanatory variables and one response variable, then the process is known as Multiple Linear Regression. On contrary, if a problem statement contains only one explanatory variable and one response variable, it is known as Simple Linear Regression.

Note — For implementing regression analysis, there needs to be a strong relationship between the explanatory variable and the response variable.

Unlike predicting the class label (in classification task), here we predict the real value (continuous value) for the new unseen data.

# Mathematical Model

Let’s denote the response variable as `y` and the explanatory variable as `X`. Here `X`, can take either a single feature or multiple features.

In the case of `X` having one feature, the model would be -

In the case of `X` having multiple features, the model would be -

The mathematical model (1) is used for simple linear regression tasks, whereas (2) for multiple linear regression tasks. In both cases, the response variable `y^` is the target feature.

The actual response variable is denoted as `y` and we all know that the machine learning model cannot predict very accurately. If it cannot predict accurately, it surely contains an error. Thus, the main focus now shifted to have errors as small as possible.

Substituting (1) in (3) for simple linear regression, we get -

Substituting (2) in (3) for multiple linear regression, we get -

The error `E` is the difference between the actual target feature and the predicted target feature.

Everything is properly written except two things which are still unknown. The two things are the parameters `w` and `b`. The error in the model depends on these two parameter values. Here, `w` is the coefficient and `b` is the intercept. We cannot simply assign random values for `w` and `b`. Instead, they are to be chosen wisely with the help stochastic gradient descent process.

Let’s consider the model equation (1) for understanding optimization.

SGD is an iterative process where we initially assign random values (possibly 0) for both `w` and `b`. At every iteration,

• For `w`, we differentiate (1) with respect to `w` and obtain `dw`.
• For `b`, we differentiate (1) with respect to `b` and obtain `db`.

Mathematically, it can be represented as -

and

We update/replace the actual `w` and `b` with `dw` and `db` respectively at every iteration until the values are not fully minimized. The updating process can be understood in the following way.

and

The entire process is the same for obtaining the minimal values of `W` and `b` for the model equation (2).

Now that we have understood the complete process, let’s implement the same from scratch.

# Linear Regression — Code

We will start by importing the necessary libraries as always at the start.

## Data Creation

For now, we will depend on a toy dataset that we can easily create by the module `sklearn`.

## Data Splitter

We need to split the data into two — the `training` set and the `testing` set. We do this by a random splitter function.

Train Test Split

## Construction

The name of the regression is `LinearRegression` and it is a class where we define other methods.

## `__init__()` Method

The above method is a constructor that takes five parameters -

• `train_df` → refers to the subset of the data that is used to train the regressor.
• `test_df` → refers to the subset of the data that is used to test the regressor.
• `label` → refers to the series of data which is actually the column name of the class label.
• `lambda_` → refers to a constant that is used to update the parameters during the process of SGD.
• `n_iters` → refers to a constant that is used to decide the total iterations of the process of SGD.

## `split_features_targets()` Method

The above method is used to separate features and targets from the data. It takes two parameters -

• `df` → refers to the entire dataset that is passed for classifying.
• `label` → refers to the series of `df` which is actually the column name of the class label.

## `diff_params_wb()` Method

The above method is used to differentiate the parameters. It takes two parameters -

• `w` → refers to the initial weight vector that is used in the process of SGD.
• `b` → refers to the initial intercept value that is used in the process of SGD.

## `find_best_params()` Method

The above method is used to get the best (minimal) values of the parameters `w` and `b`. It takes no parameters. This method follows the process of SGD to update the original values of `w` and `b` iteratively.

## `predict()` Method

The above method is used to predict the real (continuous) value for the new unseen data. It takes two parameters (which are optional) -

• `with_plot` → refers to a boolean value to decide if to plot the best fit line along with the data points.
• `save_process` → refers to a boolean value to decide if to save the process of SGD in `GIF` format.

By default, these function parameters take the `False` value and therefore optional.

## `save_process_togif()` Method

The above method is used to save the process of SGD in the form of `GIF`. It takes two parameters -

• `test_x` → refers to the features whose target needs to be predicted.
• `test_y` → refers to the actual target values.

## `score()` Method

The above method is used to calculate the R². It takes one parameter -

• `preds` → refers to the predicted values that are used to calculate R².

Full Code

# Linear Regression — Testing

We have already created a toy data set. We just need to test the model on that data.

Note: The data that we created is random. Results may differ for each execution.

## Prediction

Training & Testing Plot

The regression line sufficiently passes through the data points.

SGD Process Demonstration

The test values are used to execute the process of SGD. As the values of `w` and `b` change for every iteration the best fit line changes accordingly, and at some point, the line stops changing, which basically means that we have got the minimum values for `w` and `b`.

## Performance Score

The accuracy is almost `69%` for the data whose shape is `(200, 2)`. If we had taken/created large data, then there would have been some change.

# Challenges

Well, this entire code is been developed from scratch and it is sure that it, by performance — may not be as efficient as the library methods. But, it was good to understand the mathematics behind the work.

• My code is slow.
• No regularization is implemented although there types of it.
• Linear regression with L1 regularization is known as Ridge regression.
• Linear regression with L2 regularization is known as Lasso regression.
• Linear regression with both L1 and L2 regularizations is known as ElasticNet regression.
• If outliers are present in the data, it may impact the model significantly.

# References

End

## Geek Culture

A new tech publication by Start it up (https://medium.com/swlh).

Written by

## Sameer

Python Developer | Python Mentor | Aspiring Geo Data Scientist | Support me: https://www.buymeacoffee.com/msameeruddin

## Geek Culture

A new tech publication by Start it up (https://medium.com/swlh).