Skip to content

Instantly share code, notes, and snippets.

@seananderson
Created June 11, 2024 20:29
Show Gist options
  • Save seananderson/f67f0e2603d465224799b001b79250d6 to your computer and use it in GitHub Desktop.
Save seananderson/f67f0e2603d465224799b001b79250d6 to your computer and use it in GitHub Desktop.
Example of predicting on newdata by rebuilding TMB object
library(TMB)
compile("lm1.cpp")
dyn.load(dynlib("lm1")) # can't call it 'lm'!
set.seed(123)
x <- seq(0, 10, length.out = 10)
data <- list(Y = rnorm(length(x)) + x, x = x)
parameters <- list(a = 0, b = 0, logSigma = 0)
obj <- MakeADFun(data, parameters, DLL = "lm1")
opt <- nlminb(obj$par, obj$fn, obj$gr)
sdr <- sdreport(obj)
sdr
obj$report(obj$env$last.par.best)
# now give it new data that is longer and try to predict
nd <- data.frame(Y = rep(1, 11), x = rep(2, 11))
obj2 <- MakeADFun(nd, obj$env$parList(), DLL = "lm1")
obj2$fn(opt$par)
lp <- obj$env$last.par.best
obj2$report(lp)
#include <TMB.hpp>
template<class Type>
Type objective_function<Type>::operator() ()
{
DATA_VECTOR(Y);
DATA_VECTOR(x);
PARAMETER(a);
PARAMETER(b);
PARAMETER(logSigma);
Type nll = 0.0;
Type sigma = exp(logSigma);
vector<Type> mu(x.size());
for (int i=0; i < x.size(); i++) {
mu(i) = a + b * x(i);
nll -= dnorm(Y(i), mu(i), sigma, true);
}
REPORT(mu);
REPORT(sigma)
return nll;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment