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