Use splitfngr with lbfgs
lbfgs_share.RdUse lbfgs function from the lbfgs package but pass in a single function that returns both the function and gradient together in a list. Useful when the function and gradient are expensive to calculate and can be calculated faster together than separate.
Examples
quad_share <- function(x){list(sum(x^4), 4*x^3)}
lbfgs_share(vars=c(3, -5), fngr=quad_share)
#> Iteration 1:
#> fx = 322.314
#>
#> xnorm = 4.89476, gnorm = 274.43, step = 0.00195492
#>
#> Iteration 2:
#> fx = 100.763
#>
#> xnorm = 3.71359, gnorm = 111.211, step = 1
#>
#> Iteration 3:
#> fx = 34.1212
#>
#> xnorm = 2.84282, gnorm = 48.9431, step = 1
#>
#> Iteration 4:
#> fx = 10.9268
#>
#> xnorm = 2.14003, gnorm = 20.798, step = 1
#>
#> Iteration 5:
#> fx = 3.56744
#>
#> xnorm = 1.61783, gnorm = 8.98049, step = 1
#>
#> Iteration 6:
#> fx = 1.15599
#>
#> xnorm = 1.22065, gnorm = 3.85682, step = 1
#>
#> Iteration 7:
#> fx = 0.375674
#>
#> xnorm = 0.92163, gnorm = 1.66003, step = 1
#>
#> Iteration 8:
#> fx = 0.12195
#>
#> xnorm = 0.695664, gnorm = 0.713914, step = 1
#>
#> Iteration 9:
#> fx = 0.0396042
#>
#> xnorm = 0.525157, gnorm = 0.307125, step = 1
#>
#> Iteration 10:
#> fx = 0.0128596
#>
#> xnorm = 0.396425, gnorm = 0.132108, step = 1
#>
#> Iteration 11:
#> fx = 0.00417581
#>
#> xnorm = 0.299254, gnorm = 0.0568283, step = 1
#>
#> Iteration 12:
#> fx = 0.00135595
#>
#> xnorm = 0.225899, gnorm = 0.0244451, step = 1
#>
#> Iteration 13:
#> fx = 0.000440303
#>
#> xnorm = 0.170527, gnorm = 0.0105153, step = 1
#>
#> Iteration 14:
#> fx = 0.000142974
#>
#> xnorm = 0.128727, gnorm = 0.00452327, step = 1
#>
#> Iteration 15:
#> fx = 4.64263e-05
#>
#> xnorm = 0.0971729, gnorm = 0.00194573, step = 1
#>
#> Iteration 16:
#> fx = 1.50755e-05
#>
#> xnorm = 0.0733536, gnorm = 0.000836974, step = 1
#>
#> Iteration 17:
#> fx = 4.89527e-06
#>
#> xnorm = 0.055373, gnorm = 0.000360032, step = 1
#>
#> Iteration 18:
#> fx = 1.58958e-06
#>
#> xnorm = 0.0417999, gnorm = 0.000154871, step = 1
#>
#> Iteration 19:
#> fx = 5.16166e-07
#>
#> xnorm = 0.0315538, gnorm = 6.66195e-05, step = 1
#>
#> Iteration 20:
#> fx = 1.67608e-07
#>
#> xnorm = 0.0238192, gnorm = 2.8657e-05, step = 1
#>
#> Iteration 21:
#> fx = 5.44255e-08
#>
#> xnorm = 0.0179806, gnorm = 1.23271e-05, step = 1
#>
#> Iteration 22:
#> fx = 1.76729e-08
#>
#> xnorm = 0.0135732, gnorm = 5.30262e-06, step = 1
#>
#> L-BFGS optimization terminated with status code = 0
#> fx = 1.76729e-08
#>
#> $value
#> [1] 1.767293e-08
#>
#> $par
#> [1] 0.008565892 -0.010528829
#>
#> $convergence
#> [1] 0
#>