Commit | Line | Data |
---|---|---|
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) | |
6 | #' @param tau threshold to stop EM algorithm | |
7 | #' | |
8 | #' @return a list with phiInit, rhoInit, piInit, gamInit | |
9 | #' @export | |
39046da6 BA |
10 | initSmallEM = function(k,X,Y,tau) |
11 | { | |
e166ed4e BA |
12 | n = nrow(Y) |
13 | m = ncol(Y) | |
14 | p = ncol(X) | |
ae4fa2cb | 15 | |
4725af56 | 16 | Zinit1 = array(0, dim=c(n,20)) |
e166ed4e BA |
17 | betaInit1 = array(0, dim=c(p,m,k,20)) |
18 | sigmaInit1 = array(0, dim = c(m,m,k,20)) | |
19 | phiInit1 = array(0, dim = c(p,m,k,20)) | |
20 | rhoInit1 = array(0, dim = c(m,m,k,20)) | |
ae4fa2cb | 21 | Gam = matrix(0, n, k) |
e166ed4e BA |
22 | piInit1 = matrix(0,20,k) |
23 | gamInit1 = array(0, dim=c(n,k,20)) | |
24 | LLFinit1 = list() | |
25 | ||
26 | require(MASS) #Moore-Penrose generalized inverse of matrix | |
e166ed4e BA |
27 | for(repet in 1:20) |
28 | { | |
4725af56 BG |
29 | distance_clus = dist(X) |
30 | tree_hier = hclust(distance_clus) | |
31 | Zinit1[,repet] = cutree(tree_hier, k) | |
32 | ||
e166ed4e BA |
33 | for(r in 1:k) |
34 | { | |
35 | Z = Zinit1[,repet] | |
c3bc4705 | 36 | Z_indice = seq_len(n)[Z == r] #renvoit les indices où Z==r |
e166ed4e | 37 | |
c3bc4705 | 38 | betaInit1[,,r,repet] = ginv(crossprod(X[Z_indice,])) %*% crossprod(X[Z_indice,], Y[Z_indice,]) |
e166ed4e | 39 | sigmaInit1[,,r,repet] = diag(m) |
4725af56 | 40 | phiInit1[,,r,repet] = betaInit1[,,r,repet] #/ sigmaInit1[,,r,repet] |
e166ed4e | 41 | rhoInit1[,,r,repet] = solve(sigmaInit1[,,r,repet]) |
c3bc4705 | 42 | piInit1[repet,r] = mean(Z == r) |
e166ed4e BA |
43 | } |
44 | ||
45 | for(i in 1:n) | |
46 | { | |
47 | for(r in 1:k) | |
48 | { | |
4725af56 | 49 | dotProduct = tcrossprod(Y[i,]%*%rhoInit1[,,r,repet]-X[i,]%*%phiInit1[,,r,repet]) |
e166ed4e BA |
50 | Gam[i,r] = piInit1[repet,r]*det(rhoInit1[,,r,repet])*exp(-0.5*dotProduct) |
51 | } | |
ae4fa2cb | 52 | sumGamI = sum(Gam[i,]) |
e166ed4e BA |
53 | gamInit1[i,,repet]= Gam[i,] / sumGamI |
54 | } | |
55 | ||
56 | miniInit = 10 | |
57 | maxiInit = 11 | |
58 | ||
4725af56 | 59 | new_EMG = .Call("EMGLLF_core",phiInit1[,,,repet],rhoInit1[,,,repet],piInit1[repet,],gamInit1[,,repet],miniInit,maxiInit,1,0,X,Y,tau) |
e166ed4e BA |
60 | LLFEessai = new_EMG$LLF |
61 | LLFinit1[repet] = LLFEessai[length(LLFEessai)] | |
62 | } | |
63 | ||
64 | b = which.max(LLFinit1) | |
65 | phiInit = phiInit1[,,,b] | |
66 | rhoInit = rhoInit1[,,,b] | |
67 | piInit = piInit1[b,] | |
68 | gamInit = gamInit1[,,b] | |
69 | ||
70 | return (list(phiInit=phiInit, rhoInit=rhoInit, piInit=piInit, gamInit=gamInit)) | |
39046da6 | 71 | } |