Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
debakarr
GitHub Repository: debakarr/machinelearning
Path: blob/master/Part 2 - Regression/Polynomial Regression/polynomial_regression.py
1009 views
1
# Polynomial Regression
2
3
# Importing the libraries
4
import numpy as np
5
import matplotlib.pyplot as plt
6
import pandas as pd
7
8
# Importing the dataset
9
dataset = pd.read_csv('Position_Salaries.csv')
10
X = dataset.iloc[:, 1:2].values
11
y = dataset.iloc[:, 2].values
12
13
# Splitting the dataset into the Training set and Test set
14
"""from sklearn.cross_validation import train_test_split
15
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)"""
16
17
# Feature Scaling
18
"""from sklearn.preprocessing import StandardScaler
19
sc_X = StandardScaler()
20
X_train = sc_X.fit_transform(X_train)
21
X_test = sc_X.transform(X_test)"""
22
23
# Fitting Linear Regression to the dataset
24
from sklearn.linear_model import LinearRegression
25
lin_reg = LinearRegression()
26
lin_reg.fit(X, y)
27
28
# Fitting Polynomial Regression to the dataset
29
from sklearn.preprocessing import PolynomialFeatures
30
poly_reg = PolynomialFeatures(degree = 4)
31
X_poly = poly_reg.fit_transform(X)
32
poly_reg.fit(X_poly, y)
33
lin_reg_2 = LinearRegression()
34
lin_reg_2.fit(X_poly, y)
35
36
# Visualising the Linear Regression results
37
plt.scatter(X, y, color = 'red')
38
plt.plot(X, lin_reg.predict(X), color = 'blue')
39
plt.title('Truth or Bluff (Linear Regression)')
40
plt.xlabel('Position level')
41
plt.ylabel('Salary')
42
plt.show()
43
44
# Visualising the Polynomial Regression results
45
plt.scatter(X, y, color = 'red')
46
plt.plot(X, lin_reg_2.predict(poly_reg.fit_transform(X)), color = 'blue')
47
plt.title('Truth or Bluff (Polynomial Regression)')
48
plt.xlabel('Position level')
49
plt.ylabel('Salary')
50
plt.show()
51
52
# Visualising the Polynomial Regression results (for higher resolution and smoother curve)
53
X_grid = np.arange(min(X), max(X), 0.1)
54
X_grid = X_grid.reshape((len(X_grid), 1))
55
plt.scatter(X, y, color = 'red')
56
plt.plot(X_grid, lin_reg_2.predict(poly_reg.fit_transform(X_grid)), color = 'blue')
57
plt.title('Truth or Bluff (Polynomial Regression)')
58
plt.xlabel('Position level')
59
plt.ylabel('Salary')
60
plt.show()
61
62
# Predicting a new result with Linear Regression
63
lin_reg.predict(6.5)
64
65
# Predicting a new result with Polynomial Regression
66
lin_reg_2.predict(poly_reg.fit_transform(6.5))
67