Advertisement
Guest User

Untitled

a guest
Oct 24th, 2019
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. // Statistics refresher: The R-squared formula
  2. // Time complexity: O(3n)
  3.  
  4. package main
  5.  
  6. import "fmt"
  7.  
  8. type Point struct {
  9. x, y float64
  10. }
  11.  
  12. func getMean(points []Point) Point {
  13.  
  14. xSum := 0.0
  15. ySum := 0.0
  16. for i := 0; i < len(points); i++ {
  17. point := points[i]
  18. xSum += point.x
  19. ySum += point.y
  20. }
  21. pointsTotal := float64(len(points))
  22. xMean := xSum / pointsTotal
  23. yMean := ySum / pointsTotal
  24.  
  25. return Point{xMean, yMean}
  26. }
  27.  
  28. func getRegressionFeatures(points []Point) (float64, float64, Point) {
  29.  
  30. // Average point
  31. pointMean := getMean(points)
  32.  
  33. xyDeltaSum := 0.0
  34. xDeltaSquaredSum := 0.0
  35. for i := 0; i < len(points); i++ {
  36. point := points[i]
  37. xDelta := point.x - pointMean.x
  38. yDelta := point.y - pointMean.y
  39. xyDeltaSum += (xDelta * yDelta)
  40. xDeltaSquaredSum += (xDelta * xDelta)
  41. }
  42.  
  43. // Slope of line
  44. b1 := xyDeltaSum / xDeltaSquaredSum
  45.  
  46. // Y-intercept
  47. b0 := pointMean.y - (b1 * pointMean.x)
  48.  
  49. return b0, b1, pointMean
  50. }
  51.  
  52.  
  53. func getRSquared(points []Point) (float64) {
  54.  
  55. b0, b1, pointMean := getRegressionFeatures(points)
  56.  
  57. yDeltaSquaredSum := 0.0
  58. yHatDeltaSquaredSum := 0.0
  59. for i := 0; i < len(points); i++ {
  60. point := points[i]
  61. yDelta := point.y - pointMean.y
  62. yDeltaSquaredSum += (yDelta * yDelta)
  63. yhat := b0 + (b1 * point.x)
  64. yhatdiff := yhat - pointMean.y
  65. yHatDeltaquared := (yhatdiff * yhatdiff)
  66. yHatDeltaSquaredSum += yHatDeltaquared
  67. }
  68.  
  69. rSquared := yHatDeltaSquaredSum / yDeltaSquaredSum
  70.  
  71. return rSquared
  72. }
  73.  
  74. func main() {
  75. points := []Point {
  76. {1, 2},
  77. {3, 3},
  78. {5, 6},
  79. {8, 6},
  80. {11, 12},
  81. }
  82.  
  83. rsquared := getRSquared(points)
  84. fmt.Printf("R squared: %6.3f\n", rsquared)
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement