The Wayback Machine - https://web.archive.org/web/20240930184504/https://www.geeksforgeeks.org/ml-multiple-linear-regression-using-python/
Open In App

ML | Multiple Linear Regression using Python

Last Updated : 25 Jan, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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: 

  1. Simple linear Regression
  2. Multiple Linear Regression

Let’s Discuss Multiple Linear Regression using Python.

Multiple Linear Regression attempts to model the relationship between two or more features and a response by fitting a linear equation to observed data. The steps to perform multiple linear Regression are almost similar to that of simple linear Regression. The Difference Lies in the evaluation. We can use it to find out which factor has the highest impact on the predicted output and how different variables relate to each other.
 

Here : Y = b0 + b1 * x1 + b2 * x2 + b3 * x3 + …… bn * xn 
Y = Dependent variable and x1, x2, x3, …… xn = multiple independent variables 

Assumption of Regression Model : 

  • Linearity: The relationship between dependent and independent variables should be linear.
  • Homoscedasticity: Constant variance of the errors should be maintained.
  • Multivariate normality: Multiple Regression assumes that the residuals are normally distributed.
  • Lack of Multicollinearity: It is assumed that there is little or no multicollinearity in the data.

Dummy Variable:

As we know in the Multiple Regression Model we use a lot of categorical data. Using Categorical Data is a good method to include non-numeric data into the respective Regression Model. Categorical Data refers to data values that represent categories-data values with the fixed and unordered number of values, for instance, gender(male/female). In the regression model, these values can be represented by Dummy Variables. 
These variables consist of values such as 0 or 1 representing the presence and absence of categorical values. 
 

Dummy Variable Trap:
The Dummy Variable Trap is a condition in which two or more are Highly Correlated. In the simple term, we can say that one variable can be predicted from the prediction of the other. The solution of the Dummy Variable Trap is to drop one of the categorical variables. So if there are m Dummy variables then m-1 variables are used in the model. 

 D2 = D1-1   
 Here D2, D1 = Dummy Variables

Method of Building Models : 

  • All-in
  • Backward-Elimination
  • Forward Selection
  • Bidirectional Elimination
  • Score Comparison

Backward-Elimination :

Step #1: Select a significant level to start in the model. 
Step #2: Fit the full model with all possible predictors. 
Step #3: Consider the predictor with the highest P-value. If P > SL go to STEP 4, otherwise the model is Ready. 
Step #4: Remove the predictor. 
Step #5: Fit the model without this variable.
 

Forward-Selection :

Step #1 : Select a significance level to enter the model(e.g. SL = 0.05) 
Step #2: Fit all simple regression models y~ x(n). Select the one with the lowest P-value. 
Step #3: Keep this variable and fit all possible models with one extra predictor added to the one(s) you already have. 
Step #4: Consider the predictor with the lowest P-value. If P < SL, go to Step #3, otherwise the model is Ready.
 

Steps Involved in any Multiple Linear Regression Model

Step #1: Data Pre Processing 

  1. Importing The Libraries.
  2. Importing the Data Set.
  3. Encoding the Categorical Data.
  4. Avoiding the Dummy Variable Trap.
  5. Splitting the Data set into Training Set and Test Set.

Step #2: Fitting Multiple Linear Regression to the Training set 
Step #3: Predict the Test set results.
 

Code 1 : 

Python3




import numpy as np
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
 
def generate_dataset(n):
    x = []
    y = []
    random_x1 = np.random.rand()
    random_x2 = np.random.rand()
    for i in range(n):
        x1 = i
        x2 = i/2 + np.random.rand()*n
        x.append([1, x1, x2])
        y.append(random_x1 * x1 + random_x2 * x2 + 1)
    return np.array(x), np.array(y)
 
x, y = generate_dataset(200)
 
mpl.rcParams['legend.fontsize'] = 12
 
fig = plt.figure()
ax = fig.add_subplot(projection ='3d')
 
ax.scatter(x[:, 1], x[:, 2], y, label ='y', s = 5)
ax.legend()
ax.view_init(45, 0)
 
