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

1 optimization r

我们无法确定是什么导致Invalid Function Value in Optimize了优化代码中的错误。如果您能提供任何见解,将不胜感激。

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)); 
Run Code Online (Sandbox Code Playgroud)

这是代码的链接:

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

Jus*_*yes 5

您确定H_fun返回的是一维值吗?

fcn1()řoptimize()源代码

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 */
}
Run Code Online (Sandbox Code Playgroud)

goto badvalue如果 length 不是 1,则会发生。此外,包摘要指出优化()适用于一维无约束函数。