×

How to plot multiple linear regression in Python

This article lets us look into linear regression in Python and how we can plot multiple linear regressions in it.

Linear regression

One of the simplest and most widely used Machine Learning techniques is linear regression. It is a statistical technique for performing predictive analysis. This algorithm works on the assumption it takes based on the types of both variables and takes a linear relationship. We can calculate the model's necessary coefficients to make decisions based on the unseen data. This process can be done only if a relationship exists between the variables.

Plotting data is nothing but visualizing the given data into a graph. It is always better to plot pictorial data to comprehend it in a better way. Before applying multiple regressions, we have to check if there are any relationships between all features. We will use the pairplot() method from the seaborn package to plot the relationship between all the features. This pairplot() will produce a histogram along with a scatter plot mixing all the features.

To plot these regressions, we will need multiple python libraries like NumPy, Pandas, sklearn, matplotlib, etc.

You can use the below code to import all these libraries:

# Importing the required methods and modules for plotting 
  
# all required libraries   
import pandas as pd  
import warnings  
 import numpy as np  


# For data visualizing   
import seaborn as sns  
import matplotlib.pyplot as plt  
from mpl_toolkits.mplot3d import Axes3D  
%matplotlib inline 


 
# For building the required model  
from sklearn import linear_model  
  

Of this, we imported all the libraries required.

We use this dataset for further codes:7420         4        2

 costareabedroomfloor
012300000742532
115250000896843
213250000999934
315215000754053
413410000743042

By looking at the below code, we will get the histogram and scatter plot

# Visualizing the relationships between features using pair plots  
sns.pairplot(data = housing, height = 3) 

Output:

How to plot multiple linear regression in Python

Here we used the pairplot() function, and we can also see that the first row of this graph is a linear relationship between the price and area features of the dataset. We can see the scatter plot of the rest of all variables is random, and there is no relationship between them. We should always select only one multiple independent features having a relation.

Building a Multiple Linear Regression Model:

To build a regression model, we can use every feature where there will be no relationship with collinearity among the elements, we can use all features to build a model. In this code, we will use LinearRegression() function from sklearn.

Example

# Building a Multiple Linear Regression Model  
  
# Set the independent and dependent features of the data set 
X = housing.iloc[:, 1:].values  
y = housing.iloc[:, 0].values  
  
  
# Initializing the model class from the sklearn package and fitting our data into it  
reg = linear_model.LinearRegression()  
reg.fit(X, y)  
  
# Printing  intercept and the coefficients of the regression equation  
print('Intercepts: ', reg.intercept_)  
print('Coefficient array: ', reg.coef_)  

Output:

How to plot multiple linear regression in Python

We can also convert this model into a 3-dimensional graph. To convert that, we use the below code where all the data points will be in grey color dots in the chart, and the blue plane represents the linear model.

Example

# Preparing the required data  
independent = housing[['area', 'bedroom']].values.reshape(-1,4)  
dependent = housing['cost']  
  
# Creating a variable for every dimension  
a = independent[:, 0]  
b = independent[:, 1]  
c = dependent  
  
a_range = np.linspace(5, 10, 35)    
b_range = np.linspace(3, 6, 35)   
a1_range = np.linspace(3, 6, 35)  
a_range, a_range, a1_range = np.meshgrid(a_range, b_range, a1_range)  
viz = np.array([a_range.flatten(), b_range.flatten(), a1_range.flatten()]).T  
  
# predicting price values by using the linear regression model built above  
predictions = reg.predict(viz)  
  
# Evaluating the model by using the R2 square of the model  
r2 = reg.score(A, B)  
  
# Ploting the model for visualization  
plt.style.use('fivethirtyeight')  
  
# Initializing a matplotlib figure  
fig = plt.figure(figsize = (15, 6))  
  
axis1 = fig.add_subplot(131, projection = '3d')  
axis2 = fig.add_subplot(132, projection = '3d')  
axis3 = fig.add_subplot(133, projection = '3d')  
  
axis = [axis1, axis2, axis3]  
  
for ax in axis:  
    ax.plot(a, b, c, color='k', zorder = 10, linestyle = 'none', marker = 'o', alpha = 0.1)  
    ax.scatter(a_range.flatten(), b_range.flatten(), predictions, facecolor = (0,0,0,0), s = 20, edgecolor = '#70b3f0')  
    ax.set_alabel('Area', fontsize = 10, labelpad = 10)  
    ax.set_blabel('Bedrooms', fontsize = 10, labelpad = 10)  
    ax.set_clabel('Prices', fontsize = 10, labelpad = 10)  
    ax.locator_params(nbins = 3, axis = 'a')  
    ax.locator_params(nbins = 3, axis = 'a')  
  
