#Task 1 y <- c(3,6,3,5,9,14,12,11,19,18,15,4,1,6,11,21,11,3,7,18) #Task 2 alpha <- 0.1 beta <- 0.1 alpha_post_1 = alpha + sum(y[1:5]) alpha_post_2 = alpha + sum(y[6:10]) beta_post = beta + 5 alpha_post_1 alpha_post_2 beta_post #Task 3 #Notice that there is a difference between the parameterisation of the Gamma density in #the practical, and that used in R; type help(rgamma) to see the details. Hence, for the #R functions, we need to set the scale parameter to 1/beta. n <- 10000 lambda_1 <- rgamma(n, shape=alpha_post_1, scale=1/beta_post) lambda_2 <- rgamma(n, shape=alpha_post_2, scale=1/beta_post) weights <- rep(NA, times=n) for(i in 1:n){ weights[i] <- prod(0.5 * dpois(y[11:20], lambda_1[i]) + 0.5 * dpois(y[11:20], lambda_2[i])) } #Task 4 post_mean_1_labelled = alpha_post_1 / beta_post post_mean_2_labelled = alpha_post_2 / beta_post post_mean_1_labelled post_mean_2_labelled post_mean_1_all = sum(lambda_1 * weights) / sum(weights) post_mean_2_all = sum(lambda_2 * weights) / sum(weights) post_mean_1_all post_mean_2_all #Task 5 #Note that the function density must take as argument a vector of weights that sum to 1. lambda_1_density = density(lambda_1, weights=weights/sum(weights)) lambda_2_density = density(lambda_2, weights=weights/sum(weights)) t <- seq(0, 20, length.out = 1000) par(mfrow=c(1,2)) plot(lambda_1_density, main="Posterior density of lambda1") lines(t, dgamma(t, shape=alpha_post_1, scale=1/beta_post), lty=2) legend("topright",lty=c(1,2), legend=c("All data","Labelled data")) plot(lambda_2_density, main="Posterior density of lambda2") lines(t, dgamma(t, shape=alpha_post_2, scale=1/beta_post), lty=2) legend("topright",lty=c(1,2), legend=c("All data","Labelled data")) #Task 6 allocations <- matrix(NA, nrow=n, ncol=10) for(i in 1:n){ allocations[i,] <- dpois(y[11:20], lambda_1[i]) / (dpois(y[11:20], lambda_1[i]) + dpois(y[11:20], lambda_2[i])) } prob_of_group_1 = rep(NA, times=10) for(i in 1:10){ prob_of_group_1[i] = sum(allocations[,i] * weights) / sum(weights) } prob_of_group_1