Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Statistics refresher: The R-squared formula
- // Time complexity: O(3n)
- package main
- import "fmt"
- type Point struct {
- x, y float64
- }
- func getMean(points []Point) Point {
- xSum := 0.0
- ySum := 0.0
- for i := 0; i < len(points); i++ {
- point := points[i]
- xSum += point.x
- ySum += point.y
- }
- pointsTotal := float64(len(points))
- xMean := xSum / pointsTotal
- yMean := ySum / pointsTotal
- return Point{xMean, yMean}
- }
- func getRegressionFeatures(points []Point) (float64, float64, Point) {
- // Average point
- pointMean := getMean(points)
- xyDeltaSum := 0.0
- xDeltaSquaredSum := 0.0
- for i := 0; i < len(points); i++ {
- point := points[i]
- xDelta := point.x - pointMean.x
- yDelta := point.y - pointMean.y
- xyDeltaSum += (xDelta * yDelta)
- xDeltaSquaredSum += (xDelta * xDelta)
- }
- // Slope of line
- b1 := xyDeltaSum / xDeltaSquaredSum
- // Y-intercept
- b0 := pointMean.y - (b1 * pointMean.x)
- return b0, b1, pointMean
- }
- func getRSquared(points []Point) (float64) {
- b0, b1, pointMean := getRegressionFeatures(points)
- yDeltaSquaredSum := 0.0
- yHatDeltaSquaredSum := 0.0
- for i := 0; i < len(points); i++ {
- point := points[i]
- yDelta := point.y - pointMean.y
- yDeltaSquaredSum += (yDelta * yDelta)
- yhat := b0 + (b1 * point.x)
- yhatdiff := yhat - pointMean.y
- yHatDeltaquared := (yhatdiff * yhatdiff)
- yHatDeltaSquaredSum += yHatDeltaquared
- }
- rSquared := yHatDeltaSquaredSum / yDeltaSquaredSum
- return rSquared
- }
- func main() {
- points := []Point {
- {1, 2},
- {3, 3},
- {5, 6},
- {8, 6},
- {11, 12},
- }
- rsquared := getRSquared(points)
- fmt.Printf("R squared: %6.3f\n", rsquared)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement