Skip to content

Instantly share code, notes, and snippets.

@ferhatelmas
Forked from hyyking/main.go
Created July 23, 2019 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ferhatelmas/666b7b3cec5cdaf2cb5b97f93ab0fcfa to your computer and use it in GitHub Desktop.
Save ferhatelmas/666b7b3cec5cdaf2cb5b97f93ab0fcfa to your computer and use it in GitHub Desktop.
Go linear regression
package main;
import(
"fmt"
)
type LinearFunction struct {
a float64
b float64
}
func (f *LinearFunction) a_derivative(N, alpha, xi, yi float64) {
f.a -= (1.0/N)*alpha*(-2*xi*(yi-(f.a*xi+f.b)));
}
func (f *LinearFunction) b_derivative(N, alpha, xi, yi float64) {
f.b -= (1.0/N)*alpha*(-2*(yi-(f.a*xi+f.b)));
}
func (f *LinearFunction) descent(x, y []float64, alpha float64) {
var N int = len(x)
for i := 0; i < N; i++ {
f.a_derivative(float64(N), alpha, x[i], y[i]);
f.b_derivative(float64(N), alpha, x[i], y[i]);
}
}
func (f *LinearFunction) train(x, y []float64, epochs int, alpha float64) {
for e := 0; e < epochs; e++ {
f.descent(x, y, alpha)
}
}
func (f *LinearFunction) predict(v float64) float64 {
return f.a * v + f.b;
}
func main() {
spending := []float64{1, 4, 15, 5, 8, 2, 13, 9, 6, 19};
sales := []float64{1, 2, 10, 5, 9, 16, 4, 13, 8, 7};
f := &LinearFunction{a:0, b:0};
f.train(spending, sales, 5000, .01);
fmt.Println(f.predict(8));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment