logreg js and examples

This commit is contained in:
Anton Nesterov 2024-10-04 06:09:41 +02:00
parent af3587e284
commit 690e24271e
No known key found for this signature in database
GPG key ID: 59121E8AE2851FB5
6 changed files with 376 additions and 7 deletions

File diff suppressed because one or more lines are too long

Binary file not shown.

View file

@ -15,6 +15,7 @@ func InitRegrExports(this js.Value, args []js.Value) interface{} {
exports.Set("ElasticNet", js.FuncOf(src.NewElasticNetJS))
exports.Set("Lasso", js.FuncOf(src.NewLassoJS))
exports.Set("R2Score", js.FuncOf(src.R2ScoreJS))
exports.Set("Logistic", js.FuncOf(src.NewLogisticRegressionJS))
return exports
}

Binary file not shown.

View file

@ -0,0 +1,40 @@
//go:build js && wasm
// +build js,wasm
package src
import (
"syscall/js"
)
func NewLogisticRegressionJS(this js.Value, args []js.Value) interface{} {
var (
epochs = args[0].Get("epochs").Int()
learningRate = args[0].Get("learningRate").Float()
)
reg := &MCLogisticRegression{
Epochs: epochs,
LearningRate: learningRate,
}
loss := 1.0
obj := js.Global().Get("Object").New()
obj.Set("fit", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
X := JSFloatArray2D(args[0])
Y := JSFloatArray2D(args[1])
XDense := Array2DToDense(X)
YDense := Array2DToDense(Y)
reg.Fit(XDense, YDense)
return nil
}))
obj.Set("predict", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
X := JSFloatArray2D(args[0])
XDense := Array2DToDense(X)
Y := reg.Predict(XDense)
loss = reg.Loss(XDense, Y)
return MatrixToJSArray2D(Y)
}))
obj.Set("loss", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
return loss
}))
return obj
}

View file

@ -5,6 +5,8 @@ package src
import (
"syscall/js"
"gonum.org/v1/gonum/mat"
)
func JSFloatArray(arg js.Value) []float64 {
@ -35,3 +37,26 @@ func ToJSArray[T any](arr []T) []interface{} {
}
return jsArr
}
func MatrixToJSArray(m mat.Matrix) []interface{} {
r, c := m.Dims()
data := make([]float64, r*c)
for i := 0; i < r; i++ {
for j := 0; j < c; j++ {
data[i*c+j] = m.At(i, j)
}
}
return ToJSArray(data)
}
func MatrixToJSArray2D(m mat.Matrix) []interface{} {
r, c := m.Dims()
data := make([][]interface{}, r)
for i := 0; i < r; i++ {
data[i] = make([]interface{}, c)
for j := 0; j < c; j++ {
data[i][j] = m.At(i, j)
}
}
return ToJSArray(data)
}