r语言 - 从修改后的 arma::vec 对象中有效采样



我正在使用Rcpp来加速一些R代码。 但是,我真的很纠结类型 - 因为它们在 R 中是外来的。这是我正在尝试执行的操作的简化版本:

#include <RcppArmadillo.h>
#include <algorithm>
//[[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace arma;
// [[Rcpp::export]]
NumericVector fun(SEXP Pk, int k, int i, const vec& a, const mat& D) {
// this is dummy version of my actual function - with actual arguments.;
// I'm guessing SEXP is going to need to be replaced with something else when it's called from C++ not R.;
return D.col(i);
}
// [[Rcpp::export]]
NumericVector f(const arma::vec& assignment, char k, int B, const mat& D) {
uvec k_ind = find(assignment == k);
NumericVector output(assignment.size());  // for dummy output.
uvec::iterator k_itr = k_ind.begin();
for(; k_itr != k_ind.end(); ++k_itr) {
// this is R code, as I don't know the best way to do this in C++;
k_rep = sample(c(assignment[assignment != k], -1), size = B, replace = TRUE);
output = fun(k_rep, k, *k_itr, assignment, D);
// do something with output;
}
// compile result, ultimately return a List (after I figure out how to do that.  For right now, I'll cheat and return the last output);
return output;
}

我正在努力的部分是assignment的随机抽样。 我知道sample已在Rarmadillo实施. 但是,我可以看到两种方法,我不确定哪种方法更有效/可行。

方法1:

  • 制作一个assignment值的表格。 将assignment == k替换为 -1,并将其"计数"设置为 1。
  • 从"名称"表中抽取样本,概率与计数成正比。

方法2:

  • assignment向量的相关子集复制到具有 -1 额外位置的新向量中。
  • 从复制的向量中以相等的概率采样。

我想说方法 1 会更有效,除了assignment目前是arma::vec型,我不确定如何从中制作表格 - 或者将其转换为更兼容的格式需要多少成本。 我想我可以实现方法 2,但我希望避免昂贵的副本。

感谢您提供的任何见解。

许多变量声明与您所做的赋值不一致,例如赋值 = k 无法比较,因为赋值具有实际值,而 k 是字符。 由于任务写得不好,我可以随意更改变量类型。 这个编译..

// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
#include <RcppArmadilloExtensions/sample.h>
// [[Rcpp::export]]
arma::vec fun(const Rcpp::NumericVector& Pk, int k, unsigned int i, const arma::ivec& a, const arma::mat& D)
{
return D.col(i);
}
// [[Rcpp::export]]
Rcpp::NumericMatrix f(const arma::ivec& assignment, int k, unsigned int B, const arma::mat& D) 
{
arma::uvec k_ind = find(assignment == k);
arma::ivec KK = assignment(find(assignment != k));
//these 2 row are for KK = c(assignment[assignment != k], -1)  
//I dont know what is this -1 is for, why -1 ? maybe you dont need it.
KK.insert_rows(KK.n_rows, 1);
KK(KK.n_rows - 1) = -1;
arma::uvec k_ind_not = find(assignment != k);
Rcpp::NumericVector k_rep(B);
arma::mat output(D.n_rows,k_ind.n_rows);  // for dummy output.
for(unsigned int i =0; i < k_ind.n_rows ; i++) 
{
k_rep = Rcpp::RcppArmadillo::sample(KK, B, true);
output(arma::span::all, i) = fun(k_rep, k, i, assignment, D);
// do something with output;
}
// compile result, ultimately return a List (after I figure out how to do that.  For right now, I'll cheat and return the last output);
return Rcpp::wrap(output);
}

这没有优化(因为问题是假的(,这写得很糟糕,因为我认为 R 在搜索向量的索引时会足够快(所以在 R 中这样做,在 Rcpp 中只有趣(......在这里浪费时间是没有用的,还有其他问题需要在 Rcpp 中实现求解器,而不是这个搜索的东西...... 但这不是一个有用的问题,因为您对算法的要求比示例函数签名更多

最新更新