gpt4 book ai didi

c++ - 如何在我的 TMB .cpp 文件中包含更多目标函数?

转载 作者:行者123 更新时间:2023-11-30 03:33:31 26 4
gpt4 key购买 nike

TMB 目标函数似乎是在保存到 <name>.cpp 的一个函数 block 中定义的文件。然后,在编译文件后,通过使用命令加载访问每个目标函数 dyn.load(dynlib(<name>)) .

是否可以在每个 .cpp 中存储多个目标函数?文件?例如,以下两个目标函数彼此非常相似,但目前需要保存到不同的文件中:

// TMB Tutorial but with fixed variance
#include <TMB.hpp> // Links in the TMB libraries

template<class Type>
Type objective_function<Type>::operator() ()
{
DATA_VECTOR(x); // Data vector transmitted from R
PARAMETER(mu); // Parameter value transmitted from R
Type sigma = 1.0;

Type f; // Declare the "objective function" (neg. log. likelihood)
f = -sum(dnorm(x,mu,sigma,true)); // Use R-style call to normal density

return f;
}

// TMB Tutorial
#include <TMB.hpp> // Links in the TMB libraries

template<class Type>
Type objective_function<Type>::operator() ()
{
DATA_VECTOR(x); // Data vector transmitted from R
PARAMETER(mu); // Parameter value transmitted from R
PARAMETER(sigma); //

Type f; // Declare the "objective function" (neg. log. likelihood)
f = -sum(dnorm(x,mu,sigma,true)); // Use R-style call to normal density

return f;
}

最佳答案

MakeADFun() 的“map”参数允许您将参数固定为特定值。

在这个例子中,我们只需要编译/加载后面的模板即可。首先,我们将模板写入文件、编译并加载生成的 DLL。

library(TMB)

file_conn <- file('test.cpp')

writeLines("
#include <TMB.hpp>

template<class Type>
Type objective_function<Type>::operator() ()
{
DATA_VECTOR(x);
PARAMETER(mu);
PARAMETER(sigma);

Type f;
f = -sum(dnorm(x,mu,sigma,true));

return f;
}
", file_conn)
close(file_conn)

compile('test.cpp')
dyn.load(dynlib('test'))

我们可以使用相同的 DLL 来拟合具有和不具有不同 sigma 的模型。

n <- 100
x <- rnorm(n = n, mean = 0, sd = 1)

f1 <- MakeADFun(data = list(x = x),
parameters = list(mu = 0, sigma = 1),
DLL = 'test')

f2 <- MakeADFun(data = list(x = x),
parameters = list(mu = 0, sigma = 1),
DLL = 'test',
map = list(sigma = factor(NA)))

opt1 <- do.call('optim', f1)
opt2 <- do.call('optim', f2)

当使用“map”时,指定的参数(在本例中为 sigma)固定为“parameters”中给出的值。

优化后,我们进行健全性检查——mus 应该几乎相同。

> opt1$par
mu sigma
0.08300554 1.07926521
> opt2$par
mu
0.08300712

打开和关闭随机效果有点困难。给出了一个例子 here ,您可以在其中使用 CppAD::Variable() 检查是否减少负对数似然。

对于不同的目标函数(不是彼此的子集),您可以将 DATA_INTEGERDATA_STRING 传递到模板中,例如就像他们在 glmmTMB 中所做的那样 here ,并根据 DATA_* 的值选择目标函数。

关于c++ - 如何在我的 TMB .cpp 文件中包含更多目标函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42800829/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com