LinearRegression.py


SUBMITTED BY: okpalan86

DATE: Jan. 6, 2024, 10:19 p.m.

FORMAT: Python

SIZE: 1.6 kB

HITS: 362

  1. import numpy as np
  2. class LinearRegression:
  3. def __init__(self, learning_rate=0.01, num_iterations=1000):
  4. self.learning_rate = learning_rate
  5. self.num_iterations = num_iterations
  6. self.weights = None
  7. self.bias = None
  8. def fit(self, X, y):
  9. # Add a column of ones to X for the bias term
  10. X = np.column_stack((np.ones(len(X)), X))
  11. # Initialize weights and bias
  12. self.weights = np.zeros(X.shape[1])
  13. self.bias = 0
  14. # Gradient Descent
  15. for _ in range(self.num_iterations):
  16. predictions = self.predict(X)
  17. errors = predictions - y
  18. # Update weights and bias
  19. self.weights -= self.learning_rate * (1 / len(X)) * np.dot(errors, X)
  20. self.bias -= self.learning_rate * (1 / len(X)) * np.sum(errors)
  21. def predict(self, X):
  22. if self.weights is None or self.bias is None:
  23. raise Exception("Model not trained. Call fit() first.")
  24. return np.dot(X, self.weights) + self.bias
  25. # Example usage:
  26. # Assuming X and y are your input features and target variable, respectively
  27. X = np.array([1, 2, 3, 4, 5])
  28. y = np.array([2, 4, 5, 4, 5])
  29. # Reshape X to a column vector
  30. X = X.reshape(-1, 1)
  31. # Create and train the linear regression model
  32. model = LinearRegression()
  33. model.fit(X, y)
  34. # Make predictions
  35. new_data = np.array([6, 7, 8])
  36. new_data = new_data.reshape(-1, 1)
  37. predictions = model.predict(np.column_stack((np.ones(len(new_data)), new_data)))
  38. print("Predictions:", predictions)

comments powered by Disqus