Created
December 10, 2015 20:52
-
-
Save drbenvincent/b0549ff1ae428a3428b1 to your computer and use it in GitHub Desktop.
quick example of importance sampling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%% true probability distribution | |
true_func = @(x) betapdf(x,1+1,1+10); | |
%% Do importance sampling | |
N = 10^6; | |
% uniform proposal distribution | |
x_samples = rand(N,1); | |
proposal = 1/N; | |
% evaluate for each sample | |
target = true_func(x_samples); | |
% calculate importance weight | |
w = target ./ proposal; | |
w = w ./ sum(w); | |
% resample, with replacement, according to importance weight | |
samples = randsample(x_samples,N,true,w); | |
%% plot | |
subplot(1,2,1) | |
x = linspace(0,1,1000); | |
plot(x, true_func(x) ) | |
axis square | |
subplot(1,2,2) | |
hist(samples,1000) | |
title('importance sampling') | |
axis square |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment