0

I'm trying to implement Viterbi algorithm in R. I've written the following 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 the 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 the likelihood of the most 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 to pass the following parameters to the function arguments,

#Computing optimal path log-likelihood for the 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 program does not throw any error when I run the algorithm itself, however, when I run the program with the above mentioned values it throws the following error

"Number of the replaced elements is not a multiple of replacement length"

I'm not quite familiar with R programming errors yet and I'm not really sure what this is about or how to debug this. Could someone help please?

Thanks in advance!

MM2
  • 29
  • 8
  • The built-in debuggers `browser()`, `traceback()`, etc. are your friend. – Rich Scriven Jun 17 '14 at 23:37
  • Thats a good tip! I'll see if I can sort this out, thanks for the info... – MM2 Jun 17 '14 at 23:44
  • possible duplicate of [R error: number of items to replace is not a multiple of replacement length R](http://stackoverflow.com/questions/11857598/r-error-number-of-items-to-replace-is-not-a-multiple-of-replacement-length-r) – bright-star Jun 17 '14 at 23:58

0 Answers0