plt.show()


Output: 
 

Code 2: 

Python3




def mse(coef, x, y):
    return np.mean((np.dot(x, coef) - y)**2)/2
 
 
def gradients(coef, x, y):
    return np.mean(x.transpose()*(np.dot(x, coef) - y), axis=1)
 
 
def multilinear_regression(coef, x, y, lr, b1=0.9, b2=0.999, epsilon=1e-8):
    prev_error = 0
    m_coef = np.zeros(coef.shape)
    v_coef = np.zeros(coef.shape)
    moment_m_coef = np.zeros(coef.shape)
    moment_v_coef = np.zeros(coef.shape)
    t = 0
 
    while True:
        error = mse(coef, x, y)
        if abs(error - prev_error) <= epsilon:
            break
        prev_error = error
        grad = gradients(coef, x, y)
        t += 1
        m_coef = b1 * m_coef + (1-b1)*grad
        v_coef = b2 * v_coef + (1-b2)*grad**2
        moment_m_coef = m_coef / (1-b1**t)
        moment_v_coef = v_coef / (1-b2**t)
 
        delta = ((lr / moment_v_coef**0.5 + 1e-8) *
                 (b1 * moment_m_coef + (1-b1)*grad/(1-b1**t)))
 
        coef = np.subtract(coef, delta)
    return coef
 
 
coef = np.array([0, 0, 0])
c = multilinear_regression(coef, x, y, 1e-1)
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
 
ax.scatter(x[:, 1], x[:, 2], y, label='y',
           s=5, color="dodgerblue")
 
ax.scatter(x[:, 1], x[:, 2], c[0] + c[1]*x[:, 1] + c[2]*x[:, 2],
           label='regression', s=5, color="orange")
 
ax.view_init(45, 0)
ax.legend()
plt.show()


Output: 
 

Multiple linear regression is a statistical method used to model the relationship between multiple independent variables and a single dependent variable. In Python, the scikit-learn library provides a convenient implementation of multiple linear regression through the LinearRegression class.

Here’s an example of how to use LinearRegression to fit a multiple linear regression model in Python:

Python3




from sklearn.linear_model import LinearRegression
import numpy as np
 
# Assume you have independent variables X and a dependent variable y
X = np.array([[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]])
y = np.array([1, 2, 3, 4])
 
# Create an instance of the LinearRegression class
reg = LinearRegression()
 
# Fit the model to the data
reg.fit(X, y)
 
# Print the coefficients of the model
print(reg.coef_)


This will output the coefficients of the multiple linear regression model, which can be used to make predictions about the dependent variable given new independent variable values.

It is important to mention that Linear Regression model should be used under certain assumption, such as Linearity, Homoscedasticity, Independence of errors, Normality of errors, and no multicollinearity, if these assumptions are not met, you should consider using other techniques or transforming your data.
 



Previous Article
Next Article

Similar Reads

