我正在尝试实现 EM 算法。我正在使用 while 循环进行迭代,而我的输出矩阵中的变化大于某个阈值,但我收到一条错误消息“while 错误(delta >= tau){:需要 TRUE/FALSE 的缺失值”下面是我的代码。
Multinomial<-function(H,K,tau) {
H=H+.01
count = 0
a_mat = 0
a_data = list() #list to store old and new A matrices
delta = Inf #initialize delta
#initialize mix weights and centroid matrices
c_mat = matrix(1/K,nrow(H),K)
rand_row = H[sample(1:40000,1),]
t_mat = matrix(rand_row/sum(rand_row),ncol(H),1)
for(i in 1:(K-1)) {
rand_row = H[sample(1:40000,1),]
t_mat = cbind(t_mat,rand_row/sum(rand_row))
}
while(delta>=tau) {
count=count + 1
a_data[[1]] = 0 #initialize for new A matrix
a_data[[2]] = a_mat #old A matrix
#E-Step: computes assignment probability matrix
phi_mat = exp(H%*%log(t_mat))
num_mat = (c_mat*phi_mat) #numerator of a
num_mat[num_mat==NaN]<-.00000001
nrsums=rowSums(num_mat)
a_mat = num_mat/nrsums #assignment prob matrix
a_data[[1]] = a_mat
#M-Step: compute new mix weights and centroids
acol_sum=.colSums(a_mat,nrow(a_mat),ncol(a_mat),na.rm=T)
c_k = acol_sum/nrow(H)
c_mat = matrix(c_k,nrow(H),K)
b_mat = t(H)%*%a_mat
t_mat = b_mat/colSums(b_mat)
#compute measure of change (delta)
if(count>1){
delta = norm(a_data[[1]]-a_data[[2]],'O')
}
}