我需要非常快速地评估大量二项式似然。因此,我正在考虑在 Rcpp 中实现这一点。一种方法如下:
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector eval_likelihood(arma::vec Yi,
arma::vec Ni,
arma::vec prob){
// length of vector
int N = prob.n_rows;
// storage for evaluated log likelihoods
NumericVector eval(N);
for(int ii = 0; ii < N; ii++){
int y = Yi(ii); // no. of successes
int n = Ni(ii); // no. of trials
double p = prob(ii); // success probability
eval(ii) = R::dbinom(y,n,p,true); // argument 4 is set to true to return log-likelihood
}
return eval;
}
它返回与 R 中等效的对数似然dbinom()
:
Rcpp::sourceCpp("dbinom.cpp") #source Rcpp script
# fake data
Yi = 1:999
Ni = 2:1000
probs = runif(999)
evalR = dbinom(Yi, Ni, probs, log = T) # vectorized solution in R
evalRcpp = eval_likelihood(Yi, Ni, probs) # my Rcpp solution
identical(evalR,evalRcpp)
[1] TRUE
总的来说,这是一个不错的结果。但是,矢量化 R 解决方案平均比我的幼稚 Rcpp 解决方案略快:
microbenchmark::microbenchmark(R = dbinom(Yi, Ni, probs, log = T),
Rcpp = eval_likelihood(Yi, Ni, probs))
Unit: microseconds
expr min lq mean median uq max neval cld
R 181.753 182.181 188.7497 182.6090 189.4515 286.100 100 a
Rcpp 178.760 179.615 197.5721 179.8285 184.7470 1397.144 100 a
有人对更快地评估二项式对数似然有一些指导吗?可能是更快的代码或概率论中的一些技巧。谢谢!