2017-04-27 30 views
0

我想重寫(R)CPP原始R函數,利用伽馬函數(來自雙輸入)。低於原始來源。當與sourceCpp配合時,出現以下錯誤:「沒有匹配函數調用'gamma(Rcpp :: traits :: storage_type(< 14> :. type)''Rcpp伽馬積分

gamma函數應該放在sugar 。下面用平均值),所以我想到應該簡單地調

#include <Rcpp.h> 
#include <math.h> 
using namespace Rcpp; 


// original R function 
// function (y_pred, y_true) 
// { 
// eps <- 1e-15 
// y_pred <- pmax(y_pred, eps) 
// Poisson_LogLoss <- mean(log(gamma(y_true + 1)) + y_pred - 
//  log(y_pred) * y_true) 
// return(Poisson_LogLoss) 
// } 


// [[Rcpp::export]] 
double poissonLogLoss(NumericVector predicted, NumericVector actual) { 
    NumericVector temp, y_pred_new; 
    double out; 
    const double eps=1e-15; 

    y_pred_new=pmax(predicted,eps); 
    long n = predicted.size(); 
    for (long i = 0; i < n; ++i) { 
    temp[i] = log(gamma(actual[i]+1)+y_pred_new[i]-log(y_pred_new[i])*actual[i]); 
    } 

    out=mean(temp); // using sugar implementation 
    return out; 
} 

回答

3

您正在這個太複雜,RCPP糖的點工作矢量所以下面的編譯,以及:

#include <Rcpp.h> 
#include <math.h> 
using namespace Rcpp; 

// [[Rcpp::export]] 
double poissonLogLoss(NumericVector predicted, NumericVector actual) { 
    NumericVector temp, y_pred_new; 
    double out; 
    const double eps=1e-15; 

    y_pred_new=pmax(predicted,eps); 
    temp = log(gamma(actual + 1)) + y_pred_new - log(y_pred_new)*actual; 
    out=mean(temp); // using sugar implementation 
    return out; 
} 

現在,您沒有提供任何測試數據,所以我不知道這個計算是否正確。另外,因爲你的R表達式已經被矢量化了,所以速度不會太快。

最後,您的編譯錯誤可能是由於Sugar函數gamma()期望Rcpp對象,而您提供了double

+0

它工作正常。感謝您的解釋和支持! –