The Wayback Machine - https://web.archive.org/web/20240927190907/https://www.geeksforgeeks.org/univariate-linear-regression-in-python/
Open In App

Univariate Linear Regression in Python

Last Updated : 22 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will explain univariate linear regression. It is one of the simplest types of regression. In this regression, we predict our target value on only one independent variable.

Univariate Linear Regression in Python

Univariate Linear Regression is a type of regression in which the target variable depends on only one independent variable. For univariate regression, we use univariate data. For instance, a dataset of points on a line can be considered as univariate data where abscissa can be considered as an input feature and ordinate can be considered as output/target. 

Example Of Univariate Linear Regression

For line Y = 2X + 3; the Input feature will be X and Y will be the target.

XY
15
27
39
411
513

Concept: For univariate linear regression, there is only one input feature vector. The line of regression will be in the form of the following:

Y = b0 + b1 * X Where, b0 and b1 are the coefficients of regression.

here we try to find the best b0 and b1 by training a model so that our predicted variable y has minimum difference with actual y.

A univariate linear regression model constitutes of several utility functions. We will define each function one by one and at the end, we will combine them in a class to form a working univariate linear regression model object. 

Utility Functions in Univariate Linear Regression Model

  1. Prediction with linear regression 
  2. Cost function 
  3. Gradient Descent For Parameter Estimation
  4. Update Coefficients
  5. Stop Iterations

Prediction with linear regression 

In this function, we predict the value of y on a given value of x by multiplying and adding the coefficient of regression to the x.

Python
# Y = b0 + b1 * X
def predict(x, b0, b1):

    return b0 + b1 * x

Cost function For Univariate Linear Regression

The cost function computes the error with the current value of regression coefficients. It quantitatively defines how far the model predicted value is from the actual value wrt regression coefficients which have the lowest rate of error. 

Mean-Squared Error(MSE) = sum of squares of difference between predicted and actual value

J(b_1, b_0) = \frac{1}{n} (y_p-y)^2

We use square so that positive and negative error does not cancel out each other.

Here:

  1. y is listed of expected values 
  2. x is the independent variable 
  3. b0 and b1 are regression coefficient 
Python
def cost(x, y, b0, b1):
    errors = []
    for x, y in zip(x, y):
        prediction = predict(x, b0, b1)
        expected = y
        difference = prediction-expected
        errors.append(difference)
    mse = sum([error * error for error in errors])/len(errors)
    return mse

Gradient Descent For Parameter Estimation

 We will use gradient descent for updating our regression coefficient. It is an optimization algorithm that we use to train our model. In gradient descent, we take the partial derivative of the cost function wrt to our regression coefficient and multiply with the learning rate alpha and subtract it from our coefficient to adjust our regression coefficient.

For the case of simplicity we will apply gradient descent on only one row element and 
try to estimate our univaraite linear regression coeficient on the basis of
this gradient descent.

\begin {aligned} {J}'b_1 &=\frac{\partial J(b_1,b_0)}{\partial b_1} \\ &= \frac{\partial}{\partial b_1} \left[\frac{1}{n} (y_p-y)^2 \right] \\ &= \frac{2(y_p-y)}{n}\frac{\partial}{\partial b_1}\left [(y_p-y)  \right ] \\ &= \frac{2(y_p-y)}{n}\frac{\partial}{\partial b_1}\left [((xb_1+b_0)-y)  \right ] \\ &= \frac{2(y_p-y)}{n}\left[\frac{\partial(xb_1+b_0)}{\partial b_1}-\frac{\partial(y)}{\partial b_1}\right] \\ &= \frac{2(y_p-y)}{n}\left [ x - 0 \right ] \\ &= \frac{1}{n}(y_p-y)[2x] \end {aligned}

\begin {aligned} {J}'b_0 &=\frac{\partial J(b_1,b_0)}{\partial b_0} \\ &= \frac{\partial}{\partial b_0} \left[\frac{1}{n} (y_p-y)^2 \right] \\ &= \frac{2(y_p-y)}{n}\frac{\partial}{\partial b_0}\left [(y_p-y)  \right ] \\ &= \frac{2(y_p-y)}{n}\frac{\partial}{\partial b}\left [((xW^T+b)-y)  \right ] \\ &= \frac{2(y_p-y)}{n}\left[\frac{\partial(xb_1+b_0)}{\partial b_0}-\frac{\partial(y)}{\partial b_0}\right] \\ &= \frac{2(y_p-y)}{n}\left [ 1 - 0 \right ] \\ &= \frac{1}{n}(y_p-y)[2] \end {aligned}

