我正在尝试在R中实现Viterbi算法。我编写了以下代码,
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))
}
我尝试将以下参数传递给函数参数
#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)
当我运行算法本身时,程序不会抛出任何错误,但是,当我使用上述值运行程序时,它会抛出以下错误
“替换元素的数量不是替换长度的倍数”
我还不太熟悉R编程错误,我不确定这是关于什么或如何调试它。有人可以帮忙吗?
提前致谢!