First commit
[valse.git] / pkg / R / EMGrank.R
1 #' EMGrank
2 #'
3 #' Description de EMGrank
4 #'
5 #' @param Pi Parametre de proportion
6 #' @param Rho Parametre initial de variance renormalisé
7 #' @param mini Nombre minimal d'itérations dans l'algorithme EM
8 #' @param maxi Nombre maximal d'itérations dans l'algorithme EM
9 #' @param X Régresseurs
10 #' @param Y Réponse
11 #' @param eps Seuil pour accepter la convergence
12 #' @param rank Vecteur des rangs possibles
13 #'
14 #' @return A list ...
15 #' phi : parametre de moyenne renormalisé, calculé par l'EM
16 #' LLF : log vraisemblance associé à cet échantillon, pour les valeurs estimées des paramètres
17 #'
18 #' @export
19 EMGrank <- function(Pi, Rho, mini, maxi, X, Y, eps, rank, fast = TRUE)
20 {
21 if (!fast)
22 {
23 # Function in R
24 return(.EMGrank_R(Pi, Rho, mini, maxi, X, Y, eps, rank))
25 }
26
27 # Function in C
28 n <- nrow(X) #nombre d'echantillons
29 p <- ncol(X) #nombre de covariables
30 m <- ncol(Y) #taille de Y (multivarié)
31 k <- length(Pi) #nombre de composantes dans le mélange
32 .Call("EMGrank", Pi, Rho, mini, maxi, X, Y, eps, as.integer(rank), phi = double(p * m * k),
33 LLF = double(1), n, p, m, k, PACKAGE = "valse")
34 }
35
36 # helper to always have matrices as arg (TODO: put this elsewhere? improve?) -->
37 # Yes, we should use by-columns storage everywhere... [later!]
38 matricize <- function(X)
39 {
40 if (!is.matrix(X))
41 return(t(as.matrix(X)))
42 return(X)
43 }
44
45 # R version - slow but easy to read
46 .EMGrank_R <- function(Pi, Rho, mini, maxi, X, Y, eps, rank)
47 {
48 # matrix dimensions
49 n <- nrow(X)
50 p <- ncol(X)
51 m <- ncol(Y)
52 k <- length(Pi)
53
54 # init outputs
55 phi <- array(0, dim = c(p, m, k))
56 Z <- rep(1, n)
57 LLF <- 0
58
59 # local variables
60 Phi <- array(0, dim = c(p, m, k))
61 deltaPhi <- c()
62 sumDeltaPhi <- 0
63 deltaPhiBufferSize <- 20
64
65 # main loop
66 ite <- 1
67 while (ite <= mini || (ite <= maxi && sumDeltaPhi > eps))
68 {
69 # M step: update for Beta ( and then phi)
70 for (r in 1:k)
71 {
72 Z_indice <- seq_len(n)[Z == r] #indices where Z == r
73 if (length(Z_indice) == 0)
74 next
75 # U,S,V = SVD of (t(Xr)Xr)^{-1} * t(Xr) * Yr
76 s <- svd(MASS::ginv(crossprod(matricize(X[Z_indice, ]))) %*%
77 crossprod(matricize(X[Z_indice, ]), matricize(Y[Z_indice, ])))
78 S <- s$d
79 # Set m-rank(r) singular values to zero, and recompose best rank(r) approximation
80 # of the initial product
81 if (rank[r] < length(S))
82 S[(rank[r] + 1):length(S)] <- 0
83 phi[, , r] <- s$u %*% diag(S) %*% t(s$v) %*% Rho[, , r]
84 }
85
86 # Step E and computation of the loglikelihood
87 sumLogLLF2 <- 0
88 for (i in seq_len(n))
89 {
90 sumLLF1 <- 0
91 maxLogGamIR <- -Inf
92 for (r in seq_len(k))
93 {
94 dotProduct <- tcrossprod(Y[i, ] %*% Rho[, , r] - X[i, ] %*% phi[, , r])
95 logGamIR <- log(Pi[r]) + log(gdet(Rho[, , r])) - 0.5 * dotProduct
96 # Z[i] = index of max (gam[i,])
97 if (logGamIR > maxLogGamIR)
98 {
99 Z[i] <- r
100 maxLogGamIR <- logGamIR
101 }
102 sumLLF1 <- sumLLF1 + exp(logGamIR)/(2 * pi)^(m/2)
103 }
104 sumLogLLF2 <- sumLogLLF2 + log(sumLLF1)
105 }
106
107 LLF <- -1/n * sumLogLLF2
108
109 # update distance parameter to check algorithm convergence (delta(phi, Phi))
110 deltaPhi <- c(deltaPhi, max((abs(phi - Phi))/(1 + abs(phi)))) #TODO: explain?
111 if (length(deltaPhi) > deltaPhiBufferSize)
112 deltaPhi <- deltaPhi[2:length(deltaPhi)]
113 sumDeltaPhi <- sum(abs(deltaPhi))
114
115 # update other local variables
116 Phi <- phi
117 ite <- ite + 1
118 }
119 return(list(phi = phi, LLF = LLF))
120 }