ignore local files (projects, R history...)
[valse.git] / R / essai16mars.R
1 meanX = rep(0,6)
2 covX = 0.1*diag(6)
3
4 covY = array(dim = c(5,5,2))
5 covY[,,1] = 0.1*diag(5)
6 covY[,,2] = 0.2*diag(5)
7
8 beta = array(dim = c(6,5,2))
9 beta[,,2] = matrix(c(rep(2,12),rep(0, 18)))
10 beta[,,1] = matrix(c(rep(1,12),rep(0, 18)))
11
12 n = 500
13
14 pi = c(0.4,0.6)
15
16 source('~/valse/R/generateSampleInputs.R')
17 data = generateXY(meanX,covX,covY, pi, beta, n)
18
19 X = data$X
20 Y = data$Y
21
22 k = 2
23
24 n = nrow(Y)
25 m = ncol(Y)
26 p = ncol(X)
27
28 Zinit1 = array(0, dim=c(n))
29 betaInit1 = array(0, dim=c(p,m,k))
30 sigmaInit1 = array(0, dim = c(m,m,k))
31 phiInit1 = array(0, dim = c(p,m,k))
32 rhoInit1 = array(0, dim = c(m,m,k))
33 Gam = matrix(0, n, k)
34 piInit1 = matrix(0,k)
35 gamInit1 = array(0, dim=c(n,k))
36 LLFinit1 = list()
37
38 require(MASS) #Moore-Penrose generalized inverse of matrix
39
40 distance_clus = dist(X)
41 tree_hier = hclust(distance_clus)
42 Zinit1 = cutree(tree_hier, k)
43 sum(Zinit1==1)
44
45 for(r in 1:k)
46 {
47 Z = Zinit1
48 Z_indice = seq_len(n)[Z == r] #renvoit les indices où Z==r
49 if (length(Z_indice) == 1) {
50 betaInit1[,,r] = ginv(crossprod(t(X[Z_indice,]))) %*%
51 crossprod(t(X[Z_indice,]), Y[Z_indice,])
52 } else {
53 betaInit1[,,r] = ginv(crossprod(X[Z_indice,])) %*%
54 crossprod(X[Z_indice,], Y[Z_indice,])
55 }
56 sigmaInit1[,,r] = diag(m)
57 phiInit1[,,r] = betaInit1[,,r] #/ sigmaInit1[,,r]
58 rhoInit1[,,r] = solve(sigmaInit1[,,r])
59 piInit1[r] = mean(Z == r)
60 }
61
62 for(i in 1:n)
63 {
64 for(r in 1:k)
65 {
66 dotProduct = tcrossprod(Y[i,]%*%rhoInit1[,,r]-X[i,]%*%phiInit1[,,r])
67 Gam[i,r] = piInit1[r]*det(rhoInit1[,,r])*exp(-0.5*dotProduct)
68 }
69 sumGamI = sum(Gam[i,])
70 gamInit1[i,]= Gam[i,] / sumGamI
71 }
72
73 miniInit = 10
74 maxiInit = 101
75
76 new_EMG = EMGLLF(phiInit1,rhoInit1,piInit1,gamInit1,miniInit,maxiInit,1,0,X,Y,1e-6)
77
78 new_EMG$phi
79 new_EMG$pi
80 LLFEessai = new_EMG$LLF
81 LLFinit1 = LLFEessai[length(LLFEessai)]
82
83
84 b = which.max(LLFinit1)
85 phiInit = phiInit1[,,,b]
86 rhoInit = rhoInit1[,,,b]
87 piInit = piInit1[b,]
88 gamInit = gamInit1[,,b]