1 #helper to always have matrices as arg (TODO: put this elsewhere? improve?)
2 # --> Yes, we should use by-columns storage everywhere... [later!]
3 matricize <- function(X)
6 return (t(as.matrix(X)))
11 EMGrank_R = function(Pi, Rho, mini, maxi, X, Y, tau, rank)
20 phi = array(0, dim=c(p,m,k))
25 Phi = array(0, dim=c(p,m,k))
28 deltaPhiBufferSize = 20
32 while (ite<=mini || (ite<=maxi && sumDeltaPhi>tau))
34 #M step: Mise à jour de Beta (et donc phi)
37 Z_indice = seq_len(n)[Z==r] #indices où Z == r
38 if (length(Z_indice) == 0)
40 #U,S,V = SVD of (t(Xr)Xr)^{-1} * t(Xr) * Yr
41 s = svd( ginv(crossprod(matricize(X[Z_indice,]))) %*%
42 crossprod(matricize(X[Z_indice,]),matricize(Y[Z_indice,])) )
44 #Set m-rank(r) singular values to zero, and recompose
45 #best rank(r) approximation of the initial product
46 if(rank[r] < length(S))
47 S[(rank[r]+1):length(S)] = 0
48 phi[,,r] = s$u %*% diag(S) %*% t(s$v) %*% Rho[,,r]
51 #Etape E et calcul de LLF
59 dotProduct = tcrossprod(Y[i,]%*%Rho[,,r]-X[i,]%*%phi[,,r])
60 logGamIR = log(Pi[r]) + log(det(Rho[,,r])) - 0.5*dotProduct
61 #Z[i] = index of max (gam[i,])
62 if(logGamIR > maxLogGamIR)
65 maxLogGamIR = logGamIR
67 sumLLF1 = sumLLF1 + exp(logGamIR) / (2*pi)^(m/2)
69 sumLogLLF2 = sumLogLLF2 + log(sumLLF1)
72 LLF = -1/n * sumLogLLF2
74 #update distance parameter to check algorithm convergence (delta(phi, Phi))
75 deltaPhi = c( deltaPhi, max( (abs(phi-Phi)) / (1+abs(phi)) ) ) #TODO: explain?
76 if (length(deltaPhi) > deltaPhiBufferSize)
77 deltaPhi = deltaPhi[2:length(deltaPhi)]
78 sumDeltaPhi = sum(abs(deltaPhi))
80 #update other local variables
84 return(list("phi"=phi, "LLF"=LLF))