axis1.view_init(elev=25, azim=-60)  
axis2.view_init(elev=15, azim=15)  
axis3.view_init(elev=25, azim=60)  
  
fig.suptitle(f'Multi-Linear Regression Model Visualization (R2 = {r2}, ("fontsize"))

Output:

How to plot multiple linear regression in Python

Conclusion:

In this way, we plot multiple linear regression models in Python.


Related Topics

Python list() | List class in Python

The list() class in Python creates a list object where the list object is a collection which is ordered and changeable. Syntax class list([iterable]) Parameter Iterable: It is a required parameter which represents a sequence, collection...

1 minute read.

Uint8 Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Python Infinity

Introduction We will discover how to define an infinite number in Python in this tutorial. Infinity, as we all know, is a value that cannot be defined and can either be...

5 minutes read.

Python String isupper() method

Python String isupper() method The String.isupper() method in Python returns a boolean value ‘true’ if all cased characters in the string are uppercase else for any other value is returns false. Syntax String.isupper() Parameter NA Return This...

2 minutes read.

What is Collaborative Filtering in ML, Python

Introduction Contents recommendation is a useful tactic for almost any specific technology looking to increase interest, but it frequently calls for a lot of user data and perhaps laborious content tagging...

3 minutes read.

Python memoryview() Function

Python memoryview() Function The memoryview() function in Python returns a memory view object from a specified object. Syntax memoryview(obj) Parameter obj: This parameter represents a Bytes object or a bytearray object. Return This function returns a “memory view” object...

1 minute read.

What does base case mean in recursion

Base cases and recursive stages are used to define recursive functions. In a primary subject, we compute the outcome right away, given the function call's arguments. In a recursive step, we...

4 minutes read.

Python Set issuperset() method

Python Set issuperset() method The set.issuperset() method in Python returns a boolean value True if all items in the specified set exists in the original set, else it returns False. Syntax set.issuperset (set1) Parameter set- This parameter represents the...

2 minutes read.

Multiprocessing in python

The word multiprocessing is used to compute the operation in which more than two processors run simultaneously with more than one central processor. The computer's performance increases gradually. Multiprocessing is...

6 minutes read.

How to Install Python

Python Installation Guide Step by Step Installing Python is quite simple and easy. In this tutorial, we will show stepwise procedure to install Python and set up the Python environment in different...

2 minutes read.

How to clear screen in Python?

How to clear screen in python There are times when we execute our program and it results in an unexpected output. The obtained result can contain some kind of garbage values...

4 minutes read.

Python Switch Case

What is a Switch Case Statement? In the programming languages, a switch statement is a logical loop or syntax that tests the variable's value and compares it with multiple cases. Once...

3 minutes read.

Python sort() function

Python provides many built-in functions for solving many problems that arise in different situations in programs. One of such methods is the sort () method. In this article, the syntax...

4 minutes read.

Python AIOHTTP

Python 3.5 introduced some new syntax that makes it simpler for developers to make asynchronous programmes and packages. Aiohttp, an HTTP client/server for asyncio, is one such package. In essence,...

3 minutes read.

Python Logical Operators

In python, there are many operators which we use in our program. Operators are used in manipulating a particular value or operand. Logical operators are used mainly to evaluate an...

7 minutes read.

Python Interface

When creating an application, it is important to continuously keep track of its changes. As an application grows, sometimes it gets hard to manage its updates and changes. Often, you...

4 minutes read.

Python Set clear() Method

Python Set clear() Method The set.clear() method removes all the elements from the set. Syntax set.clear() Parameter NA Return None Example 1 # Python program explaining # the set.clear() method # initializing the set fruits = {"watermelon", "banana", "apple"} # printing the set...

2 minutes read.

Image to Text in python

Processing out information from an image is a very big task in all the fields of work such as in development and business sector. The process of converting an electronical...

3 minutes read.

Python while loop

Loops are essential in Python or any other programming language, as they help to execute a block of code repetitively. Sometimes, situations arise where you would need to use a piece of code...

2 minutes read.

iobase Python

All I/O flow classes derive from this conceptual base class. Derived classes will have to execute several of the class's abstract data types. The loop method is supported by all members of...

4 minutes read.