開始使用免費開始

從混合分配抽樣(II)

從混合分配進行抽樣的完整演算法如下:

  1. 選擇一個成分。
  2. 依所選成分的平均數與標準差,產生一個常態隨機數。

上一個練習提供了 choose_component()。在這裡,你將完成第二步,並補完 rmix() 的定義。

本練習屬於課程

用 Rcpp 最佳化 R 程式碼

檢視課程

練習說明

  • 檢查標準差的數量是否與權重相同。也就是說,sds 的大小需與 d 相同。
  • total_weight 設為所有權重的總和。
  • 透過呼叫 choose_component() 來選擇一個成分。
  • 以被選成分為基礎進行模擬:使用 meanssds 的第 j 個元素產生一個常態隨機數。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

#include 
using namespace Rcpp;

// From previous exercise; do not modify
// [[Rcpp::export]]
int choose_component(NumericVector weights, double total_weight) {
  double x = R::runif(0, total_weight);
  int j = 0;
  while(x >= weights[j]) {
    x -= weights[j];
    j++;
  }
  return j;
}

// [[Rcpp::export]]
NumericVector rmix(int n, NumericVector weights, NumericVector means, NumericVector sds) {
  // Check that weights and means have the same size
  int d = weights.size();
  if(means.size() != d) {
    stop("means size != weights size");
  }
  // Do the same for the weights and std devs
  if(___) {
    stop("sds size != weights size");
  }
  
  // Calculate the total weight
  double total_weight = ___;
  
  // Create the output vector
  NumericVector res(n);
  
  // Fill the vector
  for(int i = 0; i < n; i++) {
    // Choose a component
    int j = ___(___, ___);
    
    // Simulate from the chosen component
    res[i] = ___::___(___, ___);
  }
  
  return res;
}

/*** R
  weights <- c(0.3, 0.7)
  means <- c(2, 4)
  sds <- c(2, 4)
  rmix(10, weights, means, sds)
*/
編輯並執行程式碼