The Wayback Machine - https://web.archive.org/web/20241125065509/https://www.geeksforgeeks.org/python-implementation-of-polynomial-regression/
Open In App

Implementation of Polynomial Regression

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

Polynomial Regression is a form of linear regression in which the relationship between the independent variable x and dependent variable y is modelled as an nth-degree polynomial. Polynomial regression fits a nonlinear relationship between the value of x and the corresponding conditional mean of y, denoted E(y | x). In this article, we’ll go in-depth about polynomial regression.

What is a Polynomial Regression? 

  • There are some relationships that a researcher will hypothesize is curvilinear. Clearly, such types of cases will include a polynomial term.
  • Inspection of residuals. If we try to fit a linear model to curved data, a scatter plot of residuals (Y-axis) on the predictor (X-axis) will have patches of many positive residuals in the middle. Hence in such a situation, it is not appropriate.
  • An assumption in the usual multiple linear regression analysis is that all the independent variables are independent. In the polynomial regression model, this assumption is not satisfied.

Why Polynomial Regression?

Polynomial regression is a type of regression analysis used in statistics and machine learning when the relationship between the independent variable (input) and the dependent variable (output) is not linear. While simple linear regression models the relationship as a straight line, polynomial regression allows for more flexibility by fitting a polynomial equation to the data.

When the relationship between the variables is better represented by a curve rather than a straight line, polynomial regression can capture the non-linear patterns in the data.

How does a Polynomial Regression work?

If we observe closely then we will realize that to evolve from linear regression to polynomial regression. We are just supposed to add the higher-order terms of the dependent features in the feature space. This is sometimes also known as feature engineering but not exactly.

When the relationship is non-linear, a polynomial regression model introduces higher-degree polynomial terms.

The general form of a polynomial regression equation of degree n is:

y=β_0+β_1x+β_2x^2+…+β_nx^n +ϵ

where,

  • y is the dependent variable.
  • x is the independent variable.
  • β_0,β_1,…,β_n     ​ are the coefficients of the polynomial terms.
  • n is the degree of the polynomial.
  • ϵ represents the error term.

The basic goal of regression analysis is to model the expected value of a dependent variable y in terms of the value of an independent variable x. In simple linear regression, we used the following equation – 

y = a + bx + e

Here y is a dependent variable, a is the y-intercept, b is the slope and e is the error rate. In many cases, this linear model will not work out For example if we analyze the production of chemical synthesis in terms of the temperature at which the synthesis takes place in such cases we use a quadratic model.y = a + b_1x + b_2x^2 + e

Here,

  • y is the dependent variable on x
  • a is the y-intercept and e is the error rate.

In general, we can model it for the nth value. y = a + b_1x + b_2x^2 +....+ b_nx^n

Since the regression function is linear in terms of unknown variables, hence these models are linear from the point of estimation. Hence through the Least Square technique, response value (y) can be computed.

By including higher-degree terms (quadratic, cubic, etc.), the model can capture the non-linear patterns in the data.

  1. The choice of the polynomial degree (n) is a crucial aspect of polynomial regression. A higher degree allows the model to fit the training data more closely, but it may also lead to overfitting, especially if the degree is too high. Therefore, the degree should be chosen based on the complexity of the underlying relationship in the data.
  2. The polynomial regression model is trained to find the coefficients that minimize the difference between the predicted values and the actual values in the training data.
  3. Once the model is trained, it can be used to make predictions on new, unseen data. The polynomial equation captures the non-linear patterns observed in the training data, allowing the model to generalize to non-linear relationships.

Polynomial Regression Real-Life Example

Let’s consider a real-life example to illustrate the application of polynomial regression. Suppose you are working in the field of finance, and you are analyzing the relationship between the years of experience (in years) an employee has and their corresponding salary (in dollars). You suspect that the relationship might not be linear and that higher degrees of the polynomial might better capture the salary progression over time.

Years of Experience

Salary (in dollars)

1

50,000

2

55,000

3

65,000

4

80,000

5

110,000

6

150,000

7

200,000

