forked from xlvector/hector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lbfgs_minimizer.go
83 lines (73 loc) · 2.05 KB
/
lbfgs_minimizer.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
78
79
80
81
82
83
package lr
import (
"fmt"
"github.com/pantsing/hector/internal/core"
)
/**
* It's based the paper "Scalable Training of L1-Regularized Log-Linear Models"
* by Galen Andrew and Jianfeng Gao
* user: weixuan
* To change this template use File | Settings | File Templates.
*/
type LBFGSMinimizer struct {
costFun DiffFunction
numHist int
maxIteration int
tolerance float64
}
var lbfgs_output_switch bool = false
func NewLBFGSMinimizer() *LBFGSMinimizer {
m := new(LBFGSMinimizer)
m.numHist = 10
m.maxIteration = 200
m.tolerance = 1e-4
return m
}
func (m *LBFGSMinimizer) Minimize(costfun DiffFunction, init *core.Vector) *core.Vector {
m.costFun = costfun
var cost float64 = costfun.Value(init)
var grad *core.Vector = costfun.Gradient(init).Copy()
var pos *core.Vector = init.Copy()
var terminalCriterion *relativeMeanImprCriterion = NewRelativeMeanImprCriterion(m.tolerance)
terminalCriterion.addCost(cost)
var helper *QuasiNewtonHelper = NewQuasiNewtonHelper(m.numHist, m, pos, grad)
if lbfgs_output_switch {
fmt.Println("Iter\tcost\timprovement")
fmt.Printf("%d\t%e\tUndefined", 0, cost)
}
for iter := 1; iter <= m.maxIteration; iter++ {
dir := grad.Copy()
dir.ApplyScale(-1.0)
helper.ApplyQuasiInverseHession(dir)
newCost, newPos := helper.BackTrackingLineSearch(cost, pos, grad, dir, iter == 1)
if lbfgs_output_switch {
fmt.Println("")
}
if cost == newCost {
break
}
cost = newCost
pos = newPos
grad = costfun.Gradient(pos).Copy()
terminalCriterion.addCost(cost)
if lbfgs_output_switch {
fmt.Printf("%d\t%e\t%e", iter, newCost, terminalCriterion.improvement)
}
if terminalCriterion.isTerminable() || helper.UpdateState(pos, grad) {
if lbfgs_output_switch {
fmt.Println("")
}
break
}
}
return pos
}
func (m *LBFGSMinimizer) Evaluate(pos *core.Vector) float64 {
return m.costFun.Value(pos)
}
func (m *LBFGSMinimizer) NextPoint(curPos *core.Vector, dir *core.Vector, alpha float64) *core.Vector {
if lbfgs_output_switch {
fmt.Printf(".")
}
return curPos.ElemWiseMultiplyAdd(dir, alpha)
}