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

Python | Linear Regression using sklearn

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

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 – the kind of relationship between the dependent and independent variables, they are considering and the number of independent variables being used. This article is going to demonstrate how to use the various Python libraries to implement linear regression on a given dataset. We will demonstrate a binary linear model as this will be easier to visualize. In this demonstration, the model will use Gradient Descent to learn. You can learn about it here. 

Step 1: Importing all the required libraries 

Python3




import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn import preprocessing, svm
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression


Step 2: Reading the dataset:

Python3




df = pd.read_csv('bottle.csv')
df_binary = df[['Salnty', 'T_degC']]
  
# Taking only the selected two attributes from the dataset
df_binary.columns = ['Sal', 'Temp']
#display the first 5 rows
df_binary.head()


Output:

  

Step 3: Exploring the data scatter 

Python3




#plotting the Scatter plot to check relationship between Sal and Temp
sns.lmplot(x ="Sal", y ="Temp", data = df_binary, order = 2, ci = None)
plt.show()


Output:   

Step 4: Data cleaning 

Python3




# Eliminating NaN or missing input numbers
df_binary.fillna(method ='ffill', inplace = True)


  Step 5: Training our model 

Python3




X = np.array(df_binary['Sal']).reshape(-1, 1)
y = np.array(df_binary['Temp']).reshape(-1, 1)
  
# Separating the data into independent and dependent variables
# Converting each dataframe into a numpy array 
# since each dataframe contains only one column
df_binary.dropna(inplace = True)
  
# Dropping any rows with Nan values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25)
  
# Splitting the data into training and testing data
regr = LinearRegression()
  
regr.fit(X_train, y_train)
print(regr.score(X_test, y_test))


Output:

 

Step 6: Exploring our results 

Python3




y_pred = regr.predict(X_test)
plt.scatter(X_test, y_test, color ='b')
plt.plot(X_test, y_pred, color ='k')
  
plt.show()
# Data scatter of predicted values


Output:

 

The low accuracy score of our model suggests that our regressive model has not fit very well with the existing data. This suggests that our data is not suitable for linear regression. But sometimes, a dataset may accept a linear regressor if we consider only a part of it. Let us check for that possibility.   

Step 7: Working with a smaller dataset 

Python3




df_binary500 = df_binary[:][:500]
    
# Selecting the 1st 500 rows of the data
sns.lmplot(x ="Sal", y ="Temp", data = df_binary500,
                               order = 2, ci = None)


Output:

 

We can already see that the first 500 rows follow a linear model. Continuing with the same steps as before. 

Python3




df_binary500.fillna(method ='fill', inplace = True)
  
X = np.array(df_binary500['Sal']).reshape(-1, 1)
y = np.array(df_binary500['Temp']).reshape(-1, 1)
  
df_binary500.dropna(inplace = True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25)
  
regr = LinearRegression()
regr.fit(X_train, y_train)
print(regr.score(X_test, y_test))


Output:

 

Python3




y_pred = regr.predict(X_test)
plt.scatter(X_test, y_test, color ='b')
plt.plot(X_test, y_pred, color ='k')
  
plt.show()


Output:

Step 8: Evaluation Metrics For Regression

At last, we check the performance of the Linear Regression model with help of evaluation metrics. For Regression algorithms we widely use mean_absolute_error, and mean_squared_error metrics to check the model performance. 

Python3




from sklearn.metrics import mean_absolute_error,mean_squared_error
  
mae = mean_absolute_error(y_true=y_test,y_pred=y_pred)
#squared True returns MSE value, False returns RMSE value.
mse = mean_squared_error(y_true=y_test,y_pred=y_pred) #default=True
rmse = mean_squared_error(y_true=y_test,y_pred=y_pred,squared=False)
  
print("MAE:",mae)
print("MSE:",mse)
print("RMSE:",rmse)


Output:

MAE: 0.7927322046360309
MSE: 1.0251137190180517
RMSE: 1.0124789968281078


Similar Reads

Python Sklearn – sklearn.datasets.load_breast_cancer() Function
In this article, we are going to see how to convert sklearn dataset to a pandas dataframe in Python. Sklearn is a python library that is used widely for data science and machine learning operations. Sklearn library provides a vast list of tools and functions to train machine learning models. The library is available via pip install. pip install sci
2 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
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
Python | Decision Tree Regression using sklearn
Decision Tree is a decision-making tool that uses a flowchart-like tree structure or is a model of decisions and all of their possible results, including outcomes, input costs, and utility.Decision-tree algorithm falls under the category of supervised learning algorithms. It works for both continuous as well as categorical output variables. The bra
4 min read
Partial Least Squares Regression (PLSRegression) using Sklearn
Partial least square regression is a Machine learning Algorithm used for modelling the relationship between independent and dependent variables. This is mainly used when there are many interrelated independent variables. It is more commonly used in regression and latent variable modelling. It finds the directions (latent variables) in the independe
8 min read
Linear and Quadratic Discriminant Analysis using Sklearn
Linear Discriminant Analysis (LDA) and Quadratic Discriminant Analysis (QDA) are two well-known classification methods that are used in machine learning to find patterns and put things into groups. They are especially helpful when you have labeled data and want to classify new observations notes into pre-defined categories. In this we will implemen
5 min read
What is the default threshold in Sklearn logistic regression?
Logistic regression is a popular machine-learning algorithm used for classification problems. It is commonly used in various applications such as marketing, finance, healthcare, etc. One of the critical parameters in logistic regression is the threshold, which determines the class label of the prediction. In this article, we will discuss the defaul
8 min read
Understanding Kernel Ridge Regression With Sklearn
Kernel ridge regression (KRR) is a powerful technique in scikit-learn for tackling regression problems, particularly when dealing with non-linear relationships between features and the target variable.  This technique allows for the modeling of complex, nonlinear relationships between variables, making it a valuable asset in data analysis. This art
7 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
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
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
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
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
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
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
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
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
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 (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
Linear vs. Non-linear Classification: Analyzing Differences Using the Kernel Trick
Classification is a fundamental task in machine learning, where the goal is to assign a class label to a given input. There are two primary approaches to classification: linear and non-linear. Support Vector Machines (SVMs) are a popular choice for classification tasks due to their robustness and effectiveness. SVMs can handle both linear and non-l
8 min read
Mathematical explanation for Linear Regression working
Suppose we are given a dataset: Given is a Work vs Experience dataset of a company and the task is to predict the salary of a employee based on his / her work experience. This article aims to explain how in reality Linear regression mathematically works when we use a pre-defined function to perform prediction task. Let us explore how the stuff work
1 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
Article Tags :
Practice Tags :