In [24]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

In [25]:
np.set_printoptions(precision=3, suppress=True)

Importing a dataset


In [26]:
dataset = pd.read_csv('Position_Salaries.csv')

In [27]:
X = dataset.iloc[:, 1:2].values
y = dataset.iloc[:, -1].values

Fitting Linear Regression to the dataset


In [28]:
from sklearn.linear_model import LinearRegression

In [29]:
lin_reg = LinearRegression()
lin_reg.fit(X, y)


Out[29]:
LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)

Fitting Polynomial Regression to the dataset


In [30]:
from sklearn.preprocessing import PolynomialFeatures

In [31]:
poly_reg = PolynomialFeatures(degree=4)
X_poly = poly_reg.fit_transform(X)
poly_reg.fit(X_poly, y)


Out[31]:
PolynomialFeatures(degree=4, include_bias=True, interaction_only=False)

In [32]:
lin_reg_2 = LinearRegression()
lin_reg_2.fit(X_poly, y)


Out[32]:
LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)

Visualising the Linear Regression results


In [33]:
plt.scatter(X, y, color='red')
plt.plot(X, lin_reg.predict(X), color='blue')
plt.title('Truth or Bluff (Linear Regression)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()


Visualising the Polynomial Regression results


In [34]:
plt.scatter(X, y, color='red')
plt.plot(X, lin_reg_2.predict(poly_reg.fit_transform(X)), color='blue')
plt.title('Truth or Bluff (Polynomial Regression)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()


Visualising the Polynomial Regression results (for higher resolution and smoother curve)


In [35]:
X_grid = np.arange(min(X), max(X), 0.1)
X_grid = X_grid.reshape((len(X_grid), 1))
plt.scatter(X, y, color='red')
plt.plot(X_grid, lin_reg_2.predict(poly_reg.fit_transform(X_grid)), color='blue')
plt.title('Truth or Bluff (Polynomial Regression)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()


Predicting a new result with Linear Regression


In [36]:
lin_reg.predict(6.5)


Out[36]:
array([ 330378.788])

Predicting a new result with Polynomial Regression


In [37]:
lin_reg_2.predict(poly_reg.fit_transform(6.5))


Out[37]:
array([ 158862.453])