mirror of
https://github.com/gonum/gonum.git
synced 2025-10-05 15:16:59 +08:00
optimize: avoid unnecessary allocations for Gradient and Hessian
This commit is contained in:
@@ -478,19 +478,22 @@ func evaluate(p *Problem, loc *Location, op Operation, x []float64) {
|
|||||||
}
|
}
|
||||||
if op&GradEvaluation != 0 {
|
if op&GradEvaluation != 0 {
|
||||||
// Make sure we have a destination in which to place the gradient.
|
// Make sure we have a destination in which to place the gradient.
|
||||||
// TODO(kortschak): Consider making this a check of len(loc.Gradient) != 0
|
if len(loc.Gradient) == 0 {
|
||||||
// to allow reuse of the slice.
|
if cap(loc.Gradient) < len(x) {
|
||||||
if loc.Gradient == nil {
|
loc.Gradient = make([]float64, len(x))
|
||||||
loc.Gradient = make([]float64, len(x))
|
} else {
|
||||||
|
loc.Gradient = loc.Gradient[:len(x)]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
p.Grad(loc.Gradient, x)
|
p.Grad(loc.Gradient, x)
|
||||||
}
|
}
|
||||||
if op&HessEvaluation != 0 {
|
if op&HessEvaluation != 0 {
|
||||||
// Make sure we have a destination in which to place the Hessian.
|
// Make sure we have a destination in which to place the Hessian.
|
||||||
// TODO(kortschak): Consider making this a check of loc.Hessian.IsZero()
|
switch {
|
||||||
// to allow reuse of the matrix.
|
case loc.Hessian == nil:
|
||||||
if loc.Hessian == nil {
|
|
||||||
loc.Hessian = mat.NewSymDense(len(x), nil)
|
loc.Hessian = mat.NewSymDense(len(x), nil)
|
||||||
|
case loc.Hessian.IsEmpty():
|
||||||
|
loc.Hessian.ReuseAsSym(len(x))
|
||||||
}
|
}
|
||||||
p.Hess(loc.Hessian, x)
|
p.Hess(loc.Hessian, x)
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user