시작하기무료로 시작하기

혼합 분포에서 샘플링 (II)

혼합 분포에서 샘플링하는 전체 알고리즘은 다음과 같습니다:

  1. 한 구성 요소를 선택합니다.
  2. 선택한 구성 요소의 평균과 표준편차를 사용해 정규 난수를 생성합니다.

이전 연습 문제의 choose_component()가 제공됩니다. 이제 두 번째 단계를 완성하고 rmix()의 정의를 마무리해 보세요.

이 연습은 강의의 일부입니다

Rcpp로 R 코드 최적화하기

강의 보기

연습 안내

  • 표준편차의 개수와 가중치의 개수가 같은지 확인하세요. 즉, sds의 크기가 d와 같아야 합니다.
  • total_weight를 가중치의 합으로 계산하세요.
  • choose_component()를 호출해 구성 요소를 선택하세요.
  • 선택한 구성 요소로부터, meanssdsj번째 원소를 사용해 정규 난수를 생성하여 시뮬레이션하세요.

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

#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)
*/
코드 편집 및 실행