R:关于优化的问题 - 优化中的无效函数值

时间:2011-07-12 02:39:28

标签: r optimization

R编程问题 - 您好,我们是两名参加研究计划的暑期研究生。经过反复试验,我们无法确定在优化代码中导致“优化中的无效函数值”错误的原因。如果您能提供任何见解,我们将不胜感激。

H_fun <- function(c) 
{ 
val = -current_c_weight*c - X_counts%*%log( 
exp(rep(c,length(current_Theta))*current_Theta) - 
current_elongation_rates ) 
print('#########iteration display#############') 
print('c') 
print(c) 
print('val') 
print(val) 
print('current_c_weight') 
print(current_c_weight) 
print('current_Theta') 
print(current_Theta) 
print('current_elongation_rates') 
print(current_elongation_rates) 
} 

#...snip...

# minimize -H(c) without the non-negativity constraint 
#tmp = optim(c(0,1),H_fun,NULL, method = "BFGS", hessian = TRUE); 
tmp = optimize(H_fun,interval = c(0,1)); 

以下是代码的链接:

http://www.text-upload.com/read.php?id=102950&c=8605046

1 个答案:

答案 0 :(得分:3)

你确定H_fun正在返回一维值吗?

查看R optimize() source code中的fcn1()

static double fcn1(double x, struct callinfo *info)
{
    SEXP s;
    REAL(CADR(info->R_fcall))[0] = x;
    s = eval(info->R_fcall, info->R_env);
    switch(TYPEOF(s)) {
    case INTSXP:
        if (length(s) != 1) goto badvalue;
        if (INTEGER(s)[0] == NA_INTEGER) {
            warning(_("NA replaced by maximum positive value"));
        return DBL_MAX;
        }
        else return INTEGER(s)[0];
        break;
    case REALSXP:
        if (length(s) != 1) goto badvalue;
        if (!R_FINITE(REAL(s)[0])) {
            warning(_("NA/Inf replaced by maximum positive value"));
            return DBL_MAX;
        }
        else return REAL(s)[0];
        break;
    default:
        goto badvalue;
    }
 badvalue:
    error(_("invalid function value in 'optimize'"));
    return 0;/* for -Wall */
}
如果length不是1,则会出现

goto badvalue。此外,optimize()的package summary个状态适用于一维无约束函数。