forked from gonum/optimize
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gradientdescent.go
61 lines (51 loc) · 1.68 KB
/
gradientdescent.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
// Copyright ©2014 The gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package optimize
import "github.com/gonum/floats"
// GradientDescent is a Method that performs gradient-based optimization.
// Gradient Descent performs successive steps along the direction of the
// gradient. The Linesearcher specifies the kind of linesearch to be done, and
// StepSizer determines the initial step size of each direction. If either
// Linesearcher or StepSizer are nil, a reasonable value will be chosen.
type GradientDescent struct {
Linesearcher Linesearcher
StepSizer StepSizer
ls *LinesearchMethod
}
func (g *GradientDescent) Init(loc *Location, xNext []float64) (EvaluationType, IterationType, error) {
if g.StepSizer == nil {
g.StepSizer = &QuadraticStepSize{}
}
if g.Linesearcher == nil {
g.Linesearcher = &Backtracking{}
}
if g.ls == nil {
g.ls = &LinesearchMethod{}
}
g.ls.Linesearcher = g.Linesearcher
g.ls.NextDirectioner = g
return g.ls.Init(loc, xNext)
}
func (g *GradientDescent) Iterate(loc *Location, xNext []float64) (EvaluationType, IterationType, error) {
return g.ls.Iterate(loc, xNext)
}
func (g *GradientDescent) InitDirection(loc *Location, dir []float64) (stepSize float64) {
copy(dir, loc.Gradient)
floats.Scale(-1, dir)
return g.StepSizer.Init(loc, dir)
}
func (g *GradientDescent) NextDirection(loc *Location, dir []float64) (stepSize float64) {
copy(dir, loc.Gradient)
floats.Scale(-1, dir)
return g.StepSizer.StepSize(loc, dir)
}
func (*GradientDescent) Needs() struct {
Gradient bool
Hessian bool
} {
return struct {
Gradient bool
Hessian bool
}{true, false}
}