gpt4 book ai didi

r - 自动尝试优化其他初始值

转载 作者:行者123 更新时间:2023-12-03 07:57:13 26 4
gpt4 key购买 nike

我使用optim(.)尝试找到某些函数fn(dat, par, out=FALSE)的最佳拟合参数,其中par必须是两个元素的 vector ,而out确定输出格式。我用

optim(par=c(1,1), fn, dat=dat)

以确定最合适的 par值。根据 dat中的数据,这要么起作用,要么抛出错误,
function cannot be evaluated at initial parameters

据我了解, optim(.)需要不同的起始值。我的问题是,我将该函数并行应用于许多数据集,并且想知道是否确实需要手动尝试不同的值,或者是否有某种方法可以按照
if no error then great
if error try par=c(0.5,1)
if no error then great
if error try par=c(0.5,0.5)
...

最佳答案

您可以在开始之前运行网格搜索并丢弃NA参数。这是一个例子。

测试功能:

fn <- function(x) {
if (x[1] < 0)
NA
else
prod(x)
}

现在运行网格搜索。
library("NMOF")    
res <- gridSearch(fn,
npar = 2, ## length of x
lower = -1, ## lower bound for x
upper = 3, ## upper bound for x
n = 5) ## number of levels per element in x
## 2 variables with 5, 5 levels: 25 function evaluations required.

该函数向您显示它尝试的所有参数组合。
res$levels
## [[1]]
## [1] -1 -1
##
## [[2]]
## [1] 0 -1
##
## [[3]]
## [1] 1 -1
##
## ....

并提供与这些组合相关的目标函数值。
res$values
## [1] NA 0 -1 -2 -3 NA 0 0 0 0 NA 0 1 2 3
## [16] NA 0 2 4 6 NA 0 3 6 9

## => many objective functions values are NA

最好的(none- NA)解决方案:
res$minlevels 
## [1] 3 -1

## => your starting value for optim:
##
## optim(gridSearch(fn, npar = 2,
## lower = -1, upper = 3, n = 5)$minlevels,
## fn, dat = dat)

当然,这不能保证您至少找到一个none- NA vector ,但是机会可能会增加。

关于r - 自动尝试优化其他初始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58086657/

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