Advertisement
lancernik

Untitled

Apr 16th, 2019
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1.  
  2.  
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5.  
  6. def estimate_coef(x, y):
  7. # number of observations/points
  8. n = np.size(x)
  9.  
  10. # mean of x and y vector
  11. m_x, m_y = np.mean(x), np.mean(y)
  12.  
  13. # calculating cross-deviation and deviation about x
  14. SS_xy = np.sum(y*x) - n*m_y*m_x
  15. SS_xx = np.sum(x*x) - n*m_x*m_x
  16.  
  17. # calculating regression coefficients
  18. b_1 = SS_xy / SS_xx
  19. b_0 = m_y - b_1*m_x
  20.  
  21. return(b_0, b_1)
  22.  
  23. def plot_regression_line(x, y, b):
  24. # plotting the actual points as scatter plot
  25. plt.scatter(x, y, color = "m",
  26. marker = "o", s = 30)
  27.  
  28. # predicted response vector
  29. y_pred = b[0] + b[1]*x
  30.  
  31. # plotting the regression line
  32. plt.plot(x, y_pred, color = "g")
  33.  
  34. # putting labels
  35. plt.xlabel('x')
  36. plt.ylabel('y')
  37.  
  38. # function to show plot
  39. plt.show()
  40.  
  41.  
  42. # observations
  43. x = np.array([10,20,30,40,50,60,70,80,90])
  44. y = np.array([300,350,500,700,800,850,900,1000,1200])
  45.  
  46. # estimating coefficients
  47. b = estimate_coef(x, y)
  48.  
  49. # plotting regression line
  50. plot_regression_line(x, y, b)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement