# Simulate data
TRANS_s <- matrix(c(0.9, 0.1, 0.3, 0.7), nrow=2, byrow=TRUE)
alpha_s <- c(2, 4)
beta_s <- c(1, 0.25)
Total <- 100
x <- nbh_gen(TRANS_s, alpha_s, beta_s, Total);
count <- x$count
label <- x$label
Total <- length(count)
# dummy initialization
TRANS0 <- matrix(rep(0.5,4), 2)
alpha0 <- c(1, 20)
beta0 <- c(1, 1)
NIT_MAX <- 50
TOL <- 1e-100
nbh <- nbh_em(count, TRANS0, alpha0, beta0, NIT_MAX, TOL)
map.accuracy <- length(which(max.col(nbh$postprob) == label))/Total
vit <- nbh_vit(count, nbh$TRANS, nbh$alpha, nbh$beta)
vit.accuracy <- length(which(vit$class == label))/Total
# Plots
par(mfrow=c(2,2), cex.lab=1.2, cex.main=1.2)
plot(count, col="blue", type="l", main=sprintf("A. Simulated Data (Total = %i)",Total))
plot(as.numeric(nbh$logl), xlab="EM Iteration", ylab="Log-Likelihood",
main="B. Log-Likelihood via EM");grid()
# Marginal postprob
plot(nbh$postprob[,2], col="blue", type="l", ylim = c(0,1),
ylab="Marginal Posteriror or True State")
points(label-1, col="red")
title(main = sprintf("C. MAP Prediciton Accuracy = %.2f%s", 100 * map.accuracy, "%"))
# Viterbi states
plot(vit$class - 1, col="dark green", type="l", ylim = c(0,1),
ylab="Viterbi or True State")
points(label-1, col="red")
title(main = sprintf("D. Viterbi Prediciton Accuracy = %.2f%s", 100 * vit.accuracy, "%"))
Run the code above in your browser using DataLab