# Calculate Hessian after providing gradient: NLSolversBase, Optim

**URL:** <https://discourse.julialang.org/t/calculate-hessian-after-providing-gradient-nlsolversbase-optim/41629>\
**Category:** Performance\
**Created:** [June 17, 2020, 8:48pm UTC](https://discourse.julialang.org/t/calculate-hessian-after-providing-gradient-nlsolversbase-optim/41629 "2020-06-17T20:48:53Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![marinooss](https://avatars.discourse-cdn.com/v4/letter/m/f4b2a3/32.png) [@marinooss](https://discourse.julialang.org/u/marinooss)\
**Post date:** [June 17, 2020, 8:48pm UTC](https://discourse.julialang.org/t/calculate-hessian-after-providing-gradient-nlsolversbase-optim/41629/1 "2020-06-17T20:48:53Z")

</div>

I am using the following special interface from NLSolversBase, to minimize a function.

```julia
function fg!(F, G, x)
    common_calc(…)
    if !(G == nothing)
          # mutating calculations specific to g!
    end
    if !(F == nothing)
         # calculations specific to f
         return f
    end
end

```

In particular, my code that use Optim.jl is:

```julia
ODJ = OnceDifferentiable(only_fg!((F, G, theta)->fg!(F, G, theta, x1,x2)), θ)
results = optimize(ODJ, θ, LBFGS(),Optim.Options(store_trace = true))

```

How can I get the hessian to estimate standard errors using the gradient that I already defined in only\_fg! ? or is there another faster way? Since the problem has almost 100 parameters efficiency is important.

Currently, I am saving the gradient in another function to obtain the Hessian, and then the standard errors:

```julia
grad! = theta -> gradient_function!(theta, x1,x2)
Jinv = ForwardDiff.jacobian(grad!, results.minimizer)
V = inv(Jinv)/n

```
