Last active
October 5, 2019 23:38
-
-
Save danvas/11f38b827a4456b6bfc83ea1ca16c433 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment