Comment each function in R
[valse.git] / pkg / R / EMGLLF.R
1 #' EMGLLF
2 #'
3 #' Run a generalized EM algorithm developped for mixture of Gaussian regression
4 #' models with variable selection by an extension of the Lasso estimator (regularization parameter lambda).
5 #' Reparametrization is done to ensure invariance by homothetic transformation.
6 #' It returns a collection of models, varying the number of clusters and the sparsity in the regression mean.
7 #'
8 #' @param phiInit an initialization for phi
9 #' @param rhoInit an initialization for rho
10 #' @param piInit an initialization for pi
11 #' @param gamInit initialization for the a posteriori probabilities
12 #' @param mini integer, minimum number of iterations in the EM algorithm, by default = 10
13 #' @param maxi integer, maximum number of iterations in the EM algorithm, by default = 100
14 #' @param gamma integer for the power in the penaly, by default = 1
15 #' @param lambda regularization parameter in the Lasso estimation
16 #' @param X matrix of covariates (of size n*p)
17 #' @param Y matrix of responses (of size n*m)
18 #' @param eps real, threshold to say the EM algorithm converges, by default = 1e-4
19 #'
20 #' @return A list (corresponding to the model collection) defined by (phi,rho,pi,LLF,S,affec):
21 #' phi : regression mean for each cluster
22 #' rho : variance (homothetic) for each cluster
23 #' pi : proportion for each cluster
24 #' LLF : log likelihood with respect to the training set
25 #' S : selected variables indexes
26 #' affec : cluster affectation for each observation (of the training set)
27 #'
28 #' @export
29 EMGLLF <- function(phiInit, rhoInit, piInit, gamInit, mini, maxi, gamma, lambda,
30 X, Y, eps, fast)
31 {
32 if (!fast)
33 {
34 # Function in R
35 return(.EMGLLF_R(phiInit, rhoInit, piInit, gamInit, mini, maxi, gamma, lambda,
36 X, Y, eps))
37 }
38
39 # Function in C
40 n <- nrow(X) #nombre d'echantillons
41 p <- ncol(X) #nombre de covariables
42 m <- ncol(Y) #taille de Y (multivarié)
43 k <- length(piInit) #nombre de composantes dans le mélange
44 .Call("EMGLLF", phiInit, rhoInit, piInit, gamInit, mini, maxi, gamma, lambda,
45 X, Y, eps, phi = double(p * m * k), rho = double(m * m * k), pi = double(k),
46 llh = double(1), S = double(p * m * k), affec = integer(n), n, p, m, k,
47 PACKAGE = "valse")
48 }
49
50 # R version - slow but easy to read
51 .EMGLLF_R <- function(phiInit, rhoInit, piInit, gamInit, mini, maxi, gamma, lambda,
52 X, Y, eps)
53 {
54 # Matrix dimensions
55 n <- nrow(X)
56 p <- ncol(X)
57 m <- ncol(Y)
58 k <- length(piInit)
59
60 # Adjustments required when p==1 or m==1 (var.sel. or output dim 1)
61 if (p==1 || m==1)
62 phiInit <- array(phiInit, dim=c(p,m,k))
63 if (m==1)
64 rhoInit <- array(rhoInit, dim=c(m,m,k))
65
66 # Outputs
67 phi <- phiInit
68 rho <- rhoInit
69 pi <- piInit
70 llh <- -Inf
71 S <- array(0, dim = c(p, m, k))
72
73 # Algorithm variables
74 gam <- gamInit
75 Gram2 <- array(0, dim = c(p, p, k))
76 ps2 <- array(0, dim = c(p, m, k))
77 X2 <- array(0, dim = c(n, p, k))
78 Y2 <- array(0, dim = c(n, m, k))
79
80 for (ite in 1:maxi)
81 {
82 # Remember last pi,rho,phi values for exit condition in the end of loop
83 Phi <- phi
84 Rho <- rho
85 Pi <- pi
86
87 # Computations associated to X and Y
88 for (r in 1:k)
89 {
90 for (mm in 1:m)
91 Y2[, mm, r] <- sqrt(gam[, r]) * Y[, mm]
92 for (i in 1:n)
93 X2[i, , r] <- sqrt(gam[i, r]) * X[i, ]
94 for (mm in 1:m)
95 ps2[, mm, r] <- crossprod(X2[, , r], Y2[, mm, r])
96 for (j in 1:p)
97 {
98 for (s in 1:p)
99 Gram2[j, s, r] <- crossprod(X2[, j, r], X2[, s, r])
100 }
101 }
102
103 ## M step
104
105 # For pi
106 b <- sapply(1:k, function(r) sum(abs(phi[, , r])))
107 gam2 <- colSums(gam)
108 a <- sum(gam %*% log(pi))
109
110 # While the proportions are nonpositive
111 kk <- 0
112 pi2AllPositive <- FALSE
113 while (!pi2AllPositive)
114 {
115 pi2 <- pi + 0.1^kk * ((1/n) * gam2 - pi)
116 pi2AllPositive <- all(pi2 >= 0)
117 kk <- kk + 1
118 }
119
120 # t(m) is the largest value in the grid O.1^k such that it is nonincreasing
121 while (kk < 1000 && -a/n + lambda * sum(pi^gamma * b) <
122 # na.rm=TRUE to handle 0*log(0)
123 -sum(gam2 * log(pi2), na.rm=TRUE)/n + lambda * sum(pi2^gamma * b))
124 {
125 pi2 <- pi + 0.1^kk * (1/n * gam2 - pi)
126 kk <- kk + 1
127 }
128 t <- 0.1^kk
129 pi <- (pi + t * (pi2 - pi))/sum(pi + t * (pi2 - pi))
130
131 # For phi and rho
132 for (r in 1:k)
133 {
134 for (mm in 1:m)
135 {
136 ps <- 0
137 for (i in 1:n)
138 ps <- ps + Y2[i, mm, r] * sum(X2[i, , r] * phi[, mm, r])
139 nY2 <- sum(Y2[, mm, r]^2)
140 rho[mm, mm, r] <- (ps + sqrt(ps^2 + 4 * nY2 * gam2[r]))/(2 * nY2)
141 }
142 }
143
144 for (r in 1:k)
145 {
146 for (j in 1:p)
147 {
148 for (mm in 1:m)
149 {
150 S[j, mm, r] <- -rho[mm, mm, r] * ps2[j, mm, r] +
151 sum(phi[-j, mm, r] * Gram2[j, -j, r])
152 if (abs(S[j, mm, r]) <= n * lambda * (pi[r]^gamma)) {
153 phi[j, mm, r] <- 0
154 } else if (S[j, mm, r] > n * lambda * (pi[r]^gamma)) {
155 phi[j, mm, r] <- (n * lambda * (pi[r]^gamma) - S[j, mm, r])/Gram2[j, j, r]
156 } else {
157 phi[j, mm, r] <- -(n * lambda * (pi[r]^gamma) + S[j, mm, r])/Gram2[j, j, r]
158 }
159 }
160 }
161 }
162
163 ## E step
164
165 # Precompute det(rho[,,r]) for r in 1...k
166 detRho <- sapply(1:k, function(r) gdet(rho[, , r]))
167 sumLogLLH <- 0
168 for (i in 1:n)
169 {
170 # Update gam[,]; use log to avoid numerical problems
171 logGam <- sapply(1:k, function(r) {
172 log(pi[r]) + log(detRho[r]) - 0.5 *
173 sum((Y[i, ] %*% rho[, , r] - X[i, ] %*% phi[, , r])^2)
174 })
175
176 logGam <- logGam - max(logGam) #adjust without changing proportions
177 gam[i, ] <- exp(logGam)
178 norm_fact <- sum(gam[i, ])
179 gam[i, ] <- gam[i, ] / norm_fact
180 sumLogLLH <- sumLogLLH + log(norm_fact) - log((2 * base::pi)^(m/2))
181 }
182
183 sumPen <- sum(pi^gamma * b)
184 last_llh <- llh
185 llh <- -sumLogLLH/n #+ lambda * sumPen
186 dist <- ifelse(ite == 1, llh, (llh - last_llh)/(1 + abs(llh)))
187 Dist1 <- max((abs(phi - Phi))/(1 + abs(phi)))
188 Dist2 <- max((abs(rho - Rho))/(1 + abs(rho)))
189 Dist3 <- max((abs(pi - Pi))/(1 + abs(Pi)))
190 dist2 <- max(Dist1, Dist2, Dist3)
191
192 if (ite >= mini && (dist >= eps || dist2 >= sqrt(eps)))
193 break
194 }
195
196 affec = apply(gam, 1, which.max)
197 list(phi = phi, rho = rho, pi = pi, llh = llh, S = S, affec=affec)
198 }