Advertisement
Guest User

Untitled

a guest
Jul 16th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. import numpy as np
  2.  
  3. class univariate_Linear_Regression:
  4. # initialize slope and intercept
  5. def __init__(self):
  6. self.m = 0.0 # slope
  7. self.b = 0.0 # intercept
  8.  
  9. # sum of square deviation for single variable
  10. def ss_x(self, x):
  11. return sum((x-np.mean(x))**2)
  12.  
  13. # sum of square deviation for two variables x and y
  14. def ss_xy(self, x, y):
  15. x_mean = np.mean(x) # mean of x
  16. y_mean = np.mean(y) # mean of y
  17. return sum((x-x_mean)*(y-y_mean))
  18.  
  19. # Train our regression model based on shape and size
  20. def train(self, x, y):
  21.  
  22. # verify the features and labels are of same size
  23. assert(len(x) == len(y))
  24.  
  25. # calculate the slope
  26. ss_x = self.ss_x(x)
  27. ss_xy = self.ss_xy(x, y)
  28. self.m = ss_xy/ss_x
  29.  
  30. # calculate the intercept
  31. self.b = (np.mean(y)) - (self.m)*(np.mean(x))
  32.  
  33. # return the predicted values based on feature and weights
  34. def predict(self, x):
  35. predictions = np.zeros(len(x))
  36. for i in range(len(x)):
  37. predictions[i] = self.m * x[i] + self.b # Y = mx + b
  38. return predictions
  39.  
  40.  
  41. # Dataset to train model
  42. x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
  43. y = np.array([1.1, 1.9, 2.8, 4, 5.2, 5.8, 6.9, 8.1, 9, 9.9])
  44.  
  45. # Initialize our model
  46. reg = univariate_Linear_Regression()
  47.  
  48. # Train our model with the data
  49. reg.train(x, y)
  50.  
  51. # Make a prediction
  52. print(reg.predict(x))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement