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