Now, let’s apply polynomial regression to model the relationship between years of experience and salary. We’ll use a quadratic polynomial (degree 2) for this example.

The quadratic polynomial regression equation is:

Salary=β_0+β_1     ×Experience+β_2     ​×Experience^2+ϵ

Now, to find the coefficients that minimize the difference between the predicted salaries and the actual salaries in the dataset we can use a method of least squares. The objective is to minimize the sum of squared differences between the predicted values and the actual values.

Polynomial Regression implementations using Python

To get the Dataset used for the analysis of Polynomial Regression, click here. Import the important libraries and the dataset we are using to perform Polynomial Regression. 

Python libraries make it very easy for us to handle the data and perform typical and complex tasks with a single line of code.

  • Pandas – This library helps to load the data frame in a 2D array format and has multiple functions to perform analysis tasks in one go.
  • Numpy – Numpy arrays are very fast and can perform large computations in a very short time.
  • Matplotlib/Seaborn – This library is used to draw visualizations.
  • Sklearn – This module contains multiple libraries having pre-implemented functions to perform tasks from data preprocessing to model development and evaluation.

Python3

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
 
# Importing the dataset
datas = pd.read_csv('data.csv')
datas

                    

Output:

Printing the head of a pandas dataframe.

First Five rows of the dataset

 Our feature variable that is X will contain the Column between 1st and the target variable that is y will contain the 2nd column. 

Python3

X = datas.iloc[:, 1:2].values
y = datas.iloc[:, 2].values

                    

Now let’s fit a linear regression model on the data at hand.

Python3

# Features and the target variables
X = datas.iloc[:, 1:2].values
y = datas.iloc[:, 2].values
 
# Fitting Linear Regression to the dataset
from sklearn.linear_model import LinearRegression
lin = LinearRegression()
 
lin.fit(X, y)

                    

Fitting the Polynomial Regression model on two components X and y. 

Python3

# Fitting Polynomial Regression to the dataset
from sklearn.preprocessing import PolynomialFeatures
 
poly = PolynomialFeatures(degree=4)
X_poly = poly.fit_transform(X)
 
poly.fit(X_poly, y)
lin2 = LinearRegression()
lin2.fit(X_poly, y)

                    

In this step, we are Visualising the Linear Regression results using a scatter plot.

Python3

# Visualising the Linear Regression results
plt.scatter(X, y, color='blue')
 
plt.plot(X, lin.predict(X), color='red')
plt.title('Linear Regression')
plt.xlabel('Temperature')
plt.ylabel('Pressure')
 
plt.show()

                    

Output:

Scatter plot of feature and the target variable.

Scatter plot of feature and the target variable.

Visualize the Polynomial Regression results using a scatter plot.

Python3

# Visualising the Polynomial Regression results
plt.scatter(X, y, color='blue')
 
plt.plot(X, lin2.predict(poly.fit_transform(X)),
         color='red')
plt.title('Polynomial Regression')
plt.xlabel('Temperature')
plt.ylabel('Pressure')
 
plt.show()

                    

Output:

Implementation of Polynomial Regression

Implementation of Polynomial Regression

Predict new results with both Linear and Polynomial Regression. Note that the input variable must be in a Numpy 2D array.

Python3

# Predicting a new result with Linear Regression
# after converting predict variable to 2D array
pred = 110.0
predarray = np.array([[pred]])
lin.predict(predarray)

                    

Output:

array([0.20675333])

Python3

# Predicting a new result with Polynomial Regression
# after converting predict variable to 2D array
pred2 = 110.0
pred2array = np.array([[pred2]])
lin2.predict(poly.fit_transform(pred2array))

                    

Output:

array([0.43295877])

Overfitting Vs Under-fitting

While dealing with the polynomial regression one thing that we face is the problem of overfitting this happens because while we increase the order of the polynomial regression to achieve better and better performance model gets overfit on the data and does not perform on the new data points.

Due to this reason only while using the polynomial regression, do we try to penalize the weights of the model to regularize the effect of the overfitting problem. Regularization techniques like Lasso regression and Ridge regression methodologies are used whenever we deal with a situation in which the model may overfit the data at hand.

