go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/matrix/determination_coefficient.go (about) 1 /* 2 3 Copyright (c) 2024 - Present. Will Charczuk. All rights reserved. 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository. 5 6 */ 7 8 package matrix 9 10 import ( 11 "math" 12 ) 13 14 // DeterminationCoefficient returns the R^2 value for the regression coefficients. 15 func DeterminationCoefficient(xvalues, yvalues, regressionCoefficients []float64) float64 { 16 var residualsSquared float64 17 for x := 0; x < len(xvalues); x++ { 18 computedValue := computedValueFromCoeffs(xvalues[x], regressionCoefficients) 19 residual := yvalues[x] - computedValue 20 residualsSquared += (residual * residual) 21 } 22 mean := mean(yvalues) 23 var meanDeltasSquared float64 24 for x := 0; x < len(yvalues); x++ { 25 meanDelta := (yvalues[x] - mean) 26 meanDeltasSquared += (meanDelta * meanDelta) 27 } 28 return 1 - (residualsSquared / meanDeltasSquared) 29 } 30 31 func mean(values []float64) (output float64) { 32 if len(values) == 0 { 33 return 34 } 35 36 for _, v := range values { 37 output += v 38 } 39 output = output / float64(len(values)) 40 return 41 } 42 43 func computedValueFromCoeffs(xvalue float64, coeffs []float64) float64 { 44 var output float64 45 var power = float64(len(coeffs) - 1) 46 for x := 0; x < len(coeffs); x++ { 47 output += math.Pow(xvalue, power) * coeffs[x] 48 power-- 49 } 50 return output 51 }