R: Question about Optimizing - Invalid Function Value in Optimize

只谈情不闲聊 提交于 2019-12-31 05:47:07

问题


R Programming Question - Hello, we are two summer research students participating in a research program. After trial and error, we have not been able to pinpoint what is causing the error of "Invalid Function Value in Optimize" in our Optimizing code. If you could offer any insight, it would be appreciated.

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)); 

Here is a link to the code:

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


回答1:


Are you sure H_fun is returning a one-dimensional value?

Look at fcn1() in the R optimize() source code:

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 */
}

goto badvalue occurs if length is not 1. Also, the package summary states that optimize() works on a one-dimensional unconstrained function.



来源:https://stackoverflow.com/questions/6658941/r-question-about-optimizing-invalid-function-value-in-optimize

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!