Bias Vs Variance Tradeoff

This technique is the generalization of the approach that is used to avoid the problem of overfitting and underfitting. Here as well this technique helps us to avoid the problem of overfitting by helping us select the appropriate value for the degree of the polynomial we are trying to fit our data on. For example, this is achieved when after increasing the degree of polynomial after a certain level the gap between the training and the validation metrics starts increasing.

Application of Polynomial Regression

The reason behind the vast use cases of the polynomial regression is that approximately all of the real-world data is non-linear in nature and hence when we fit a non-linear model on the data or a curvilinear regression line then the results that we obtain are far better than what we can achieve with the standard linear regression. Some of the use cases of the Polynomial regression are as stated below: 

  • The growth rate of tissues.
  • Progression of disease epidemics
  • Distribution of carbon isotopes in lake sediments

Advantages & Disadvantages of using Polynomial Regression

Advantages of using Polynomial Regression

  • A broad range of functions can be fit under it.
  • Polynomial basically fits a wide range of curvatures.
  • Polynomial provides the best approximation of the relationship between dependent and independent variables.

Disadvantages of using Polynomial Regression 

  • These are too sensitive to outliers.
  • The presence of one or two outliers in the data can seriously affect the results of nonlinear analysis.
  • In addition, there are unfortunately fewer model validation tools for the detection of outliers in nonlinear regression than there are for linear regression.

Conclusion

Polynomial regression, a versatile tool, finds applications in diverse domains. While addressing non-linear relationships, it requires careful consideration of overfitting and model complexity.

Frequently Asked Questions(FAQs)

1.What is a real life example of polynomial regression?

Predicting car fuel efficiency based on engine power—capturing non-linear patterns in the relationship.

2.What is polynomial regression pipeline?

A sequence of data processing steps, like polynomial feature creation and linear regression, streamlining polynomial regression modeling.

3.What is polynomial regression Excel?

Excel can perform polynomial regression using the “LINEST” function or the “Trendline” feature in a scatter plot.

4.What is polynomial regression with example?

Modeling stock prices over time using a quadratic polynomial to capture potential non-linear trends in the data.

5.What is the purpose of polynomial regression?

Captures non-linear relationships in data, providing a flexible model for complex patterns beyond linear regression’s scope.




Previous Article
Next Article

