Skip to content

MakeTape$newton's (sometimes?) has NaN effect on obj$he() #66

@phillipbvetter

Description

@phillipbvetter

Hi.

As always, thanks for a great package!

I believe I've found some inconsistent behaviour with obj$he() when the objective function includes calls to MakeTape$newton(). For certain parameters columns of the hessian are NaNs. The behaviour seems to be affected by previous calls to obj$he.

I provide a code example below taken from https://github.com/kaskr/RTMB/blob/master/tmb_examples/linreg.R, with the addition of each parameter wrapped in a MakeTape$newton() function - which is the identity function.

library(RTMB)
set.seed(14)

g <- RTMB::MakeTape(function(x) ((x[1])-x[2])^2, rep(1,2))
f_newton <- g$newton(2)

data <- list(Y = rnorm(10) + 1:10, x=1:10)
parameters <- list(a=0, b=0, logSigma=0)

f <- function(parms) {
    Y <- data$Y
    x <- data$x
    a <- f_newton(parms$a)
    b <- f_newton(parms$b)
    logSigma <- f_newton(parms$logSigma)
    nll = -sum(dnorm(Y, a+b*x, exp(logSigma), TRUE))
    nll
}
obj <- MakeADFun(f, parameters, silent=TRUE)
obj$he(obj$par) #works fine
obj$he(obj$par + 4.0) #works fine
obj$he(obj$par + 2.0) # gives NaN
obj$he(obj$par + 4.0) # now this gives NaN
obj$he(obj$par) #works fine

# Optimize
opt <- do.call("optim", obj)
# nlminb(obj$par,obj$fn,obj$gr,obj$he) #doesn't work because some hessian calls will give NaN eventually...

# Check hessian
obj$he(opt$par) #gives NaN's

rep <- sdreport(obj)
summary(rep) # but here we get std. errors!

# A small perturbation gives answers
obj$he(opt$par+1e-15) #does work
obj$he(opt$par-1e-15) # does work

# Check inversion of neg. log like hessian against sdreport result
std.error <- sqrt(diag(solve(obj$he(opt$par+1e-15))))
cbind(
  sdreport = sqrt(diag(rep$cov.fixed)),
  inverted_hessian = std.error,
  difference  = sqrt(diag(rep$cov.fixed)) - std.error
)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions