简体   繁体   English

Rcpp Armadillo中的样本

[英]sample in Rcpp Armadillo

I am currently struggeling with the sample() command provided in RcppArmadillo . 我目前正与提供的样本()命令struggeling RcppArmadillo When I try to run the code below I get the error no matching function for call to sample and I already add the extra Rcpp:: namespace in front since this worked out well in another post . 当我尝试运行下面的代码时,出现错误, no matching function for call to sample并且我已经在前面添加了额外的Rcpp::名称空间,因为这在另一篇文章中很好地解决了。

I also tried several other container classes, but I am always stuck with this error. 我也尝试了其他几个容器类,但是我总是被这个错误困扰。 Below is some code, which produces the error. 下面是一些代码,它会产生错误。

Any help would be greatly appreciated :) 任何帮助将不胜感激 :)

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadilloExtensions/sample.h>
using namespace Rcpp;

// [[Rcpp::export]]
NumericMatrix example(arma::mat fprob,
                      int K) {
  int t = fprob.n_rows;
  IntegerVector choice_set = seq_len(K);
  arma::mat states(t,1); states.fill(0);
  arma::rowvec p0(K);
  arma::rowvec alph(K);
  double fit;

  p0 = fprob.row(t-1);
  fit = accu(p0);
  alph = p0/fit;
  states(t-1,1) = Rcpp::RcppArmadillo::sample(choice_set, 1, false, alph)[0];

  return wrap(states);
}

Here the definition of that function from the header: 这里从头开始定义该函数:

    // Enables supplying an arma probability
    template <class T> 
    T sample(const T &x, const int size, const bool replace, arma::vec &prob_){
      return sample_main(x, size, replace, prob_);
    }

Note that it expects a arma::vec == arma::colvec , while you are providing a arma::rowvec . 请注意,当您提供arma::rowvec ,它期望arma::vec == arma::colvec arma::rowvec So it should work if you change p0 and alph to arma::vec . 因此,如果将p0alph更改为arma::vec它应该可以工作。 Untested because of missing sample data ... 由于缺少样本数据而未经测试...

BTW, there is meanwhile also a Rcpp:::sample() function in case you are not really needing Armadillo for other tasks. 顺便说一句,同时还有Rcpp:::sample()函数,以防您真的不需要Armadillo来完成其他任务。

Concerning the performance questions raised by @JosephWood in the comments: I have the impression that both Rcpp::sample() and Rcpp::RcppArmadillo::sample() are based on do_sample() . 关于@JosephWood在评论中提出的性能问题:我的印象是Rcpp::sample()Rcpp::RcppArmadillo::sample()都基于do_sample() So they should be quite similar in most cases, but I have not benchmarked them. 因此,它们在大多数情况下应该非常相似,但我尚未对其进行基准测试。 The higher performance of R for unweighted sampling without replacement for larger numbers comes from the hash algorithm , which is selected at R level in such cases. R在未加权采样的情况下具有更高的性能,而无需替换较大的数字,这得益于在这种情况下在R级别选择哈希算法 It is also interesting to note that R 3.6 will have a new method for sampling in order to remove a bias present in the current method. 还有趣的是,R 3.6将具有一种新的采样方法,以消除当前方法中存在的偏差。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM