X-Git-Url: https://git.auder.net/?p=valse.git;a=blobdiff_plain;f=src%2Ftest%2Fgenerate_test_data%2Fhelpers%2FEMGrank.R;h=346916b1fe3786209cbf19534ee9274657b5fdc8;hp=d4198138a177b8417d5ceddb9109cbd1794d2937;hb=ef67d338c7f28ba041abe40ca9a8ab69f8365a90;hpb=c3bc47052f3ccb659659c59a82e9a99ea842398d diff --git a/src/test/generate_test_data/helpers/EMGrank.R b/src/test/generate_test_data/helpers/EMGrank.R index d419813..346916b 100644 --- a/src/test/generate_test_data/helpers/EMGrank.R +++ b/src/test/generate_test_data/helpers/EMGrank.R @@ -7,7 +7,8 @@ matricize <- function(X) } require(MASS) -EMGrank = function(Pi, Rho, mini, maxi, X, Y, tau, rank){ +EMGrank = function(Pi, Rho, mini, maxi, X, Y, tau, rank) +{ #matrix dimensions n = dim(X)[1] p = dim(X)[2] @@ -17,18 +18,17 @@ EMGrank = function(Pi, Rho, mini, maxi, X, Y, tau, rank){ #init outputs phi = array(0, dim=c(p,m,k)) Z = rep(1, n) -# Pi = piInit LLF = 0 #local variables Phi = array(0, dim=c(p,m,k)) - deltaPhi = c(0) - sumDeltaPhi = 0 + deltaPhi = c() + sumDeltaPhi = 0. deltaPhiBufferSize = 20 #main loop ite = 1 - while(ite<=mini || (ite<=maxi && sumDeltaPhi>tau)) + while (ite<=mini || (ite<=maxi && sumDeltaPhi>tau)) { #M step: Mise à jour de Beta (et donc phi) for(r in 1:k) @@ -40,46 +40,45 @@ EMGrank = function(Pi, Rho, mini, maxi, X, Y, tau, rank){ s = svd( ginv(crossprod(matricize(X[Z_indice,]))) %*% crossprod(matricize(X[Z_indice,]),matricize(Y[Z_indice,])) ) S = s$d - U = s$u - V = s$v #Set m-rank(r) singular values to zero, and recompose #best rank(r) approximation of the initial product if(rank[r] < length(S)) S[(rank[r]+1):length(S)] = 0 - phi[,,r] = U %*% diag(S) %*% t(V) %*% Rho[,,r] + phi[,,r] = s$u %*% diag(S) %*% t(s$v) %*% Rho[,,r] } - + #Etape E et calcul de LLF sumLogLLF2 = 0 - for(i in 1:n){ + for(i in seq_len(n)) + { sumLLF1 = 0 maxLogGamIR = -Inf - for(r in 1:k){ + for (r in seq_len(k)) + { dotProduct = tcrossprod(Y[i,]%*%Rho[,,r]-X[i,]%*%phi[,,r]) logGamIR = log(Pi[r]) + log(det(Rho[,,r])) - 0.5*dotProduct #Z[i] = index of max (gam[i,]) - if(logGamIR > maxLogGamIR){ + if(logGamIR > maxLogGamIR) + { Z[i] = r maxLogGamIR = logGamIR } - sumLLF1 = sumLLF1 + exp(logGamIR) / (2*pi)^(m/2) + sumLLF1 = sumLLF1 + exp(logGamIR) / (2*pi)^(m/2) } sumLogLLF2 = sumLogLLF2 + log(sumLLF1) } LLF = -1/n * sumLogLLF2 - + #update distance parameter to check algorithm convergence (delta(phi, Phi)) - deltaPhi = c(deltaPhi, max(max(max((abs(phi-Phi))/(1+abs(phi))))) ) - if(length(deltaPhi) > deltaPhiBufferSize){ - l_1 = c(2:length(deltaPhi)) - deltaPhi = deltaPhi[l_1] - } + deltaPhi = c( deltaPhi, max( (abs(phi-Phi)) / (1+abs(phi)) ) ) #TODO: explain? + if (length(deltaPhi) > deltaPhiBufferSize) + deltaPhi = deltaPhi[2:length(deltaPhi)] sumDeltaPhi = sum(abs(deltaPhi)) - + #update other local variables Phi = phi ite = ite+1 } - return(list(phi=phi, LLF=LLF)) + return(list("phi"=phi, "LLF"=LLF)) }