Tuesday, 15 July 2014

Viterbi algorithm in R - Number of the replaced elements is not a multiple of replacement length error -



Viterbi algorithm in R - Number of the replaced elements is not a multiple of replacement length error -

i'm trying implement viterbi algorithm in r. i've written next code,

viterbi_impl <- function(y,p,b,pi){ # creating required matrices based on dimension of p sk <- matrix(0,nrow=dim(p)[1],ncol=length(y)) path <- matrix(0,,nrow=dim(p)[1],ncol=length(y)) # creating first column for(i in 1:dim(sk)[1]){ sk[i,1] <- log(pi[i]) + log(b[i,y[1]]) } for(x in 2:length(y)){ for(z in 1:dim(p)[1]){ max_sk <- max(sk[,(x-1)] + log(p[,z])) sk[z,x] <- log(b[z,y[x]]) + max_sk p <- which((sk[,(x-1)] + log(p[,z])) == max_sk) path[z,x] <- p } } likelihood <- max(sk[,length(y)]) # gives likelihood of optimal path start_opt_path <- which(sk[,length(y)] == max(sk[,length(y)])) backtrace <- vector(length=length(y)) backtrace[length(backtrace)] <- start_opt_path for(i in (length(y)-1):1){ backtrace[i] <- path[backtrace[i+1],i+1] } return(list(backtrace,likelihood)) }

i tried pass next parameters function arguments,

#computing optimal path log-likelihood observed sequence (a,b,c,b,a) y <- c(1,2,3,2,1) p <- matrix(c(1/3,0.5,0.5,1/3,1/3,1/3,0.5,0.5,0.5),3,3,byrow = true) b <- matrix(c(1/3,1/3,1/3,0.5,0.5,1/3,0.5,1/3,1/3),3,3,byrow = true) pi <-c(1/3,1/3,1/3) output <- viterbi_impl(y,p,b,pi)

the programme not throw error when run algorithm itself, however, when run programme above mentioned values throws next error

"number of replaced elements not multiple of replacement length"

i'm not quite familiar r programming errors yet , i'm not sure or how debug this. help please?

thanks in advance!

r viterbi

No comments:

Post a Comment