Commit | Line | Data |
---|---|---|
4263503b | 1 | #' Wrapper function for OptimParams class |
cbd88fe5 BA |
2 | #' |
3 | #' @param K Number of populations. | |
4 | #' @param link The link type, 'logit' or 'probit'. | |
4263503b BA |
5 | #' @param X Data matrix of covariables |
6 | #' @param Y Output as a binary vector | |
cbd88fe5 BA |
7 | #' |
8 | #' @return An object 'op' of class OptimParams, initialized so that \code{op$run(x0)} | |
9 | #' outputs the list of optimized parameters | |
10 | #' \itemize{ | |
11 | #' \item p: proportions, size K | |
12 | #' \item β: regression matrix, size dxK | |
13 | #' \item b: intercepts, size K | |
14 | #' } | |
15 | #' x0 is a vector containing respectively the K-1 first elements of p, then β by | |
16 | #' columns, and finally b: \code{x0 = c(p[1:(K-1)],as.double(β),b)}. | |
17 | #' | |
18 | #' @seealso \code{multiRun} to estimate statistics based on β, and | |
19 | #' \code{generateSampleIO} for I/O random generation. | |
20 | #' | |
21 | #' @examples | |
22 | #' # Optimize parameters from estimated μ | |
23 | #' io = generateSampleIO(10000, 1/2, matrix(c(1,-2,3,1),ncol=2), c(0,0), "logit") | |
24 | #' μ = computeMu(io$X, io$Y, list(K=2)) | |
4263503b BA |
25 | #' o <- optimParams(io$X, io$Y, 2, "logit") |
26 | #' x0 <- list(p=1/2, β=μ, b=c(0,0)) | |
cbd88fe5 BA |
27 | #' par0 <- o$run(x0) |
28 | #' # Compare with another starting point | |
4263503b | 29 | #' x1 <- list(p=1/2, β=2*μ, b=c(0,0)) |
cbd88fe5 BA |
30 | #' par1 <- o$run(x1) |
31 | #' o$f( o$linArgs(par0) ) | |
32 | #' o$f( o$linArgs(par1) ) | |
33 | #' @export | |
4263503b | 34 | optimParams = function(X, Y, K, link=c("logit","probit")) |
cbd88fe5 BA |
35 | { |
36 | # Check arguments | |
4263503b BA |
37 | if (!is.matrix(X) || any(is.na(X))) |
38 | stop("X: numeric matrix, no NAs") | |
39 | if (!is.numeric(Y) || any(is.na(Y)) || any(Y!=0 | Y!=1)) | |
40 | stop("Y: binary vector with 0 and 1 only") | |
cbd88fe5 | 41 | link <- match.arg(link) |
4263503b BA |
42 | if (!is.numeric(K) || K!=floor(K) || K < 2) |
43 | stop("K: integer >= 2") | |
cbd88fe5 | 44 | |
cbd88fe5 | 45 | # Build and return optimization algorithm object |
4263503b BA |
46 | methods::new("OptimParams", "li"=link, "X"=X, |
47 | "Y"=as.integer(Y), "K"=as.integer(K)) | |
cbd88fe5 BA |
48 | } |
49 | ||
4263503b BA |
50 | #' Encapsulated optimization for p (proportions), β and b (regression parameters) |
51 | #' | |
52 | #' Optimize the parameters of a mixture of logistic regressions model, possibly using | |
53 | #' \code{mu <- computeMu(...)} as a partial starting point. | |
54 | #' | |
55 | #' @field li Link function, 'logit' or 'probit' | |
56 | #' @field X Data matrix of covariables | |
57 | #' @field Y Output as a binary vector | |
58 | #' @field K Number of populations | |
59 | #' @field d Number of dimensions | |
60 | #' @field W Weights matrix (iteratively refined) | |
61 | #' | |
cbd88fe5 BA |
62 | setRefClass( |
63 | Class = "OptimParams", | |
64 | ||
65 | fields = list( | |
66 | # Inputs | |
4263503b BA |
67 | li = "character", #link function |
68 | X = "matrix", | |
69 | Y = "numeric", | |
70 | M1 = "numeric", | |
cbd88fe5 | 71 | M2 = "numeric", #M2 easier to process as a vector |
4263503b | 72 | M3 = "numeric", #same for M3 |
cbd88fe5 BA |
73 | # Dimensions |
74 | K = "integer", | |
4263503b | 75 | n = "integer", |
e92d9d9d BA |
76 | d = "integer", |
77 | # Weights matrix (generalized least square) | |
78 | W = "matrix" | |
cbd88fe5 BA |
79 | ), |
80 | ||
81 | methods = list( | |
82 | initialize = function(...) | |
83 | { | |
4263503b | 84 | "Check args and initialize K, d, W" |
cbd88fe5 | 85 | |
4263503b BA |
86 | callSuper(...) |
87 | if (!hasArg("X") || !hasArg("Y") || !hasArg("K") || !hasArg("li")) | |
cbd88fe5 | 88 | stop("Missing arguments") |
cbd88fe5 | 89 | |
4263503b BA |
90 | # Precompute empirical moments |
91 | M <- computeMoments(optargs$X,optargs$Y) | |
92 | M1 <<- as.double(M[[1]]) | |
93 | M2 <<- as.double(M[[2]]) | |
94 | M3 <<- as.double(M[[3]]) | |
95 | ||
96 | n <<- nrow(X) | |
cbd88fe5 | 97 | d <<- length(M1) |
e92d9d9d | 98 | W <<- diag(d+d^2+d^3) #initialize at W = Identity |
cbd88fe5 BA |
99 | }, |
100 | ||
101 | expArgs = function(x) | |
102 | { | |
103 | "Expand individual arguments from vector x" | |
104 | ||
105 | list( | |
106 | # p: dimension K-1, need to be completed | |
107 | "p" = c(x[1:(K-1)], 1-sum(x[1:(K-1)])), | |
108 | "β" = matrix(x[K:(K+d*K-1)], ncol=K), | |
109 | "b" = x[(K+d*K):(K+(d+1)*K-1)]) | |
110 | }, | |
111 | ||
112 | linArgs = function(o) | |
113 | { | |
114 | " Linearize vectors+matrices into a vector x" | |
115 | ||
116 | c(o$p[1:(K-1)], as.double(o$β), o$b) | |
117 | }, | |
118 | ||
4263503b BA |
119 | getOmega = function(theta) |
120 | { | |
121 | dim <- d + d^2 + d^3 | |
122 | matrix( .C("Compute_Omega", | |
123 | X=as.double(X), Y=as.double(Y), pn=as.integer(n), pd=as.integer(d), | |
124 | p=as.double(theta$p), β=as.double(theta$β), b=as.double(theta$b), | |
125 | W=as.double(W), PACKAGE="morpheus")$W, nrow=dim, ncol=dim) | |
126 | }, | |
127 | ||
128 | f = function(theta) | |
129 | { | |
e92d9d9d | 130 | "Product t(Mi - hat_Mi) W (Mi - hat_Mi) with Mi(theta)" |
cbd88fe5 | 131 | |
4263503b BA |
132 | p <- theta$p |
133 | β <- theta$β | |
cbd88fe5 | 134 | λ <- sqrt(colSums(β^2)) |
4263503b | 135 | b <- theta$b |
cbd88fe5 BA |
136 | |
137 | # Tensorial products β^2 = β2 and β^3 = β3 must be computed from current β1 | |
138 | β2 <- apply(β, 2, function(col) col %o% col) | |
139 | β3 <- apply(β, 2, function(col) col %o% col %o% col) | |
140 | ||
4263503b BA |
141 | A <- matrix(c( |
142 | β %*% (p * .G(li,1,λ,b)) - M1, | |
143 | β2 %*% (p * .G(li,2,λ,b)) - M2, | |
144 | β3 %*% (p * .G(li,3,λ,b)) - M3), ncol=1) | |
145 | t(A) %*% W %*% A | |
146 | }, | |
cbd88fe5 BA |
147 | |
148 | grad_f = function(x) | |
149 | { | |
150 | "Gradient of f, dimension (K-1) + d*K + K = (d+2)*K - 1" | |
151 | ||
4263503b BA |
152 | # TODO: formula -2 t(grad M(theta)) . W . (Mhat - M(theta)) |
153 | } | |
154 | ||
155 | grad_M = function(theta) | |
156 | { | |
157 | # TODO: adapt code below for grad of d+d^2+d^3 vector of moments, | |
158 | # instead of grad (sum(Mhat-M(theta)^2)) --> should be easier | |
159 | ||
160 | P <- expArgs(x) | |
cbd88fe5 BA |
161 | p <- P$p |
162 | β <- P$β | |
163 | λ <- sqrt(colSums(β^2)) | |
164 | μ <- sweep(β, 2, λ, '/') | |
165 | b <- P$b | |
166 | ||
167 | # Tensorial products β^2 = β2 and β^3 = β3 must be computed from current β1 | |
168 | β2 <- apply(β, 2, function(col) col %o% col) | |
169 | β3 <- apply(β, 2, function(col) col %o% col %o% col) | |
170 | ||
171 | # Some precomputations | |
172 | G1 = .G(li,1,λ,b) | |
173 | G2 = .G(li,2,λ,b) | |
174 | G3 = .G(li,3,λ,b) | |
175 | G4 = .G(li,4,λ,b) | |
176 | G5 = .G(li,5,λ,b) | |
177 | ||
178 | # (Mi - hat_Mi)^2 ' == (Mi - hat_Mi)' 2(Mi - hat_Mi) = Mi' Fi | |
179 | F1 = as.double( 2 * ( β %*% (p * G1) - M1 ) ) | |
180 | F2 = as.double( 2 * ( β2 %*% (p * G2) - M2 ) ) | |
181 | F3 = as.double( 2 * ( β3 %*% (p * G3) - M3 ) ) | |
182 | ||
183 | km1 = 1:(K-1) | |
184 | grad <- #gradient on p | |
e92d9d9d BA |
185 | t( sweep(as.matrix(β [,km1]), 2, G1[km1], '*') - G1[K] * β [,K] ) %*% F1 + |
186 | t( sweep(as.matrix(β2[,km1]), 2, G2[km1], '*') - G2[K] * β2[,K] ) %*% F2 + | |
187 | t( sweep(as.matrix(β3[,km1]), 2, G3[km1], '*') - G3[K] * β3[,K] ) %*% F3 | |
cbd88fe5 BA |
188 | |
189 | grad_β <- matrix(nrow=d, ncol=K) | |
190 | for (i in 1:d) | |
191 | { | |
192 | # i determines the derivated matrix dβ[2,3] | |
193 | ||
194 | dβ_left <- sweep(β, 2, p * G3 * β[i,], '*') | |
195 | dβ_right <- matrix(0, nrow=d, ncol=K) | |
196 | block <- i | |
197 | dβ_right[block,] <- dβ_right[block,] + 1 | |
198 | dβ <- dβ_left + sweep(dβ_right, 2, p * G1, '*') | |
199 | ||
200 | dβ2_left <- sweep(β2, 2, p * G4 * β[i,], '*') | |
201 | dβ2_right <- do.call( rbind, lapply(1:d, function(j) { | |
202 | sweep(dβ_right, 2, β[j,], '*') | |
203 | }) ) | |
204 | block <- ((i-1)*d+1):(i*d) | |
205 | dβ2_right[block,] <- dβ2_right[block,] + β | |
206 | dβ2 <- dβ2_left + sweep(dβ2_right, 2, p * G2, '*') | |
207 | ||
208 | dβ3_left <- sweep(β3, 2, p * G5 * β[i,], '*') | |
209 | dβ3_right <- do.call( rbind, lapply(1:d, function(j) { | |
210 | sweep(dβ2_right, 2, β[j,], '*') | |
211 | }) ) | |
212 | block <- ((i-1)*d*d+1):(i*d*d) | |
213 | dβ3_right[block,] <- dβ3_right[block,] + β2 | |
214 | dβ3 <- dβ3_left + sweep(dβ3_right, 2, p * G3, '*') | |
215 | ||
e92d9d9d | 216 | grad_β[i,] <- t(dβ) %*% F1 + t(dβ2) %*% F2 + t(dβ3) %*% F3 |
cbd88fe5 BA |
217 | } |
218 | grad <- c(grad, as.double(grad_β)) | |
219 | ||
220 | grad = c(grad, #gradient on b | |
e92d9d9d BA |
221 | t( sweep(β, 2, p * G2, '*') ) %*% F1 + |
222 | t( sweep(β2, 2, p * G3, '*') ) %*% F2 + | |
223 | t( sweep(β3, 2, p * G4, '*') ) %*% F3 ) | |
cbd88fe5 BA |
224 | |
225 | grad | |
226 | }, | |
227 | ||
4263503b | 228 | # TODO: rename x(0) into theta(0) --> θ |
cbd88fe5 BA |
229 | run = function(x0) |
230 | { | |
231 | "Run optimization from x0 with solver..." | |
232 | ||
d294ece1 BA |
233 | if (!is.list(x0)) |
234 | stop("x0: list") | |
235 | if (is.null(x0$β)) | |
236 | stop("At least x0$β must be provided") | |
237 | if (!is.matrix(x0$β) || any(is.na(x0$β)) || ncol(x0$β) != K) | |
238 | stop("x0$β: matrix, no NA, ncol == K") | |
239 | if (is.null(x0$p)) | |
240 | x0$p = rep(1/K, K-1) | |
241 | else if (length(x0$p) != K-1 || sum(x0$p) > 1) | |
242 | stop("x0$p should contain positive integers and sum to < 1") | |
243 | # Next test = heuristic to detect missing b (when matrix is called "beta") | |
244 | if (is.null(x0$b) || all(x0$b == x0$β)) | |
245 | x0$b = rep(0, K) | |
246 | else if (any(is.na(x0$b))) | |
247 | stop("x0$b cannot have missing values") | |
248 | ||
249 | op_res = constrOptim( linArgs(x0), .self$f, .self$grad_f, | |
cbd88fe5 BA |
250 | ui=cbind( |
251 | rbind( rep(-1,K-1), diag(K-1) ), | |
252 | matrix(0, nrow=K, ncol=(d+1)*K) ), | |
253 | ci=c(-1,rep(0,K-1)) ) | |
254 | ||
4263503b BA |
255 | # We get a first non-trivial estimation of W: getOmega(theta)^{-1} |
256 | # TODO: loop, this redefine f, so that we can call constrOptim again... | |
257 | # Stopping condition? N iterations? Delta <= ε ? | |
258 | ||
cbd88fe5 BA |
259 | expArgs(op_res$par) |
260 | } | |
261 | ) | |
262 | ) | |
263 | ||
264 | # Compute vectorial E[g^{(order)}(<β,x> + b)] with x~N(0,Id) (integral in R^d) | |
265 | # = E[g^{(order)}(z)] with z~N(b,diag(λ)) | |
4263503b | 266 | # by numerically evaluating the integral. |
cbd88fe5 BA |
267 | # |
268 | # @param link Link, 'logit' or 'probit' | |
269 | # @param order Order of derivative | |
270 | # @param λ Norm of columns of β | |
271 | # @param b Intercept | |
272 | # | |
273 | .G <- function(link, order, λ, b) | |
274 | { | |
275 | # NOTE: weird "integral divergent" error on inputs: | |
276 | # link="probit"; order=2; λ=c(531.8099,586.8893,523.5816); b=c(-118.512674,-3.488020,2.109969) | |
277 | # Switch to pracma package for that (but it seems slow...) | |
4263503b BA |
278 | sapply( seq_along(λ), function(k) { |
279 | res <- NULL | |
280 | tryCatch({ | |
281 | # Fast code, may fail: | |
282 | res <- stats::integrate( | |
283 | function(z) .deriv[[link]][[order]](λ[k]*z+b[k]) * exp(-z^2/2) / sqrt(2*pi), | |
284 | lower=-Inf, upper=Inf )$value | |
285 | }, error = function(e) { | |
286 | # Robust slow code, no fails observed: | |
287 | sink("/dev/null") #pracma package has some useless printed outputs... | |
288 | res <- pracma::integral( | |
289 | function(z) .deriv[[link]][[order]](λ[k]*z+b[k]) * exp(-z^2/2) / sqrt(2*pi), | |
290 | xmin=-Inf, xmax=Inf, method="Kronrod") | |
291 | sink() | |
292 | }) | |
293 | res | |
294 | }) | |
cbd88fe5 BA |
295 | } |
296 | ||
297 | # Derivatives list: g^(k)(x) for links 'logit' and 'probit' | |
298 | # | |
299 | .deriv <- list( | |
300 | "probit"=list( | |
301 | # 'probit' derivatives list; | |
4263503b | 302 | # NOTE: exact values for the integral E[g^(k)(λz+b)] could be computed |
cbd88fe5 BA |
303 | function(x) exp(-x^2/2)/(sqrt(2*pi)), #g' |
304 | function(x) exp(-x^2/2)/(sqrt(2*pi)) * -x, #g'' | |
305 | function(x) exp(-x^2/2)/(sqrt(2*pi)) * ( x^2 - 1), #g^(3) | |
306 | function(x) exp(-x^2/2)/(sqrt(2*pi)) * (-x^3 + 3*x), #g^(4) | |
307 | function(x) exp(-x^2/2)/(sqrt(2*pi)) * ( x^4 - 6*x^2 + 3) #g^(5) | |
308 | ), | |
309 | "logit"=list( | |
310 | # Sigmoid derivatives list, obtained with http://www.derivative-calculator.net/ | |
311 | # @seealso http://www.ece.uc.edu/~aminai/papers/minai_sigmoids_NN93.pdf | |
312 | function(x) {e=exp(x); .zin(e /(e+1)^2)}, #g' | |
313 | function(x) {e=exp(x); .zin(e*(-e + 1) /(e+1)^3)}, #g'' | |
314 | function(x) {e=exp(x); .zin(e*( e^2 - 4*e + 1) /(e+1)^4)}, #g^(3) | |
315 | function(x) {e=exp(x); .zin(e*(-e^3 + 11*e^2 - 11*e + 1) /(e+1)^5)}, #g^(4) | |
316 | function(x) {e=exp(x); .zin(e*( e^4 - 26*e^3 + 66*e^2 - 26*e + 1)/(e+1)^6)} #g^(5) | |
317 | ) | |
318 | ) | |
319 | ||
320 | # Utility for integration: "[return] zero if [argument is] NaN" (Inf / Inf divs) | |
321 | # | |
322 | # @param x Ratio of polynoms of exponentials, as in .S[[i]] | |
323 | # | |
324 | .zin <- function(x) | |
325 | { | |
326 | x[is.nan(x)] <- 0. | |
327 | x | |
328 | } |