Path: blob/master/Part 2 - Regression/Polynomial Regression/polynomial_regression.py
1009 views
# Polynomial Regression12# Importing the libraries3import numpy as np4import matplotlib.pyplot as plt5import pandas as pd67# Importing the dataset8dataset = pd.read_csv('Position_Salaries.csv')9X = dataset.iloc[:, 1:2].values10y = dataset.iloc[:, 2].values1112# Splitting the dataset into the Training set and Test set13"""from sklearn.cross_validation import train_test_split14X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)"""1516# Feature Scaling17"""from sklearn.preprocessing import StandardScaler18sc_X = StandardScaler()19X_train = sc_X.fit_transform(X_train)20X_test = sc_X.transform(X_test)"""2122# Fitting Linear Regression to the dataset23from sklearn.linear_model import LinearRegression24lin_reg = LinearRegression()25lin_reg.fit(X, y)2627# Fitting Polynomial Regression to the dataset28from sklearn.preprocessing import PolynomialFeatures29poly_reg = PolynomialFeatures(degree = 4)30X_poly = poly_reg.fit_transform(X)31poly_reg.fit(X_poly, y)32lin_reg_2 = LinearRegression()33lin_reg_2.fit(X_poly, y)3435# Visualising the Linear Regression results36plt.scatter(X, y, color = 'red')37plt.plot(X, lin_reg.predict(X), color = 'blue')38plt.title('Truth or Bluff (Linear Regression)')39plt.xlabel('Position level')40plt.ylabel('Salary')41plt.show()4243# Visualising the Polynomial Regression results44plt.scatter(X, y, color = 'red')45plt.plot(X, lin_reg_2.predict(poly_reg.fit_transform(X)), color = 'blue')46plt.title('Truth or Bluff (Polynomial Regression)')47plt.xlabel('Position level')48plt.ylabel('Salary')49plt.show()5051# Visualising the Polynomial Regression results (for higher resolution and smoother curve)52X_grid = np.arange(min(X), max(X), 0.1)53X_grid = X_grid.reshape((len(X_grid), 1))54plt.scatter(X, y, color = 'red')55plt.plot(X_grid, lin_reg_2.predict(poly_reg.fit_transform(X_grid)), color = 'blue')56plt.title('Truth or Bluff (Polynomial Regression)')57plt.xlabel('Position level')58plt.ylabel('Salary')59plt.show()6061# Predicting a new result with Linear Regression62lin_reg.predict(6.5)6364# Predicting a new result with Polynomial Regression65lin_reg_2.predict(poly_reg.fit_transform(6.5))6667