ML | Linear Regression vs Logistic Regression
Linear Regression is a machine learning algorithm based on supervised regression algorithm. Regression models a target prediction value based on independent variables. It is mostly used for finding out the relationship between variables and forecasting. Different regression models differ based on – the kind of relationship between the dependent and
3 min read
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
Multiple Linear Regression using R
Prerequisite: Simple Linear-Regression using RLinear Regression: It is the basic and commonly used type for predictive analysis. It is a statistical approach for 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 Mul
3 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
Multiple linear regression analysis of Boston Housing Dataset using R
In this article, we are going to perform multiple linear regression analyses on the Boston Housing dataset using the R programming language. What is Multiple Linear Regression?Multiple Linear Regression is a supervised learning model, which is an extension of simple linear regression, where instead of just one independent variable, we have multiple
13 min read
Multiple linear regression using R for the Real estate data set
Multiple linear regression is widely used in machine learning and data science. In this article, We will discuss the Multiple linear regression by building a step-by-step project on a Real estate data set. Multiple linear regressionMultiple Linear Regression is a statistical method used to model the relationship between a dependent variable (or tar
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
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
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
Missing Coefficients in Linear Regression with Multiple Categorical Variables in R
In linear regression, dealing with multiple categorical variables can lead to challenges, especially when some coefficients are missing from the summary output. This typically occurs due to the reference level handling in categorical variables. Understanding and addressing these issues is crucial for accurate model interpretation in the R Programmi
5 min read
ANOVA vs multiple linear regression?
In the realm of statistical analysis, ANOVA (Analysis of Variance) and multiple linear regression are two powerful techniques used to examine relationships within data. Although they share similarities, such as dealing with variance and multiple predictors, their applications and interpretations differ significantly. This article delves into the co
4 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
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
Python | Linear Regression using sklearn
Prerequisite: Linear Regression Linear Regression is a machine learning algorithm based on supervised learning. It performs a regression task. Regression models a target prediction value based on independent variables. It is mostly used for finding out the relationship between variables and forecasting. Different regression models differ based on –
3 min read
Linear Regression using PyTorch
Linear Regression is a very commonly used statistical method that allows us to determine and study the relationship between two continuous variables. The various properties of linear regression and its Python implementation have been covered in this article previously. Now, we shall find out how to implement this in PyTorch, a very popular deep lea
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
Pyspark | Linear regression with Advanced Feature Dataset using Apache MLlib
Ames Housing Data: The Ames Housing dataset was compiled by Dean De Cock for use in data science education and expanded version of the often-cited Boston Housing dataset. The dataset provided has 80 features and 1459 instances. Dataset description is as below: For demo few columns are displayed but there are a lot more columns are there in the data
4 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
Hierarchical linear regression using R
Linear Regression model is used to establish a connection between two or more variables. These variables are either dependent or independent. Linear Regression In R Programming Language is used to give predictions based on the given data about a particular topic, It helps us to have valuable insights and give conclusions that help us in many future
9 min read
Box Office Revenue Prediction Using Linear Regression in ML
When a movie is produced then the director would certainly like to maximize his/her movie's revenue. But can we predict what will be the revenue of a movie by using its genre or budget information? This is exactly what we'll learn in this article, we will learn how to implement a machine learning algorithm that can predict a box office revenue by u
5 min read
ML | Rainfall prediction using Linear regression
Rainfall prediction is a common application of machine learning, and linear regression is a simple and effective technique that can be used for this purpose. In this task, the goal is to predict the amount of rainfall based on historical data. Linear regression is a supervised learning algorithm that is used to model the relationship between a depe
7 min read
Linear Regression using Turicreate
Linear Regression is a method or approach for Supervised Learning.Supervised Learning takes the historical or past data and then train the model and predict the things according to the past results.Linear Regression comes from the word 'Linear' and 'Regression'.Regression concept deals with predicting the future using the past data.Linear means the
2 min read
Step-by-Step Guide to Modeling Time Series Data Using Linear Regression
Time series data is a sequence of data points collected or recorded at specific time intervals. Modeling time series data is crucial in various fields such as finance, economics, environmental science, and many others. One of the simplest yet powerful methods to model time series data is using linear regression. This article will delve into the tec
6 min read
Reason for Using RMSE Instead of MSE in Linear Regression
Answer: RMSE is preferred over MSE in linear regression because it is in the same units as the response variable, making interpretation easier.In linear regression analysis, both the Mean Squared Error (MSE) and the Root Mean Squared Error (RMSE) serve as measures to evaluate model performance, specifically regarding how well the model predicts the
2 min read
Interpreting the results of Linear Regression using OLS Summary
This article is to tell you the whole interpretation of the regression summary table. There are many statistical softwares that are used for regression analysis like Matlab, Minitab, spss, R etc. but this article uses python. The Interpretation is the same for other tools as well. This article needs the basics of statistics including basic knowledg
6 min read
Curve Fitting using Linear and Nonlinear Regression
Curve fitting, a fundamental technique in data analysis and machine learning, plays a pivotal role in modelling relationships between variables, predicting future outcomes, and uncovering underlying patterns in data. In this article, we delve into the intricacies of linear and nonlinear regression, exploring their principles, methodologies, applica
4 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