Twist_Nemo

Polynomial Regression vs. Linear Regression.py

Apr 18th, 2021
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.80 KB | None | 0 0
  1. # importing libraries
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. import pandas as pd
  5.  
  6. # for calculating mean_squared error
  7. from sklearn.metrics import mean_squared_error
  8.  
  9. # creating a dataset with curvilinear relationship
  10. x=10*np.random.normal(0,1,70)
  11. y=10*(-x**2)+np.random.normal(-100,100,70)
  12.  
  13. # plotting dataset
  14. plt.figure(figsize=(10,5))
  15. plt.scatter(x,y,s=15)
  16. plt.xlabel('Predictor',fontsize=16)
  17. plt.ylabel('Target',fontsize=16)
  18. plt.show()
  19. # Importing Linear Regression
  20. from sklearn.linear_model import LinearRegression
  21.  
  22. # Training Model
  23. lm=LinearRegression()
  24. lm.fit(x.reshape(-1,1),y.reshape(-1,1))
  25. y_pred=lm.predict(x.reshape(-1,1))
  26.  
  27. # plotting predictions
  28. plt.figure(figsize=(10,5))
  29. plt.scatter(x,y,s=15)
  30. plt.plot(x,y_pred,color='r')
  31. plt.xlabel('Predictor',fontsize=16)
  32. plt.ylabel('Target',fontsize=16)
  33. plt.show()
  34. print('RMSE for Linear Regression=>',np.sqrt(mean_squared_error(y,y_pred)))
  35. # importing libraries for polynomial transform
  36. from sklearn.preprocessing import PolynomialFeatures
  37. # for creating pipeline
  38. from sklearn.pipeline import Pipeline
  39. # creating pipeline and fitting it on data
  40. Input=[('polynomial',PolynomialFeatures(degree=2)),('modal',LinearRegression())]
  41. pipe=Pipeline(Input)
  42. pipe.fit(x.reshape(-1,1),y.reshape(-1,1))
  43. poly_pred=pipe.predict(x.reshape(-1,1))
  44. #sorting predicted values with respect to predictor
  45. sorted_zip = sorted(zip(x,poly_pred))
  46. x_poly, poly_pred = zip(*sorted_zip)
  47. #plotting predictions
  48. plt.figure(figsize=(10,6))
  49. plt.scatter(x,y,s=15)
  50. plt.plot(x,y_pred,color='r',label='Linear Regression')
  51. plt.plot(x_poly,poly_pred,color='g',label='Polynomial Regression')
  52. plt.xlabel('Predictor',fontsize=16)
  53. plt.ylabel('Target',fontsize=16)
  54. plt.legend()
  55. plt.show()
  56. print('RMSE for Polynomial Regression=>',np.sqrt(mean_squared_error(y,poly_pred)))
Advertisement
Add Comment
Please, Sign In to add comment