1 #helper to always have matrices as arg (TODO: put this elsewhere? improve?)
2 matricize <- function(X)
5 return (t(as.matrix(X)))
10 EMGrank = function(Pi, Rho, mini, maxi, X, Y, tau, rank){
18 phi = array(0, dim=c(p,m,k))
24 Phi = array(0, dim=c(p,m,k))
27 deltaPhiBufferSize = 20
31 while(ite<=mini || (ite<=maxi && sumDeltaPhi>tau))
33 #M step: Mise à jour de Beta (et donc phi)
36 Z_indice = seq_len(n)[Z==r] #indices où Z == r
37 if (length(Z_indice) == 0)
39 #U,S,V = SVD of (t(Xr)Xr)^{-1} * t(Xr) * Yr
40 s = svd( ginv(crossprod(matricize(X[Z_indice,]))) %*%
41 crossprod(matricize(X[Z_indice,]),matricize(Y[Z_indice,])) )
45 #Set m-rank(r) singular values to zero, and recompose
46 #best rank(r) approximation of the initial product
47 if(rank[r] < length(S))
48 S[(rank[r]+1):length(S)] = 0
49 phi[,,r] = U %*% diag(S) %*% t(V) %*% Rho[,,r]
52 #Etape E et calcul de LLF
58 dotProduct = tcrossprod(Y[i,]%*%Rho[,,r]-X[i,]%*%phi[,,r])
59 logGamIR = log(Pi[r]) + log(det(Rho[,,r])) - 0.5*dotProduct
60 #Z[i] = index of max (gam[i,])
61 if(logGamIR > maxLogGamIR){
63 maxLogGamIR = logGamIR
65 sumLLF1 = sumLLF1 + exp(logGamIR) / (2*pi)^(m/2)
67 sumLogLLF2 = sumLogLLF2 + log(sumLLF1)
70 LLF = -1/n * sumLogLLF2
72 #update distance parameter to check algorithm convergence (delta(phi, Phi))
73 deltaPhi = c(deltaPhi, max(max(max((abs(phi-Phi))/(1+abs(phi))))) )
74 if(length(deltaPhi) > deltaPhiBufferSize){
75 l_1 = c(2:length(deltaPhi))
76 deltaPhi = deltaPhi[l_1]
78 sumDeltaPhi = sum(abs(deltaPhi))
80 #update other local variables
84 return(list(phi=phi, LLF=LLF))