Rcpp Armadillo中的样本 [英] sample in Rcpp Armadillo

查看:71
本文介绍了Rcpp Armadillo中的样本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在努力使用 RcppArmadillo 中提供的sample()命令.当我尝试运行下面的代码时,出现错误没有匹配的函数来调用样本,并且我已经在前面添加了额外的 Rcpp :: 命名空间,因为这样做很好在另一篇帖子中.

I am currently struggeling with the sample() command provided in 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.

我也尝试了其他几个容器类,但是我总是被这个错误所困扰.下面是一些代码,它会产生错误.

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

请注意,当您提供 arma :: rowvec 时,它期望的是 arma :: vec == arma :: colvec .因此,如果将 p0 alph 更改为 arma :: vec ,它应该可以工作.由于缺少样本数据而未经测试...

Note that it expects a arma::vec == arma::colvec, while you are providing a arma::rowvec. So it should work if you change p0 and alph to arma::vec. Untested because of missing sample data ...

顺便说一句,同时还有一个 Rcpp ::: sample()函数,以防您真的不需要Armadillo来完成其他任务.

BTW, there is meanwhile also a Rcpp:::sample() function in case you are not really needing Armadillo for other tasks.

关于@JosephWood在评论中提出的性能问题:我的印象是,两个 Rcpp :: sample() 哈希算法,它是

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(). 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. 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.

这篇关于Rcpp Armadillo中的样本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