Dağılımların karışımından örnekleme (II)
Bir karışım dağılımından örnekleme için tam algoritma şöyledir:
- Bir bileşen seç.
- Seçilen bileşenin ortalama ve standart sapmasını kullanarak normal bir rastgele sayı üret.
Önceki egzersizdeki choose_component() fonksiyonu hazır. Burada ikinci adımı tamamlayacak ve rmix() tanımını bitireceksin.
Bu egzersiz, kursun bir parçasıdır
Rcpp ile R Kodunu Optimize Etme
Egzersiz talimatları
- Standart sapma sayısının ağırlık sayısıyla aynı olduğunu kontrol et. Yani
sds'nin boyutudile aynı olmalı. total_weight'i ağırlıkların toplamı olarak hesapla.choose_component()çağırarak bir bileşen seç.- Seçilen bileşenden,
meansvesds'ninj'inci elemanlarını kullanarak normal bir rastgele sayı üreterek simüle et.
Uygulamalı etkileşimli egzersiz
Bu egzersizi bu örnek kodu tamamlayarak deneyin.
#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)
*/