【问题标题】:Rcpp gamma integralRcpp 伽玛积分
【发布时间】:2017-04-27 12:05:43
【问题描述】:

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

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

【问题讨论】:

    标签: r rcpp gamma-function


    【解决方案1】:

    由于 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

    【讨论】:

    • 它工作正常。感谢您的解释和支持!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-13
    • 1970-01-01
    • 2018-12-04
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    相关资源
    最近更新 更多