혼합 분포에서의 샘플링 (I)
혼합 분포는 정규분포(성분)들의 밀도를 선형 결합한 분포를 말합니다. 각 성분은 선택될 확률인 가중치와, 평균 및 표준편차(일반적인 정규분포와 동일한 특성)를 가집니다.
이 알고리즘은 두 개의 연습 문제를 통해 단계적으로 완성할 거예요. 여기서는 choose_component() 정의를 완성하여 어떤 성분에서 샘플링할지 선택합니다.
이 연습은 강의의 일부입니다
Rcpp로 R 코드 최적화하기
연습 안내
R네임스페이스의runif()함수를 사용해0부터total_weight까지 균등한 난수를 생성하세요.- while 루프 안에서
x값을weights의j번째 원소만큼 감소시키세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
#include
using namespace Rcpp;
// [[Rcpp::export]]
int choose_component(NumericVector weights, double total_weight) {
// Generate a uniform random number from 0 to total_weight
double x = ___::___(0, ___);
// Remove the jth weight from x until x is small enough
int j = 0;
while(x >= weights[j]) {
// Subtract jth element of weights from x
___;
j++;
}
return j;
}
/*** R
weights <- c(0.3, 0.7)
# Randomly choose a component 5 times
replicate(5, choose_component(weights, sum(weights)))
*/