0

I am trying to rewrite into (R)cpp an original R function that makes use of the gamma function (from double input). Below the original source. When comping with sourceCpp the following error is raised "no matching function for call to 'gamma(Rcpp::traits::storage_type(<14>:.type)'"

The gamma function should has been put within sugar (as the mean below use) so I expect there should be easily called.

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

1 回答 1

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.

于 2017-04-27T12:27:23.653 回答