【问题标题】:In Optim function, print out parameter input in R在 Optim 函数中,打印出 R 中的参数输入
【发布时间】:2014-07-14 17:39:07
【问题描述】:

我有一个名为 est_Bt() 的函数

est_Bt = function(pars)
{
    exp_Bt <- rep(NA,length(prawn_df$Catch))
    exp_Bt[1] <- pars[4]
    for(i in 2:length(prawn_df$Catch))
    {
        exp_Bt[i] <- max(exp_Bt[i-1] + exp_Bt[i-1]* (pars[1]/pars[3]) * (1-((exp_Bt[i-1]/pars[2])^pars[3])) - prawn_df$Catch[i-1],100)
    }### Not we put the max to either bt+1 or 100 so the stock doesn't go extinct.
    cpue_obs <- prawn_df$Catch/prawn_df$Effort
    pred_q <- log(cpue_obs/exp_Bt)
    series <- 0:(nrow(prawn_df)-1)
    q_int <- as.vector(lsfit(series,pred_q)$coefficients)[1]
    q_stat <- as.vector(lsfit(series,pred_q)$coefficients)[2]
    qinc_int <- exp(q_int)
    qinc_stat <- exp(q_stat)
    q <- rep(NA, length(series))
    q[1] <- qinc_int
    for(i in 2:length(q)){
        q[i] <- q[i-1]* qinc_stat
    }
    pred_cpue <- pred_bt* q
    sum((log(cpue_obs) - log(pred_cpue))^2)
}

函数本身并不重要我想要帮助的是在使用函数 optim() 评估 pars 时我想知道是否有用于打印试验参数的命令。该函数给出了将渔业盈余模型应用于渔获量数据的平方和。

est_Bt(c(0.2,30000, 0.0000000001, 50000))
[1] 159.2381
est_Bt(c(0.32,27000, 0.0000000001, 45000))
[1] 67.45901

当我使用 optim 时,我得到了

optim(c(0.32,27000, 0.0000000001, 45000), est_Bt)
Error in lsfit(series, pred_q) : NA/NaN/Inf in 'y'
In addition: Warning message:
In lsfit(series, pred_q) : 26 missing values deleted

我对此的想法是,它正在测试一个无意义的参数值并且函数失败。而且我确信我应该知道我的方程来惩罚荒谬的参数值。但我认为如果 optim 可以打印出每次试验的参数值,那么它会帮助我探索模型中的参数交互吗?

椅子西里尔

【问题讨论】:

  • 在您的函数开始后立即添加print(pars)。这就是你所需要的吗?
  • 但是如果我添加 optim 需要函数的单个输出来最小化它
  • 我得到错误 Error in optim(c(0.2, 30000, 50000, 1e-10),est_Bt) :objective function in optim 计算为长度 4 而不是 1
  • 我的意思是把它放在这里:est_Bt &lt;- function(pars) {print(pars); exp_Bt&lt;- rep(NA, length(prawn_df$Catch)) ...你的函数应该有完全相同的返回值
  • 对不起,你是对的,谢谢。我把它放在函数的开头而不是开头。

标签: r function optimization


【解决方案1】:

如果要打印函数正在评估的“当前”参数集,只需在函数开头添加 print

est_Bt <-function(pars)
{
    print(pars)
    exp_Bt <- rep(NA,length(prawn_df$Catch))
    exp_Bt[1] <- pars[4]
    ...
}

这会将值发送到屏幕。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-26
    • 1970-01-01
    • 2014-08-28
    • 2013-12-21
    • 2019-05-07
    • 1970-01-01
    • 2013-06-20
    • 1970-01-01
    相关资源
    最近更新 更多