1 #' Wrapper function for OptimParams class
3 #' @param K Number of populations.
4 #' @param link The link type, 'logit' or 'probit'.
5 #' @param X Data matrix of covariables
6 #' @param Y Output as a binary vector
8 #' @return An object 'op' of class OptimParams, initialized so that \code{op$run(x0)}
9 #' outputs the list of optimized parameters
11 #' \item p: proportions, size K
12 #' \item β: regression matrix, size dxK
13 #' \item b: intercepts, size K
15 #' θ0 is a vector containing respectively the K-1 first elements of p, then β by
16 #' columns, and finally b: \code{θ0 = c(p[1:(K-1)],as.double(β),b)}.
18 #' @seealso \code{multiRun} to estimate statistics based on β, and
19 #' \code{generateSampleIO} for I/O random generation.
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))
25 #' o <- optimParams(io$X, io$Y, 2, "logit")
26 #' θ0 <- list(p=1/2, β=μ, b=c(0,0))
28 #' # Compare with another starting point
29 #' θ1 <- list(p=1/2, β=2*μ, b=c(0,0))
31 #' o$f( o$linArgs(par0) )
32 #' o$f( o$linArgs(par1) )
34 optimParams = function(X, Y, K, link=c("logit","probit"))
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")
41 link <- match.arg(link)
42 if (!is.numeric(K) || K!=floor(K) || K < 2)
43 stop("K: integer >= 2")
45 # Build and return optimization algorithm object
46 methods::new("OptimParams", "li"=link, "X"=X,
47 "Y"=as.integer(Y), "K"=as.integer(K))
50 #' Encapsulated optimization for p (proportions), β and b (regression parameters)
52 #' Optimize the parameters of a mixture of logistic regressions model, possibly using
53 #' \code{mu <- computeMu(...)} as a partial starting point.
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)
63 Class = "OptimParams",
67 li = "character", #link function
70 Mhat = "numeric", #vector of empirical moments
75 # Weights matrix (generalized least square)
80 initialize = function(...)
82 "Check args and initialize K, d, W"
85 if (!hasArg("X") || !hasArg("Y") || !hasArg("K") || !hasArg("li"))
86 stop("Missing arguments")
88 # Precompute empirical moments
89 M <- computeMoments(optargs$X,optargs$Y)
90 M1 <- as.double(M[[1]])
91 M2 <- as.double(M[[2]])
92 M3 <- as.double(M[[3]])
93 Mhat <<- matrix(c(M1,M2,M3), ncol=1)
97 W <<- diag(d+d^2+d^3) #initialize at W = Identity
100 expArgs = function(v)
102 "Expand individual arguments from vector v into a list"
105 # p: dimension K-1, need to be completed
106 "p" = c(v[1:(K-1)], 1-sum(v[1:(K-1)])),
107 "β" = matrix(v[K:(K+d*K-1)], ncol=K),
108 "b" = v[(K+d*K):(K+(d+1)*K-1)])
111 linArgs = function(L)
113 "Linearize vectors+matrices from list L into a vector"
115 c(L$p[1:(K-1)], as.double(L$β), L$b)
118 computeW = function(θ)
121 W <<- solve( matrix( .C("Compute_Omega",
122 X=as.double(X), Y=as.double(Y), M=as.double(M(θ)),
123 pn=as.integer(n), pd=as.integer(d),
124 W=as.double(W), PACKAGE="morpheus")$W, nrow=dim, ncol=dim) )
125 NULL #avoid returning W
130 "Vector of moments, of size d+d^2+d^3"
134 λ <- sqrt(colSums(β^2))
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)
142 β %*% (p * .G(li,1,λ,b)),
143 β2 %*% (p * .G(li,2,λ,b)),
144 β3 %*% (p * .G(li,3,λ,b))), ncol=1)
149 "Product t(Mi - hat_Mi) W (Mi - hat_Mi) with Mi(theta)"
157 "Gradient of f, dimension (K-1) + d*K + K = (d+2)*K - 1"
159 -2 * t(grad_M(θ)) %*% getW(θ) %*% (Mhat - M(θ))
164 "Gradient of the vector of moments, size (dim=)d+d^2+d^3 x K-1+K+d*K"
169 λ <- sqrt(colSums(β^2))
170 μ <- sweep(β, 2, λ, '/')
173 res <- matrix(nrow=nrow(W), ncol=0)
175 # Tensorial products β^2 = β2 and β^3 = β3 must be computed from current β1
176 β2 <- apply(β, 2, function(col) col %o% col)
177 β3 <- apply(β, 2, function(col) col %o% col %o% col)
179 # Some precomputations
186 # Gradient on p: K-1 columns, dim rows
188 res <- cbind(res, rbind(
189 t( sweep(as.matrix(β [,km1]), 2, G1[km1], '*') - G1[K] * β [,K] ),
190 t( sweep(as.matrix(β2[,km1]), 2, G2[km1], '*') - G2[K] * β2[,K] ),
191 t( sweep(as.matrix(β3[,km1]), 2, G3[km1], '*') - G3[K] * β3[,K] )))
195 # i determines the derivated matrix dβ[2,3]
197 dβ_left <- sweep(β, 2, p * G3 * β[i,], '*')
198 dβ_right <- matrix(0, nrow=d, ncol=K)
200 dβ_right[block,] <- dβ_right[block,] + 1
201 dβ <- dβ_left + sweep(dβ_right, 2, p * G1, '*')
203 dβ2_left <- sweep(β2, 2, p * G4 * β[i,], '*')
204 dβ2_right <- do.call( rbind, lapply(1:d, function(j) {
205 sweep(dβ_right, 2, β[j,], '*')
207 block <- ((i-1)*d+1):(i*d)
208 dβ2_right[block,] <- dβ2_right[block,] + β
209 dβ2 <- dβ2_left + sweep(dβ2_right, 2, p * G2, '*')
211 dβ3_left <- sweep(β3, 2, p * G5 * β[i,], '*')
212 dβ3_right <- do.call( rbind, lapply(1:d, function(j) {
213 sweep(dβ2_right, 2, β[j,], '*')
215 block <- ((i-1)*d*d+1):(i*d*d)
216 dβ3_right[block,] <- dβ3_right[block,] + β2
217 dβ3 <- dβ3_left + sweep(dβ3_right, 2, p * G3, '*')
219 res <- cbind(res, rbind(t(dβ), t(dβ2), t(dβ3)))
223 res <- cbind(res, rbind(
224 t( sweep(β, 2, p * G2, '*') ),
225 t( sweep(β2, 2, p * G3, '*') ),
226 t( sweep(β3, 2, p * G4, '*') )))
233 "Run optimization from θ0 with solver..."
238 stop("At least θ0$β must be provided")
239 if (!is.matrix(θ0$β) || any(is.na(θ0$β)) || ncol(θ0$β) != K)
240 stop("θ0$β: matrix, no NA, ncol == K")
243 else if (length(θ0$p) != K-1 || sum(θ0$p) > 1)
244 stop("θ0$p should contain positive integers and sum to < 1")
245 # Next test = heuristic to detect missing b (when matrix is called "beta")
246 if (is.null(θ0$b) || all(θ0$b == θ0$β))
248 else if (any(is.na(θ0$b)))
249 stop("θ0$b cannot have missing values")
251 op_res = constrOptim( linArgs(θ0), .self$f, .self$grad_f,
253 rbind( rep(-1,K-1), diag(K-1) ),
254 matrix(0, nrow=K, ncol=(d+1)*K) ),
255 ci=c(-1,rep(0,K-1)) )
258 print(computeW(expArgs(op_res$par)))
259 # We get a first non-trivial estimation of W
260 # TODO: loop, this redefine f, so that we can call constrOptim again...
261 # Stopping condition? N iterations? Delta <= ε ?
268 # Compute vectorial E[g^{(order)}(<β,x> + b)] with x~N(0,Id) (integral in R^d)
269 # = E[g^{(order)}(z)] with z~N(b,diag(λ))
270 # by numerically evaluating the integral.
272 # @param link Link, 'logit' or 'probit'
273 # @param order Order of derivative
274 # @param λ Norm of columns of β
277 .G <- function(link, order, λ, b)
279 # NOTE: weird "integral divergent" error on inputs:
280 # link="probit"; order=2; λ=c(531.8099,586.8893,523.5816); b=c(-118.512674,-3.488020,2.109969)
281 # Switch to pracma package for that (but it seems slow...)
282 sapply( seq_along(λ), function(k) {
285 # Fast code, may fail:
286 res <- stats::integrate(
287 function(z) .deriv[[link]][[order]](λ[k]*z+b[k]) * exp(-z^2/2) / sqrt(2*pi),
288 lower=-Inf, upper=Inf )$value
289 }, error = function(e) {
290 # Robust slow code, no fails observed:
291 sink("/dev/null") #pracma package has some useless printed outputs...
292 res <- pracma::integral(
293 function(z) .deriv[[link]][[order]](λ[k]*z+b[k]) * exp(-z^2/2) / sqrt(2*pi),
294 xmin=-Inf, xmax=Inf, method="Kronrod")
301 # Derivatives list: g^(k)(x) for links 'logit' and 'probit'
305 # 'probit' derivatives list;
306 # NOTE: exact values for the integral E[g^(k)(λz+b)] could be computed
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)
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)
324 # Utility for integration: "[return] zero if [argument is] NaN" (Inf / Inf divs)
326 # @param x Ratio of polynoms of exponentials, as in .S[[i]]