Guest User

Untitled

a guest
Oct 16th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. import csv
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4.  
  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.  
  24. def main():
  25. # observations
  26. x_test = np.array([])
  27. y_test = np.array([])
  28.  
  29. x_train = np.array([])
  30. y_train = np.array([])
  31.  
  32. with open("team_1.csv", encoding="latin-1") as csvfile:
  33. reader = csv.DictReader(csvfile)
  34. for column in reader:
  35. x_test = np.append(x_test, column["Age"]).astype(float)
  36. y_test = np.append(y_test, column["Experience"]).astype(float)
  37.  
  38. with open("team_2.csv", encoding="latin-1") as csvfile:
  39. reader = csv.DictReader(csvfile)
  40. for column in reader:
  41. x_train = np.append(x_train, column["Age"]).astype(float)
  42. y_train = np.append(y_train, column["Experience"]).astype(float)
  43.  
  44. # estimating coefficients
  45. b_train = estimate_coef(x_train, y_train)
  46.  
  47. b_test = estimate_coef(x_test, y_test)
  48.  
  49. # plotting regression line
  50.  
  51. # plotting the actual points as scatter plot
  52. plt.scatter(x_test, y_test, color="m",
  53. marker="o", s=30)
  54.  
  55. # predicted response vector
  56. y_pred_train = b_train[0] + b_train[1] * x_train
  57. y_pred_test = b_test[0] + b_test[1] * x_test
  58.  
  59. # plotting the regression line
  60. plt.plot(x_train, y_pred_train, color="g")
  61.  
  62. # putting labels
  63. plt.xlabel('Age')
  64. plt.ylabel('Experience')
  65.  
  66. # function to show plot
  67. plt.show()
  68.  
  69. # plotting the actual points as scatter plot
  70. plt.scatter(x_train, y_train, color="m",
  71. marker="o", s=30)
  72.  
  73. plt.plot(x_test, y_pred_test, color="g")
  74.  
  75. # putting labels
  76. plt.xlabel('Age')
  77. plt.ylabel('Experience')
  78.  
  79. plt.show()
  80.  
  81.  
  82. main()
Add Comment
Please, Sign In to add comment