ajout des commentaires Roxygen - anglicisme de certains noms de fonctions et de variables
[valse.git] / R / initSmallEM.R
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
10 initSmallEM = function(k,X,Y,tau)
11 {
12 n = nrow(Y)
13 m = ncol(Y)
14 p = ncol(X)
15
16 betaInit1 = array(0, dim=c(p,m,k,20))
17 sigmaInit1 = array(0, dim = c(m,m,k,20))
18 phiInit1 = array(0, dim = c(p,m,k,20))
19 rhoInit1 = array(0, dim = c(m,m,k,20))
20 piInit1 = matrix(0,20,k)
21 gamInit1 = array(0, dim=c(n,k,20))
22 LLFinit1 = list()
23
24 require(MASS) #Moore-Penrose generalized inverse of matrix
25 for(repet in 1:20)
26 {
27 clusters = hclust(dist(y)) #default distance : euclidean
28 #cutree retourne les indices (? quel cluster indiv_i appartient) d'un clustering hierarchique
29 clusterCut = cutree(clusters,k)
30 Zinit1[,repet] = clusterCut
31
32 for(r in 1:k)
33 {
34 Z = Zinit1[,repet]
35 Z_bin = vec_bin(Z,r)
36 Z_vec = Z_bin$Z #vecteur 0 et 1 aux endroits o? Z==r
37 Z_indice = Z_bin$indice #renvoit les indices o? Z==r
38
39 betaInit1[,,r,repet] =
40 ginv(t(x[Z_indice,])%*%x[Z_indice,])%*%t(x[Z_indice,])%*%y[Z_indice,]
41 sigmaInit1[,,r,repet] = diag(m)
42 phiInit1[,,r,repet] = betaInit1[,,r,repet]/sigmaInit1[,,r,repet]
43 rhoInit1[,,r,repet] = solve(sigmaInit1[,,r,repet])
44 piInit1[repet,r] = sum(Z_vec)/n
45 }
46
47 for(i in 1:n)
48 {
49 for(r in 1:k)
50 {
51 dotProduct = (y[i,]%*%rhoInit1[,,r,repet]-x[i,]%*%phiInit1[,,r,repet]) %*%
52 (y[i,]%*%rhoInit1[,,r,repet]-x[i,]%*%phiInit1[,,r,repet])
53 Gam[i,r] = piInit1[repet,r]*det(rhoInit1[,,r,repet])*exp(-0.5*dotProduct)
54 }
55 sumGamI = sum(gam[i,])
56 gamInit1[i,,repet]= Gam[i,] / sumGamI
57 }
58
59 miniInit = 10
60 maxiInit = 11
61
62 new_EMG = .Call("EMGLLF",phiInit1[,,,repet],rhoInit1[,,,repet],piInit1[repet,],
63 gamInit1[,,repet],miniInit,maxiInit,1,0,x,y,tau)
64 LLFEessai = new_EMG$LLF
65 LLFinit1[repet] = LLFEessai[length(LLFEessai)]
66 }
67
68 b = which.max(LLFinit1)
69 phiInit = phiInit1[,,,b]
70 rhoInit = rhoInit1[,,,b]
71 piInit = piInit1[b,]
72 gamInit = gamInit1[,,b]
73
74 return (list(phiInit=phiInit, rhoInit=rhoInit, piInit=piInit, gamInit=gamInit))
75 }