Since our cost function has two parameters b_1 and b_0  we have taken the derivative of the cost function wrt b_1 and then wrt b_0.

Python function for Gradient Descent.

Python
def grad_fun(x, y, b0, b1, i):
    return sum([
        2*(predict(xi, b0, b1)-yi)*1
        if i == 0
        else 2*(predict(xi, b0, b1)-yi)*xi
        for xi, yi in zip(x, y)
    ])/len(x)

Update Coefficients Of Univariate Linear Regression.

At each iteration (epoch), the values of the regression coefficient are updated by a specific value wrt to the error from the previous iteration. This updation is very crucial and is the crux of the machine learning applications that you write. Updating the coefficients is done by penalizing their value with a fraction of the error that its previous values caused. This fraction is called the learning rate. This defines how fast our model reaches to point of convergence(the point where the error is ideally 0).

 b_i = b_i - \alpha * \left( \frac{\partial}{\partial b} cost(x, y) \right)             

Python
def update_coeff(x, y, b0, b1, i, alpha):
  bi -= alpha * cost_derivative(x, y, b0, b1, i)
  return bi

Stop Iterations

This is the function that is used to specify when the iterations should stop. As per the user, the algorithm stop_iteration generally returns true in the following conditions:

  1. Max Iteration: Model is trained for a specified number of iterations.
  2. Error value: Depending upon the value of the previous error, the algorithm decides whether to continue or stop.
  3. Accuracy: Depending upon the last accuracy of the model, if it is larger than the mentioned accuracy, the algorithm returns True,
  4. Hybrid: This is more often used. This combines more than one above mentioned conditions along with an exceptional break option. The exceptional break is a condition where training continues until when something bad happens. Something bad might include an overflow of results, time constraints exceeded, etc.

Having all the utility functions defined let’s see the pseudo-code followed by its implementation:

 Pseudocode for linear regression:

x, y is the given data.
(b0, b1) <-- (0, 0)
i = 0
while True:
if stop_iteration(i):
break
else:
b0 = update_coeff(x, y, b0, b1, 0, alpha)
b1 = update_coeff(x, y, b0, b1, 1, alpha)

Full Implementation of univariate using Python 

Python
class LinearRegressor:
    def __init__(self, x, y, alpha=0.01, b0=0, b1=0):
        """ 
            x: input feature
            y: result / target
            alpha: learning rate, default is 0.01
            b0, b1: linear regression coefficient.
        """
        self.i = 0
        self.x = x
        self.y = y
        self.alpha = alpha
        self.b0 = b0
        self.b1 = b1
        if len(x) != len(y):
            raise TypeError("""x and y should have same number of rows.""")
            
    def cost_derivative(x, y, b0, b1):
        errors = []
        for x, y in zip(x, y):
            prediction = predict(x, b0, b1)
            expected = y
            difference = prediction-expected
            errors.append(difference)
        mse = sum([error * error for error in errors])/len(errors)
        return mse


    def predict(model, x):
        """Predicts the value of prediction based on 
           current value of regression coefficients
           when input is x"""
        return model.b0 + model.b1 * x

    def grad_fun(model, i):
        x, y, b0, b1 = model.x, model.y, model.b0, model.b1
        predict = model.predict
        return sum([
            2 * (predict(xi) - yi) * 1
            if i == 0
            else (predict(xi) - yi) * xi
            for xi, yi in zip(x, y)
        ]) / len(x)

    def update_coeff(model, i):
        cost_derivative = model.cost_derivative
        if i == 0:
            model.b0 -= model.alpha * cost_derivative(i)
        elif i == 1:
            model.b1 -= model.alpha * cost_derivative(i)

    def stop_iteration(model, max_epochs=1000):
        model.i += 1
        if model.i == max_epochs:
            return True
        else:
            return False

    def fit(model):
        update_coeff = model.update_coeff
        model.i = 0
        while True:
            if model.stop_iteration():
                break
            else:
                update_coeff(0)
                update_coeff(1)

Initializing the Model object 

Python
linearRegressor = LinearRegressor(
    x=[i for i in range(12)],
    y=[2 * i + 3 for i in range(12)],
    alpha=0.03
)
linearRegressor.fit()
print(linearRegressor.predict(12))

Output:

27.00000004287766


Previous Article
Next Article

Similar Reads

