fix many problems (models appearing twice, irrelevant coefficients in a relevant...
[valse.git] / pkg / R / main.R
1 #' valse
2 #'
3 #' Main function
4 #'
5 #' @param X matrix of covariates (of size n*p)
6 #' @param Y matrix of responses (of size n*m)
7 #' @param procedure among 'LassoMLE' or 'LassoRank'
8 #' @param selecMod method to select a model among 'DDSE', 'DJump', 'BIC' or 'AIC'
9 #' @param gamma integer for the power in the penaly, by default = 1
10 #' @param mini integer, minimum number of iterations in the EM algorithm, by default = 10
11 #' @param maxi integer, maximum number of iterations in the EM algorithm, by default = 100
12 #' @param eps real, threshold to say the EM algorithm converges, by default = 1e-4
13 #' @param kmin integer, minimum number of clusters, by default = 2
14 #' @param kmax integer, maximum number of clusters, by default = 10
15 #' @param rang.min integer, minimum rank in the low rank procedure, by default = 1
16 #' @param rang.max integer, maximum rank in the
17 #' @param ncores_outer Number of cores for the outer loop on k
18 #' @param ncores_inner Number of cores for the inner loop on lambda
19 #' @param size_coll_mod (Maximum) size of a collection of models
20 #' @param fast TRUE to use compiled C code, FALSE for R code only
21 #' @param verbose TRUE to show some execution traces
22 #'
23 #' @return a list with estimators of parameters
24 #'
25 #' @examples
26 #' #TODO: a few examples
27 #' @export
28 valse = function(X, Y, procedure='LassoMLE', selecMod='DDSE', gamma=1, mini=10, maxi=50,
29 eps=1e-4, kmin=2, kmax=2, rank.min=1, rank.max=10, ncores_outer=1, ncores_inner=1,
30 size_coll_mod=10, fast=TRUE, verbose=FALSE, plot = TRUE)
31 {
32 p = dim(X)[2]
33 m = dim(Y)[2]
34 n = dim(X)[1]
35
36 if (verbose)
37 print("main loop: over all k and all lambda")
38
39 if (ncores_outer > 1)
40 {
41 cl = parallel::makeCluster(ncores_outer, outfile='')
42 parallel::clusterExport( cl=cl, envir=environment(), varlist=c("X","Y","procedure",
43 "selecMod","gamma","mini","maxi","eps","kmin","kmax","rang.min","rang.max",
44 "ncores_outer","ncores_inner","verbose","p","m") )
45 }
46
47 # Compute models with k components
48 computeModels <- function(k)
49 {
50 if (ncores_outer > 1)
51 require("valse") #nodes start with an empty environment
52
53 if (verbose)
54 print(paste("Parameters initialization for k =",k))
55 #smallEM initializes parameters by k-means and regression model in each component,
56 #doing this 20 times, and keeping the values maximizing the likelihood after 10
57 #iterations of the EM algorithm.
58 P = initSmallEM(k, X, Y)
59 grid_lambda <- computeGridLambda(P$phiInit, P$rhoInit, P$piInit, P$gamInit, X, Y,
60 gamma, mini, maxi, eps, fast)
61 if (length(grid_lambda)>size_coll_mod)
62 grid_lambda = grid_lambda[seq(1, length(grid_lambda), length.out = size_coll_mod)]
63
64 if (verbose)
65 print("Compute relevant parameters")
66 #select variables according to each regularization parameter
67 #from the grid: S$selected corresponding to selected variables
68 S = selectVariables(P$phiInit, P$rhoInit, P$piInit, P$gamInit, mini, maxi, gamma,
69 grid_lambda, X, Y, 1e-8, eps, ncores_inner, fast) #TODO: 1e-8 as arg?! eps?
70
71 if (procedure == 'LassoMLE')
72 {
73 if (verbose)
74 print('run the procedure Lasso-MLE')
75 #compute parameter estimations, with the Maximum Likelihood
76 #Estimator, restricted on selected variables.
77 models <- constructionModelesLassoMLE(P$phiInit, P$rhoInit, P$piInit, P$gamInit,
78 mini, maxi, gamma, X, Y, thresh, eps, S, ncores_inner, fast, verbose)
79 }
80 else
81 {
82 if (verbose)
83 print('run the procedure Lasso-Rank')
84 #compute parameter estimations, with the Low Rank
85 #Estimator, restricted on selected variables.
86 models <- constructionModelesLassoRank(S$Pi, S$Rho, mini, maxi, X, Y, eps, S,
87 rank.min, rank.max, ncores_inner, fast, verbose)
88 }
89 #warning! Some models are NULL after running selectVariables
90 models = models[sapply(models, function(cell) !is.null(cell))]
91 models
92 }
93
94 # List (index k) of lists (index lambda) of models
95 models_list <-
96 if (ncores_outer > 1)
97 parLapply(cl, kmin:kmax, computeModels)
98 else
99 lapply(kmin:kmax, computeModels)
100 if (ncores_outer > 1)
101 parallel::stopCluster(cl)
102
103 if (! requireNamespace("capushe", quietly=TRUE))
104 {
105 warning("'capushe' not available: returning all models")
106 return (models_list)
107 }
108
109 # Get summary "tableauRecap" from models
110 tableauRecap = do.call( rbind, lapply( seq_along(models_list), function(i) {
111 models <- models_list[[i]]
112 #For a collection of models (same k, several lambda):
113 LLH <- sapply( models, function(model) model$llh[1] )
114 k = length(models[[1]]$pi)
115 sumPen = sapply(models, function(model)
116 k*(dim(model$rho)[1]+sum(model$phi[,,1]!=0)+1)-1)
117 data.frame(model=paste(i,".",seq_along(models),sep=""),
118 pen=sumPen/n, complexity=sumPen, contrast=-LLH)
119 } ) )
120
121 print(tableauRecap)
122 tableauRecap = tableauRecap[which(tableauRecap[,4]!= Inf),]
123 modSel = capushe::capushe(tableauRecap, n)
124 indModSel <-
125 if (selecMod == 'DDSE')
126 as.numeric(modSel@DDSE@model)
127 else if (selecMod == 'Djump')
128 as.numeric(modSel@Djump@model)
129 else if (selecMod == 'BIC')
130 modSel@BIC_capushe$model
131 else if (selecMod == 'AIC')
132 modSel@AIC_capushe$model
133
134 mod = as.character(tableauRecap[indModSel,1])
135 listMod = as.integer(unlist(strsplit(mod, "[.]")))
136 modelSel = models_list[[listMod[1]]][[listMod[2]]]
137
138 ##Affectations
139 Gam = matrix(0, ncol = length(modelSel$pi), nrow = n)
140 for (i in 1:n){
141 for (r in 1:length(modelSel$pi)){
142 sqNorm2 = sum( (Y[i,]%*%modelSel$rho[,,r]-X[i,]%*%modelSel$phi[,,r])^2 )
143 Gam[i,r] = modelSel$pi[r] * exp(-0.5*sqNorm2)* det(modelSel$rho[,,r])
144 }
145 }
146 Gam = Gam/rowSums(Gam)
147 modelSel$affec = apply(Gam, 1,which.max)
148 modelSel$proba = Gam
149
150 if (plot){
151 print(plot_valse(modelSel,n))
152 }
153
154 return(modelSel)
155 }