Rcpp伽玛积分

时间:2017-04-27 12:05:44

标签: r rcpp gamma-function

我正在尝试将(R)cpp重写为使用gamma函数(来自双输入)的原始R函数。原始来源下方。在使用sourceCpp进行编译时,会出现以下错误:“没有匹配函数来调用'gamma(Rcpp :: traits :: storage_type(< 14>:。type)'”

伽玛函数应该放在糖中(如下面使用的平均值)所以我希望应该很容易调用。

#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;
}

1 个答案:

答案 0 :(得分:3)

你正在使这个太复杂,因为Rcpp Sugar的工作向量化。所以以下编译:

#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