-
Notifications
You must be signed in to change notification settings - Fork 22
/
main.go
77 lines (69 loc) · 1.77 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package main
import (
"flag"
"log"
"math"
"github.com/c-bata/goptuna"
"github.com/c-bata/goptuna/rdb.v2"
"github.com/c-bata/goptuna/tpe"
"gorm.io/driver/mysql"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
func objective(trial goptuna.Trial) (float64, error) {
x1, _ := trial.SuggestFloat("x1", -10, 10)
x2, _ := trial.SuggestFloat("x2", -10, 10)
return math.Pow(x1-2, 2) + math.Pow(x2+5, 2), nil
}
func main() {
flag.Parse()
if len(flag.Args()) == 0 {
log.Fatal("please pass dialect and dsn")
}
dialect := flag.Arg(0)
dsn := flag.Arg(1)
var db *gorm.DB
var err error
if dialect == "sqlite3" {
db, err = gorm.Open(sqlite.Open(dsn), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
})
} else if dialect == "mysql" {
db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
})
} else {
log.Fatal("unsupported dialect")
}
if err != nil {
log.Fatal("failed to open db:", err)
}
err = rdb.RunAutoMigrate(db)
if err != nil {
log.Fatal("failed to run auto migrate:", err)
}
study, err := goptuna.CreateStudy(
"rdb",
goptuna.StudyOptionStorage(rdb.NewStorage(db)),
goptuna.StudyOptionSampler(tpe.NewSampler()),
goptuna.StudyOptionDirection(goptuna.StudyDirectionMinimize),
goptuna.StudyOptionLoadIfExists(true),
)
if err != nil {
log.Fatal("failed to create study", err)
}
if err = study.Optimize(objective, 50); err != nil {
log.Fatal("failed to optimize", err)
}
v, err := study.GetBestValue()
if err != nil {
log.Fatal("failed to get best value", err)
}
params, err := study.GetBestParams()
if err != nil {
log.Fatal("failed to get best params:", err)
}
log.Printf("Best evaluation=%f (x1=%f, x2=%f)",
v, params["x1"].(float64), params["x2"].(float64))
}