Vikhyath_11

a1

Dec 12th, 2024
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. #program 1
  2. from math import sqrt
  3. # Calculate root mean squared error
  4. def rmse(actual, predicted):
  5. errors = [(predicted[i] - actual[i]) ** 2 for i in
  6. range(len(actual))]
  7. return sqrt(sum(errors) / len(actual))
  8. # Calculate mean
  9. def mean(values):
  10. return sum(values) / len(values)
  11. # Calculate covariance
  12. def covariance(x, y):
  13. mean_x, mean_y = mean(x), mean(y)
  14. return sum((x[i] - mean_x) * (y[i] - mean_y) for i in
  15. range(len(x)))
  16. # Calculate variance
  17. def variance(values):
  18. mean_val = mean(values)
  19. return sum((x - mean_val) ** 2 for x in values)
  20. # Calculate coefficients
  21. def coefficients(data):
  22. x = [row[0] for row in data]
  23. y = [row[1] for row in data]
  24. b1 = covariance(x, y) / variance(x)
  25. b0 = mean(y) - b1 * mean(x)
  26. return b0, b1
  27. # Simple linear regression
  28. def simple_linear_regression(train, test):
  29. b0, b1 = coefficients(train)
  30. return [b0 + b1 * row[0] for row in test]
  31. # Test dataset
  32. data = [[1, 1], [2, 3], [4, 3], [3, 2], [5, 5]]
  33. # Evaluate model
  34. x, y = [row[0] for row in data], [row[1] for row in data]
  35. print(f"x stats: mean={mean(x):.3f}, variance={variance(x):.3f}")
  36. print(f"y stats: mean={mean(y):.3f}, variance={variance(y):.3f}")
  37. print(f"Covariance: {covariance(x, y):.3f}")
  38. predicted = simple_linear_regression(data, data)
  39. print(f"Predicted: {predicted}")
  40. print(f"RMSE: {rmse(y, predicted):.3f}")
  41. b0, b1 = coefficients(data)
  42. print(f"Coefficients: B0={b0:.3f}, B1={b1:.3f}")
Advertisement
Add Comment
Please, Sign In to add comment