The Wayback Machine - https://web.archive.org/web/20240825102855/https://www.geeksforgeeks.org/polynomial-regression-for-non-linear-data-ml/
Open In App

Polynomial Regression for Non-Linear Data – ML

Last Updated : 03 Jun, 2020
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 travelled by a uniformly accelerated body: The distance can be calculated as ut + ½at2
    where,

    g = acceleration due to gravity
    u = initial velocity
    ho = initial height
    a = acceleration

In addition to these examples, Non-linear trends are also observed in the growth rate of tissues, the progress of disease epidemic, black body radiation, the motion of the pendulum etc. These examples clearly indicate that we cannot always have a linear relationship between the independent and dependent attributes. Hence, linear regression is a poor choice for dealing with such nonlinear situations. This is where Polynomial Regression comes to our rescue!!

Polynomial Regression is a powerful technique to encounter the situations where a quadratic, cubic or a higher degree nonlinear relationship exists. The underlying concept in polynomial regression is to add powers of each independent attribute as new attributes and then train a linear model on this expanded collection of features.
Let us illustrate the use of Polynomial Regression with an example. Consider a situation where the dependent variable y varies with respect to an independent variable x following a relation

y = 13x2 + 2x + 7

.

We shall use Scikit-Learn’s PolynomialFeatures class for the implementation.

Step1: Import the libraries and generate a random dataset.




# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.metrics import mean_squared_error, r2_score
  
# Importing the dataset
## x = data, y = quadratic equation
x = np.array(7 * np.random.rand(100, 1) - 3)
x1 = x.reshape(-1, 1)
y = 13 * x*x + 2 * x + 7 


Step2: Plot the data points.




# data points
plt.scatter(x, y, s = 10)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Non Linear Data')



 
Step3: First try to fit the data with a linear model.




# Model initialization
regression_model = LinearRegression()
# Fit the data(train the model)
regression_model.fit(x1, y)
print('Slope of the line is', regression_model.coef_)
print('Intercept value is', regression_model.intercept_)
# Predict
y_predicted = regression_model.predict(x1)


Output:

Slope of the line is [[14.87780012]]
Intercept value is [58.31165769]

Step 4: Plot the data points and the linear line.




# data points
plt.scatter(x, y, s = 10)
plt.xlabel("$x$", fontsize = 18)
plt.ylabel("$y$", rotation = 0, fontsize = 18)
plt.title("data points")
  
# predicted values
plt.plot(x, y_predicted, color ='g')


Output:

Equation of the linear model is y = 14.87x + 58.31

 

Step 5: Calculate the performance of the model in terms of mean square error, root mean square error and r2 score.




# model evaluation
mse = mean_squared_error(y, y_predicted)
  
rmse = np.sqrt(mean_squared_error(y, y_predicted))
r2 = r2_score(y, y_predicted)
  
# printing values
  
print('MSE of Linear model', mse)
  
print('R2 score of Linear model: ', r2)


Output:

MSE of Linear model 2144.8229656677095
R2 score of Linear model:  0.3019970606151057

The performance of the linear model is not satisfactory. Let’s try Polynomial Regression with degree 2

Step 6: For improving the performance, we need to make the model a bit complex. So, lets fit a polynomial of degree 2 and proceed with linear regression.




poly_features = PolynomialFeatures(degree = 2, include_bias = False)
x_poly = poly_features.fit_transform(x1)
x[3]


Output:

Out[]:array([-2.84314447])




x_poly[3]


Output:

  Out[]:array([-2.84314447,  8.08347046])


In addition to column x, one more column has been introduced which is the square of actual data. Now we proceed with simple Linear Regression




lin_reg = LinearRegression()
lin_reg.fit(x_poly, y)
print('Coefficients of x are', lin_reg.coef_)
print('Intercept is', lin_reg.intercept_)


Output:

Coefficients of x are [[ 2. 13.]]
Intercept is [7.]


This is the desired equation 13x2 + 2x + 7

Step 7: Plot the quadratic equation obtained.




x_new = np.linspace(-3, 4, 100).reshape(100, 1)
x_new_poly = poly_features.transform(x_new)
y_new = lin_reg.predict(x_new_poly)
plt.plot(x, y, "b.")
plt.plot(x_new, y_new, "r-", linewidth = 2, label ="Predictions")
plt.xlabel("$x_1$", fontsize = 18)
plt.ylabel("$y$", rotation = 0, fontsize = 18)
plt.legend(loc ="upper left", fontsize = 14)
  
plt.title("Quadratic_predictions_plot")
plt.show()


Output:
 

Step 8: Calculate the performance of the model obtained by Polynomial Regression.




y_deg2 = lin_reg.predict(x_poly)
# model evaluation
mse_deg2 = mean_squared_error(y, y_deg2)
  
r2_deg2 = r2_score(y, y_deg2)
  
# printing values
  
print('MSE of Polyregression model', mse_deg2)
  
print('R2 score of Linear model: ', r2_deg2)


Output:

MSE of Polyregression model 7.668437973562934e-28
R2 score of Linear model:  1.0

The performance of polynomial regression model is far better than linear regression model for the given quadratic equation.
Important Facts: PolynomialFeatures (degree = d) transforms an array containing n features into an array containing (n + d)! / d! n! features.

Conclusion: Polynomial Regression is an effective way to deal with nonlinear data as it can find relationships between features which plain Linear Regression model struggles to do.



Similar Reads

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
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
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
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
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
Implementation of Polynomial Regression
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-dep
9 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
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
Difference between Linear Pipeline and Non-Linear Pipeline
1. Linear Pipeline : Linear pipeline is a pipeline in which a series of processors are connected together in a serial manner. In linear pipeline the data flows from the first block to the final block of processor. The processing of data is done in a linear and sequential manner. The input is supplied to the first block and we get the output from th
4 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
What is the difference between Linear and non-linear filters?
Digital filters which include linear and non-linear filters play a major role in signal and image processing since they are capable of producing different results depending on their type. Linear filters take a linear mathematical operation that helps in removing noise, improving or extracting certain features from the signals or images and is very
7 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
Managing Missing Data in Linear Regression
Managing missing data in linear regression or any machine learning model is crucial, to maintain the accuracy and reliability of machine learning models. This article will delve into the methods and techniques for managing missing data in linear regression, highlighting the importance of understanding the context and nature of missing data. In the
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
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
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
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
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
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