Similar Reads

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
Polynomial Regression ( From Scratch using Python )
Prerequisites Linear RegressionGradient DescentIntroductionLinear Regression finds the correlation between the dependent variable ( or target variable ) and independent variables ( or features ). In short, it is a linear model to fit the data linearly. But it fails to fit and catch the pattern in non-linear data. Let's first apply Linear Regression
5 min read
Polynomial Regression using Turicreate
In this article, we will discuss the implementation of Polynomial Regression using Turicreate. Polynomial Regression: Polynomial regression is a form of regression analysis that models the relationship between a dependent say y and an independent variable say x as a nth degree polynomial. It is expressed as : y= b0+b1x1+ b2x12+ b2x13+...... bnx1n [
2 min read
How to proceed from Simple to Multiple and Polynomial Regression in R
Regression analysis allows us to understand how one or more independent variables relate to a dependent variable. Simple linear regression, which explores the relationship between two variables. Multiple linear regression extends this to include several predictors simultaneously. Finally, polynomial regression introduces flexibility by accommodatin
11 min read
Logistic Regression With Polynomial Features
Logistic regression with polynomial features is a technique used to model complex, non-linear relationships between input variables and the target variable. This approach involves transforming the original input features into higher-degree polynomial features, which can help capture intricate patterns in the data and improve the model's predictive
5 min read
Polynomial Contrasts for Regression Using R
Polynomial contrasts are a useful technique in regression analysis for modeling non-linear relationships between a predictor variable and the response variable. This approach allows you to fit polynomial curves (such as quadratic, cubic, etc.) to the data. This article will guide you through the theory behind polynomial contrasts and provide practi
4 min read
Linear vs. Polynomial Regression: Understanding the Differences
Regression analysis is a cornerstone technique in data science and machine learning, used to model the relationship between a dependent variable and one or more independent variables. Among the various types of regression, Linear Regression and Polynomial Regression are two fundamental approaches. This article delves into the differences between th
6 min read
Choosing Between Nonlinear and Polynomial Regression: A Technical Guide
Regression analysis is a fundamental technique in data science and machine learning, used to model the relationship between a dependent variable and one or more independent variables. Among the various types of regression, nonlinear regression and polynomial regression are two important approaches for modeling complex relationships. This article de
6 min read
Polynomial Regression vs Neural Network
In this article, we are going to compare polynomial regression and neural networks. What is Polynomial Regression?Polynomial regression is a technique used to model the relationship between a dependent variable (what you're trying to predict) and an independent variable (what you're basing your prediction on) when that relationship isn't straight l
4 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
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
Is least squares regression the same as linear regression
Yes, Least squares regression and linear regression are closely related in machine learning, but they’re not quite the same. Linear regression is a type of predictive model that assumes a linear relationship between input features and the output variable. Least squares is a common method used to find the best-fitting line in linear regression by mi
2 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
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
Implementation of Ridge Regression from Scratch using Python
Prerequisites: Linear Regression Gradient Descent Introduction: Ridge Regression ( or L2 Regularization ) is a variation of Linear Regression. In Linear Regression, it minimizes the Residual Sum of Squares ( or RSS or cost function ) to fit the training examples perfectly as possible. The cost function is also represented by J. Cost Function for Li
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
Implementation of Logistic Regression from Scratch using Python
Introduction:Logistic Regression is a supervised learning algorithm that is used when the target variable is categorical. Hypothetical function h(x) of linear regression predicts unbounded values. But in the case of Logistic Regression, where the target variable is categorical we have to strict the range of predicted values. Consider a classificati
5 min read
Implementation of Bayesian Regression
Linear regression is a popular regression approach in machine learning. Linear regression is based on the assumption that the underlying data is normally distributed and that all relevant predictor variables have a linear relationship with the outcome.  But In the real world, this is not always possible, it will follows these assumptions, Bayesian
13 min read
Implementation of Elastic Net Regression From Scratch
Prerequisites: Linear RegressionGradient DescentLasso & Ridge RegressionIntroduction: Elastic-Net Regression is a modification of Linear Regression which shares the same hypothetical function for prediction. The cost function of Linear Regression is represented by J. [Tex]\frac{1}{m} \sum_{i=1}^{m}\left(y^{(i)}-h\left(x^{(i)}\right)\right)^{2}[
5 min read
Implementation of Lasso Regression From Scratch using Python
For regularization and feature selection, Lasso Regression, also known as the Least Absolute Shrinkage and Selection Operator, is a linear regression technique. The cost function of linear regression, which is the sum of squared discrepancies between predicted and actual values, gains a penalty element. The absolute value of the coefficients multip
11 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
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
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
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
ML | Locally weighted Linear Regression
Linear Regression is a supervised learning algorithm used for computing linear relationships between input (X) and output (Y). The steps involved in ordinary linear regression are: Training phase: Compute [Tex]\theta [/Tex]to minimize the cost. [Tex]J(\theta) = $\sum_{i=1}^{m} (\theta^Tx^{(i)} - y^{(i)})^2 [/Tex] Predict output: for given query poi
3 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
ML | Dummy variable trap in Regression Models
Before learning about the dummy variable trap, let's first understand what actually dummy variable is. Dummy Variable in Regression Models: In statistics, especially in regression models, we deal with various kinds of data. The data may be quantitative (numerical) or qualitative (categorical). The numerical data can be easily handled in regression
2 min read
ML | Why Logistic Regression in Classification ?
Using Linear Regression, all predictions >= 0.5 can be considered as 1 and rest all < 0.5 can be considered as 0. But then the question arises why classification can't be performed using it? Problem - Suppose we are classifying a mail as spam or not spam and our output is y, it can be 0(spam) or 1(not spam). In case of Linear Regression, hθ(x
3 min read
three90RightbarBannerImg