Part 3: Polynomial Regression : ( Python )
Today we will learn more about the Polynomial Regression and which regression is better Linear or Polynomial . The Polynomial vs Linear Regression ? , Polynomial key factor and uses.
Importing data and Liberaries
import numpy as npimport matplotlib.pyplot as pltimport pandas as pd# Importing the datasetdataset = pd.read_csv('position_salaries.csv')X = dataset.iloc[:, 1:2].valuesy = dataset.iloc[:, 2].values
Now we will Splitting the data in train and test data sets
# Splitting the dataset into the Training set and Test setfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2
random_state=0)
Now we will do Linear regression using the Sklearn liberaries inwhich we used LinearReression Class and ' lreg ' Objects
# Fitting Linear Regression to the datasetfrom sklearn.linear_model import LinearRegressionlreg = LinearRegression()lreg.fit(X, y)
After Fitting data in Linear model now we will go Toward Displaying thegraph of Linear Regression and try to figure out in visulisation method
def vlinear():plt.scatter(X, y, color='red')plt.plot(X, lreg.predict(X), color='blue')plt.title('Truth or Bluff (Linear Regression)')plt.xlabel('Position level')plt.ylabel('Salary')plt.show()returnvlinear()
After Completeing the Linear Model now we move forward to ward the Polynomial Model
The equation of Polynomial Regression is
Y = β + β . X1 + β . X1^2 + β . X2^3 + β . X3^4
we need the Square term of each Coolum to get the Best prediction and good result .
Now We fill Fit The Data in PolyNomial Regression model :
# Fitting Polynomial Regression to the datasetfrom sklearn.preprocessing import PolynomialFeaturespoly_reg = PolynomialFeatures(degree=4)X_poly = poly_reg.fit_transform(X)pol_reg = LinearRegression()pol_reg.fit(X_poly, y)
Now We Fit The data In Regression model and now we will Visulize the data Using the sklearn libararies and we will compare the linear and Polynomial regression and the output of both are give below in screen shots.
def vpolymonial():plt.scatter(X, y, color='red')plt.plot(X, pol_reg.predict(poly_reg.fit_transform(X)), color='blue')plt.title('Truth or Bluff (Linear Regression)')plt.xlabel('Position level')plt.ylabel('Salary')plt.show()returnvpolymonial()
Comparison :
The Polynomial is accurate than the linear and giving best prediction .The polynomial is very closed to exact result and data .
Comments
Post a Comment