The Difference between Linear Regression and Nonlinear Regression Models
areRegression analysis is a fundamental tool in statistical modelling used to understand the relationship between a dependent variable and one or more independent variables. Two primary types of regression models are linear regression and nonlinear regression. This article delves into the key differences between these models, their applications, an
7 min read
Support Vector Regression (SVR) using Linear and Non-Linear Kernels in Scikit Learn
Support vector regression (SVR) is a type of support vector machine (SVM) that is used for regression tasks. It tries to find a function that best predicts the continuous output value for a given input value. SVR can use both linear and non-linear kernels. A linear kernel is a simple dot product between two input vectors, while a non-linear kernel
5 min read
SVM with Univariate Feature Selection in Scikit Learn
Support Vector Machines (SVM) is a powerful machine learning algorithm used for classification and regression analysis. It is based on the idea of finding the optimal boundary between two classes that maximizes the margin between them. However, the challenge with SVM is that it requires a large amount of computational power and is sensitive to the
10 min read
What is Univariate, Bivariate & Multivariate Analysis in Data Visualisation?
Data Visualisation is a graphical representation of information and data. By using different visual elements such as charts, graphs, and maps data visualization tools provide us with an accessible way to find and understand hidden trends and patterns in data. In this article, we are going to see about the univariate, Bivariate & Multivariate An
3 min read
Univariate Time Series Analysis and Forecasting
Time series data is one of the most challenging tasks in machine learning as well as the real-world problems related to data because the data entities not only depend on the physical factors but mostly on the chronological order in which they have occurred. We can forecast a target value in the time series based on a single feature that is univaria
15+ min read
Feature Agglomeration vs Univariate Selection in Scikit Learn
Selecting the most relevant characteristics for a given job is the aim of feature selection, a crucial stage in machine learning. Feature Agglomeration and Univariate Selection are two popular methods for feature selection in Scikit-Learn. These techniques aid in the reduction of dimensionality, increase model effectiveness, and maybe improve model
4 min read
Univariate, Bivariate and Multivariate data and its analysis
In this article,we will be discussing univariate, bivariate, and multivariate data and their analysis. Univariate data: Univariate data refers to a type of data in which each observation or data point corresponds to a single variable. In other words, it involves the measurement or observation of a single characteristic or attribute for each individ
5 min read
How to improve the performance of segmented regression using quantile regression in R?
Segmented regression, also known as piecewise or broken-line regression is a powerful statistical technique used to identify changes in the relationship between a dependent variable and one or more independent variables. Quantile regression, on the other hand, estimates the conditional quantiles of a response variable distribution in the linear mod
8 min read
ML | Multiple Linear Regression using Python
Linear Regression: It is the basic and commonly used type for predictive analysis. It is a statistical approach to modeling the relationship between a dependent variable and a given set of independent variables. These are of two types: Simple linear RegressionMultiple Linear Regression Let's Discuss Multiple Linear Regression using Python. Multiple
6 min read
Solving Linear Regression in Python
Linear regression is a common method to model the relationship between a dependent variable and one or more independent variables. Linear models are developed using the parameters which are estimated from the data. Linear regression is useful in prediction and forecasting where a predictive model is fit to an observed data set of values to determin
4 min read
Linear Regression Implementation From Scratch using Python
Linear Regression is a supervised learning algorithm which is both a statistical and a machine learning algorithm. It is used to predict the real-valued output y based on the given input value x. It depicts the relationship between the dependent variable y and the independent variables xi ( or features ). The hypothetical function used for predicti
4 min read
Locally weighted linear Regression using Python
Locally weighted linear regression is the nonparametric regression methods that combine k-nearest neighbor based machine learning. It is referred to as locally weighted because for a query point the function is approximated on the basis of data near that and weighted because the contribution is weighted by its distance from the query point. Locally
4 min read
Linear Regression (Python Implementation)
This article discusses the basics of linear regression and its implementation in the Python programming language. Linear regression is a statistical method for modeling relationships between a dependent variable with a given set of independent variables. Note: In this article, we refer to dependent variables as responses and independent variables a
15+ min read
Simple Linear Regression in Python
Simple linear regression is a fundamental statistical method used to model the relationship between a dependent variable and a single independent variable. This technique assumes a linear relationship between the two variables, allowing us to predict the dependent variable based on the independent variable's value. In this article, we will explore
6 min read
ML | Boston Housing Kaggle Challenge with Linear Regression
Boston Housing Data: This dataset was taken from the StatLib library and is maintained by Carnegie Mellon University. This dataset concerns the housing prices in the housing city of Boston. The dataset provided has 506 instances with 13 features.The Description of the dataset is taken from the below reference as shown in the table follows: Let's ma
3 min read
ML | Normal Equation in Linear Regression
We know the Linear Regression model is a parameterized model which means that the model's behavior and predictions are determined by a set of parameters or coefficients in the model. However, we use different methods for finding these parameters which give the lowest error on our dataset. In this article, we will read one such article which is the
4 min read
A Practical approach to Simple Linear Regression using R
Simple Linear Regression is a statistical method that allows us to summarize and study relationships between two continuous (quantitative) variables. One variable denoted x is regarded as an independent variable and other one denoted y is regarded as a dependent variable. It is assumed that the two variables are linearly related. Hence, we try to f
9 min read
ML | Multiple Linear Regression (Backward Elimination Technique)
Multiple Linear Regression is a type of regression where the model depends on several independent variables(instead of only on one independent variable as seen in the case of Simple Linear Regression). Multiple Linear Regression has several techniques to build an effective model namely: All-in Backward Elimination Forward Selection Bidirectional El
5 min read
Polynomial Regression for Non-Linear Data - ML
Non-linear data is usually encountered in daily life. Consider some of the equations of motion as studied in physics. Projectile Motion: The height of a projectile is calculated as h = -½ gt2 +ut +ho Equation of motion under free fall: The distance travelled by an object after falling freely under gravity for ‘t’ seconds is ½ g t2. Distance travell
5 min read
Implementation of Locally Weighted Linear Regression
LOESS or LOWESS are non-parametric regression methods that combine multiple regression models in a k-nearest-neighbor-based meta-model. LOESS combines much of the simplicity of linear least squares regression with the flexibility of nonlinear regression. It does this by fitting simple models to localized subsets of the data to build up a function t
3 min read
Assumptions of Linear Regression
Linear regression is the simplest machine learning algorithm of predictive analysis. Linear regression algorithm shows a linear relationship between a dependent (y variable) and one or more independent (x variable) variables hence it is known as linear regression. Since linear regression shows the linear relationship, which means it finds how the v
4 min read
Multiple Linear Regression Model with Normal Equation
Prerequisite: NumPy Consider a data set, area (x1)rooms (x2)age (x3)price (y)2338656215274569244968972954756231768234253107485 let us consider, Here area, rooms, age are features / independent variables and price is the target / dependent variable. As we know the hypothesis for multiple linear regression is given by: [Tex]$h_{\theta}(x)=\theta_{0}
3 min read
Difference between Multilayer Perceptron and Linear Regression
Multi-layer perceptrons (MLP) is an artificial neural network that has 3 or more layers of perceptrons. These layers are- a single input layer, 1 or more hidden layers, and a single output layer of perceptrons. The data flows in a single direction, that is forward, from the input layers-> hidden layer(s) -> output layer. Backpropagation is a
2 min read
Multiple Linear Regression With scikit-learn
In this article, let's learn about multiple linear regression using scikit-learn in the Python programming language. Regression is a statistical method for determining the relationship between features and an outcome variable or result. Machine learning, it's utilized as a method for predictive modeling, in which an algorithm is employed to forecas
8 min read
Non-Linear Regression in R
Non-Linear Regression is a form of regression analysis in which function models observational data is a nonlinear combination with non-linear parameters To perform non-linear regression in R, you can use various functions and packages, including 'nls', 'nlme', and 'mgcv'. You need to provide the equation of the model and the data, and the function
7 min read
PySpark Linear Regression Get Coefficients
In this tutorial series, we are going to cover Linear Regression using Pyspark. Linear Regression is a machine learning algorithm that is used to perform regression methods. Linear Regression is a supervised machine learning algorithm where we know inputs as well as outputs. Loading Dataframe : We will be using the data for "E-commerce Customer Dat
3 min read
How to Plot the Linear Regression in R
In this article, we are going to learn to plot linear regression in R. But, to plot Linear regression, we first need to understand what exactly is linear regression. What is Linear Regression?Linear Regression is a supervised learning model, which computes and predicts the output implemented from the linear relationship the model established based
8 min read
Multiple Linear Regression using R to predict housing prices
Predicting housing prices is a common task in the field of data science and statistics. Multiple Linear Regression is a valuable tool for this purpose as it allows you to model the relationship between multiple independent variables and a dependent variable, such as housing prices. In this article, we'll walk you through the process of performing M
12 min read
Linear Regression Assumptions and Diagnostics using R
Linear regression is a statistical method used to model the relationship between a dependent variable and one or more independent variables. Before interpreting the results of a linear regression analysis in R, it's important to check and ensure that the assumptions of linear regression are met. Assumptions of linear regression include linearity, i
7 min read
7 Steps to Run a Linear Regression Analysis using R
Linear Regression is a useful statistical tool for modelling the relationship between a dependent variable and one or more independent variables. It is widely used in many disciplines, such as science, medicine, economics, and education. For instance, several areas of education employ linear regression to estimate student performance or identify th
9 min read
Article Tags :
Practice Tags :