Merge branch 'master' of auder.net:valse
[valse.git] / pkg / R / initSmallEM.R
CommitLineData
d1531659 1#' initialization of the EM algorithm
2#'
3#' @param k number of components
4#' @param X matrix of covariates (of size n*p)
5#' @param Y matrix of responses (of size n*m)
d1531659 6#'
7#' @return a list with phiInit, rhoInit, piInit, gamInit
8#' @export
e3f2fe8a 9#' @importFrom methods new
10#' @importFrom stats cutree dist hclust runif
11initSmallEM = function(k,X,Y)
39046da6 12{
e166ed4e
BA
13 n = nrow(Y)
14 m = ncol(Y)
15 p = ncol(X)
ae4fa2cb 16
ef67d338 17 Zinit1 = array(0, dim=c(n,20))
e166ed4e
BA
18 betaInit1 = array(0, dim=c(p,m,k,20))
19 sigmaInit1 = array(0, dim = c(m,m,k,20))
20 phiInit1 = array(0, dim = c(p,m,k,20))
21 rhoInit1 = array(0, dim = c(m,m,k,20))
ae4fa2cb 22 Gam = matrix(0, n, k)
e166ed4e
BA
23 piInit1 = matrix(0,20,k)
24 gamInit1 = array(0, dim=c(n,k,20))
25 LLFinit1 = list()
26
27 require(MASS) #Moore-Penrose generalized inverse of matrix
e166ed4e
BA
28 for(repet in 1:20)
29 {
4725af56
BG
30 distance_clus = dist(X)
31 tree_hier = hclust(distance_clus)
32 Zinit1[,repet] = cutree(tree_hier, k)
33
e166ed4e
BA
34 for(r in 1:k)
35 {
36 Z = Zinit1[,repet]
c3bc4705 37 Z_indice = seq_len(n)[Z == r] #renvoit les indices où Z==r
e3f2fe8a 38 if (length(Z_indice) == 1) {
39 betaInit1[,,r,repet] = ginv(crossprod(t(X[Z_indice,]))) %*%
40 crossprod(t(X[Z_indice,]), Y[Z_indice,])
41 } else {
ef67d338
BA
42 betaInit1[,,r,repet] = ginv(crossprod(X[Z_indice,])) %*%
43 crossprod(X[Z_indice,], Y[Z_indice,])
e3f2fe8a 44 }
e166ed4e 45 sigmaInit1[,,r,repet] = diag(m)
4725af56 46 phiInit1[,,r,repet] = betaInit1[,,r,repet] #/ sigmaInit1[,,r,repet]
e166ed4e 47 rhoInit1[,,r,repet] = solve(sigmaInit1[,,r,repet])
c3bc4705 48 piInit1[repet,r] = mean(Z == r)
e166ed4e
BA
49 }
50
51 for(i in 1:n)
52 {
53 for(r in 1:k)
54 {
4725af56 55 dotProduct = tcrossprod(Y[i,]%*%rhoInit1[,,r,repet]-X[i,]%*%phiInit1[,,r,repet])
e166ed4e
BA
56 Gam[i,r] = piInit1[repet,r]*det(rhoInit1[,,r,repet])*exp(-0.5*dotProduct)
57 }
ae4fa2cb 58 sumGamI = sum(Gam[i,])
e166ed4e
BA
59 gamInit1[i,,repet]= Gam[i,] / sumGamI
60 }
61
62 miniInit = 10
63 maxiInit = 11
64
f227455a 65 #new_EMG = .Call("EMGLLF_core",phiInit1[,,,repet],rhoInit1[,,,repet],piInit1[repet,],
66# gamInit1[,,repet],miniInit,maxiInit,1,0,X,Y,1e-4)
67 new_EMG = EMGLLF(phiInit1[,,,repet],rhoInit1[,,,repet],piInit1[repet,],gamInit1[,,repet],miniInit,maxiInit,1,0,X,Y,1e-4)
e166ed4e
BA
68 LLFEessai = new_EMG$LLF
69 LLFinit1[repet] = LLFEessai[length(LLFEessai)]
70 }
71
72 b = which.max(LLFinit1)
73 phiInit = phiInit1[,,,b]
74 rhoInit = rhoInit1[,,,b]
75 piInit = piInit1[b,]
76 gamInit = gamInit1[,,b]
77
78 return (list(phiInit=phiInit, rhoInit=rhoInit, piInit=piInit, gamInit=gamInit))
39046da6 79}