functions.R 39.8 KB
Newer Older
Armin Rauschenberger's avatar
Armin Rauschenberger committed
1

Armin Rauschenberger's avatar
Armin Rauschenberger committed
2 3
# import unexported functions:
# FUNCTION <- get("FUNCTION",envir=asNamespace("PACKAGE"))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
4

Armin Rauschenberger's avatar
Armin Rauschenberger committed
5
#--- Main function -------------------------------------------------------------
Armin Rauschenberger's avatar
Armin Rauschenberger committed
6

Armin Rauschenberger's avatar
Armin Rauschenberger committed
7 8
#' @export
#' @title
Armin Rauschenberger's avatar
Armin Rauschenberger committed
9
#' Multivariate Elastic Net Regression
Armin Rauschenberger's avatar
Armin Rauschenberger committed
10 11
#' 
#' @description
Armin Rauschenberger's avatar
Armin Rauschenberger committed
12 13 14 15 16 17 18
#' Implements multivariate elastic net regression.
#'  
#' @param Y
#' outputs\strong{:}
#' numeric matrix with \eqn{n} rows (samples)
#' and \eqn{q} columns (variables),
#' with positive correlation (see details)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
19 20
#' 
#' @param X
Armin Rauschenberger's avatar
Armin Rauschenberger committed
21
#' inputs\strong{:}
Armin Rauschenberger's avatar
Armin Rauschenberger committed
22
#' numeric matrix with \eqn{n} rows (samples)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
23
#' and \eqn{p} columns (variables)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
24 25 26 27 28 29 30 31 32
#'
#' @param family
#' distribution\strong{:}
#' vector of length \eqn{1} or \eqn{q} with entries
#' \code{"gaussian"}, \code{"binomial"} or \code{"poisson"}
#'
#' @param nfolds
#' number of folds
#'
Armin Rauschenberger's avatar
Armin Rauschenberger committed
33 34
#' @param foldid
#' fold identifiers\strong{:}
Armin Rauschenberger's avatar
Armin Rauschenberger committed
35
#' vector of length \eqn{n} with entries between \eqn{1} and \code{nfolds};
Armin Rauschenberger's avatar
Armin Rauschenberger committed
36
#' or \code{NULL} (balance)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
37
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
38
#' @param type.measure
Armin Rauschenberger's avatar
Armin Rauschenberger committed
39 40 41 42 43 44 45 46
#' loss function\strong{:}
#' vector of length \eqn{1} or \eqn{q} with entries
#' \code{"deviance"}, \code{"class"}, \code{"mse"} or \code{"mae"}
#' (see \code{\link[glmnet]{cv.glmnet}})
#'
#' @param alpha.base
#' elastic net mixing parameter for base learners\strong{:}
#' numeric between \eqn{0} (ridge) and \eqn{1} (lasso)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
47
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
48 49
#' @param alpha.meta
#' elastic net mixing parameter for meta learner\strong{:}
Armin Rauschenberger's avatar
Armin Rauschenberger committed
50
#' numeric between \eqn{0} (ridge) and \eqn{1} (lasso)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
51
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
52 53 54
#' @param ...
#' further arguments passed to \code{\link[glmnet]{glmnet}}
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
55
#' @references 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
56 57
#' Armin Rauschenberger, Enrico Glaab (2020)
#' "Predicting correlated outcomes from molecular data"
Armin Rauschenberger's avatar
Armin Rauschenberger committed
58
#' \emph{Manuscript in preparation}.
Armin Rauschenberger's avatar
Armin Rauschenberger committed
59 60
#' 
#' @details
Armin Rauschenberger's avatar
Armin Rauschenberger committed
61
#' \strong{correlation:}
Armin Rauschenberger's avatar
Armin Rauschenberger committed
62 63
#' The \eqn{q} outcomes should be positively correlated.
#' Avoid negative correlations by changing the sign of the variable.
Armin Rauschenberger's avatar
Armin Rauschenberger committed
64
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
65
#' \strong{elastic net:}
Armin Rauschenberger's avatar
Armin Rauschenberger committed
66 67
#' \code{alpha.base} controls input-output effects,
#' \code{alpha.meta} controls output-output effects;
Armin Rauschenberger's avatar
Armin Rauschenberger committed
68 69 70 71 72 73 74 75 76 77 78
#' lasso renders sparse models (\code{alpha}\eqn{=1}),
#' ridge renders dense models (\code{alpha}\eqn{=0})
#' 
#' @return
#' This function returns an object of class \code{joinet}.
#' Available methods include
#' \code{\link[=predict.joinet]{predict}},
#' \code{\link[=coef.joinet]{coef}},
#' and \code{\link[=weights.joinet]{weights}}.
#' The slots \code{base} and \code{meta} each contain
#' \eqn{q} \code{\link[glmnet]{cv.glmnet}}-like objects.
Armin Rauschenberger's avatar
Armin Rauschenberger committed
79
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
80
#' @seealso
Armin Rauschenberger's avatar
Armin Rauschenberger committed
81
#' \code{\link{cv.joinet}}, vignette
Armin Rauschenberger's avatar
Armin Rauschenberger committed
82
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
83
#' @examples
Armin Rauschenberger's avatar
Armin Rauschenberger committed
84
#' if(!grepl('SunOS',Sys.info()['sysname'])){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
85
#' n <- 50; p <- 100; q <- 3
Armin Rauschenberger's avatar
Armin Rauschenberger committed
86
#' X <- matrix(rnorm(n*p),nrow=n,ncol=p)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
87
#' Y <- replicate(n=q,expr=rnorm(n=n,mean=rowSums(X[,1:5])))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
88
#' object <- joinet(Y=Y,X=X)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
89
#' }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
90
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
91 92 93
#' \dontrun{
#' browseVignettes("joinet") # further examples}
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
94
joinet <- function(Y,X,family="gaussian",nfolds=10,foldid=NULL,type.measure="deviance",alpha.base=1,alpha.meta=1,...){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
95
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
96
  #--- temporary ---
Armin Rauschenberger's avatar
Armin Rauschenberger committed
97
  # family <- "gaussian"; nfolds <- 10; foldid <- NULL; type.measure <- "deviance"
Armin Rauschenberger's avatar
Armin Rauschenberger committed
98
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
99
  #--- checks ---
Armin Rauschenberger's avatar
Armin Rauschenberger committed
100 101 102
  Y <- as.matrix(Y)
  X <- as.matrix(X)
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
103
  cornet:::.check(x=Y,type="matrix",miss=TRUE)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
104 105 106 107 108 109 110 111 112 113 114 115 116
  
  ### trial start ###
  for(i in 1:(ncol(Y)-1)){
    for(j in i:ncol(Y)){
      cor <- stats::cor.test(Y[,i],Y[,j],use="pairwise.complete.obs")
      if(cor$statistic<0 & cor$p.value<0.05){
        warning(paste("Columns",i,"and",j,"are negatively correlated."))
      }
    }
  }
  ### trial end ###
  
  #if(any(stats::cor(Y,use="pairwise.complete.obs")<0,na.rm=TRUE)){warning("Negative correlation!",call.=FALSE)}
Armin Rauschenberger's avatar
Armin Rauschenberger committed
117
  cornet:::.check(x=X,type="matrix")
Armin Rauschenberger's avatar
Armin Rauschenberger committed
118
  #cornet:::.check(x=family,type="vector",values=c("gaussian","binomial","poisson"))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
119 120 121 122 123 124 125 126
  if(nrow(Y)!=nrow(X)){stop("Contradictory sample size.",call.=FALSE)}
  cornet:::.check(x=nfolds,type="scalar",min=3)
  cornet:::.check(x=foldid,type="vector",values=seq_len(nfolds),null=TRUE)
  cornet:::.check(x=type.measure,type="string",values=c("deviance","class","mse","mae")) # not auc (min/max confusion)
  cornet:::.check(x=alpha.base,type="scalar",min=0,max=1)
  cornet:::.check(x=alpha.meta,type="scalar",min=0,max=1)
  if(!is.null(c(list(...)$lower.limits,list(...)$upper.limits))){
    stop("Reserved arguments \"lower.limits\" and \"upper.limits\".",call.=FALSE)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
127 128
  }
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
129 130 131 132 133 134 135 136 137 138
  #--- dimensionality ---
  n <- nrow(Y)
  q <- ncol(Y)
  p <- ncol(X)
  
  #--- family ---
  if(length(family)==1){
    family <- rep(family,times=q)
  } else if(length(family)!=q){
    stop("Invalid argument family",call.=FALSE)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
139
  }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
140
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
141 142 143 144
  #--- fold identifiers ---
  # provide foldid as matrix?
  if(is.null(foldid)){
    foldid <- palasso:::.folds(y=Y[,1],nfolds=nfolds) # temporary Y[,1]
Armin Rauschenberger's avatar
Armin Rauschenberger committed
145
  } else {
Armin Rauschenberger's avatar
Armin Rauschenberger committed
146
    nfolds <- length(unique(foldid))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
147 148
  }
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
149 150 151 152 153 154 155 156 157 158
  #--- full fit ---
  nlambda <- numeric()
  base <- lapply(seq_len(q),function(x) list())
  for(i in seq_len(q)){
    cond <- !is.na(Y[,i])
    #if(sum(cond)==0){nlambda[i] <- 0; next}
    base[[i]]$glmnet.fit <- glmnet::glmnet(y=Y[cond,i],x=X[cond,],family=family[i],alpha=alpha.base,...) # ellipsis
    base[[i]]$lambda <- base[[i]]$glmnet.fit$lambda
    nlambda[i] <- length(base[[i]]$glmnet.fit$lambda)
  }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
159
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
160 161 162 163
  #--- predictions ---
  link <- list()
  for(i in seq_len(q)){
    link[[i]] <- matrix(data=NA,nrow=n,ncol=nlambda[i])
Armin Rauschenberger's avatar
Armin Rauschenberger committed
164
  }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
165 166
  
  #--- base cross-validation ---
Armin Rauschenberger's avatar
Armin Rauschenberger committed
167
  for(k in seq_len(nfolds)){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
168 169
    Y0 <- Y[foldid!=k,,drop=FALSE]
    Y1 <- Y[foldid==k,,drop=FALSE]
Armin Rauschenberger's avatar
Armin Rauschenberger committed
170 171
    X0 <- X[foldid!=k,,drop=FALSE]
    X1 <- X[foldid==k,,drop=FALSE]
Armin Rauschenberger's avatar
Armin Rauschenberger committed
172 173 174 175 176 177 178
    for(i in seq_len(q)){
      cond <- !is.na(Y0[,i])
      #if(sum(cond)==0){next}
      object <- glmnet::glmnet(y=Y0[cond,i],x=X0[cond,],family=family[i],alpha=alpha.base,...) # ellipsis
      temp <- stats::predict(object=object,newx=X1,type="link",
                             s=base[[i]]$glmnet.fit$lambda)
      link[[i]][foldid==k,seq_len(ncol(temp))] <- temp
Armin Rauschenberger's avatar
Armin Rauschenberger committed
179
    }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
180 181
  }
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
182 183 184 185 186 187 188
  #--- tune base lambdas ---
  for(i in seq_len(q)){
    fit <- .mean.function(link[[i]],family=family[i])
    cond <- !is.na(Y[,i])
    base[[i]]$cvm <- palasso:::.loss(y=Y[cond,i],fit=fit[cond,],
                                     family=family[i],type.measure=type.measure)[[1]]
    base[[i]]$lambda.min <- base[[i]]$lambda[which.min(base[[i]]$cvm)]
Armin Rauschenberger's avatar
Armin Rauschenberger committed
189
    class(base[[i]]) <- "cv.glmnet" # trial 2020-01-10
Armin Rauschenberger's avatar
Armin Rauschenberger committed
190
  }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
191
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
192 193 194 195 196
  #--- predictions ---
  hat <- matrix(NA,nrow=n,ncol=q)
  for(i in seq_len(q)){
    hat[,i] <- link[[i]][,base[[i]]$lambda==base[[i]]$lambda.min]
  }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
197
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
198 199 200 201 202 203 204 205 206 207 208 209 210
  #--- meta cross-validation ---
  meta <- list()
  for(i in seq_len(q)){
    cond <- !is.na(Y[,i])
    meta[[i]] <- glmnet::cv.glmnet(y=Y[cond,i],x=hat[cond,],
                                   lower.limits=0, # important: 0
                                   upper.limits=Inf, # important: Inf
                                   foldid=foldid[cond],
                                   family=family[i],
                                   type.measure=type.measure,
                                   intercept=TRUE, # with intercept
                                   alpha=alpha.meta,...) # ellipsis
    # consider trying different alpha.meta and selecting best one
Armin Rauschenberger's avatar
Armin Rauschenberger committed
211 212
  }
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
213
  #--- return ---
Armin Rauschenberger's avatar
Armin Rauschenberger committed
214 215 216
  names(base) <- names(meta) <- paste0("y",seq_len(q))
  info <- data.frame(q=q,p=p,family=family,type.measure=type.measure)
  list <- list(base=base,meta=meta,info=info)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
217
  class(list) <- "joinet"
Armin Rauschenberger's avatar
Armin Rauschenberger committed
218
  return(list)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
219 220
}

Armin Rauschenberger's avatar
Armin Rauschenberger committed
221
.mean.function <- function(x,family){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
222
  if(family %in% c("gaussian","cox")){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
223 224 225 226 227 228 229 230 231
    return(x)
  } else if(family=="binomial"){
    return(1/(1+exp(-x)))
  } else if(family=="poisson"){
    return(exp(x))
  } else {
    stop("Family not implemented.",call.=FALSE)
  }
}
Armin Rauschenberger's avatar
Armin Rauschenberger committed
232

Armin Rauschenberger's avatar
Armin Rauschenberger committed
233
.link.function <- function(x,family){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
234
  if(family %in% c("gaussian","cox")){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
235 236
    return(x)
  } else if(family=="binomial"){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
237 238
    if(any(x<0|x>1)){stop("Invalid!",call.=FALSE)}
    return(log(x/(1-x)))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
239
  } else if(family=="poisson"){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
240
    if(any(x<0)){stop("Invalid!",call.=FALSE)}
Armin Rauschenberger's avatar
Armin Rauschenberger committed
241 242 243 244
    return(log(x))
  } else {
    stop("Family not implemented.",call.=FALSE)
  }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
245 246
}

Armin Rauschenberger's avatar
Armin Rauschenberger committed
247
#--- Methods for class "joinet" -----------------------------------------------
Armin Rauschenberger's avatar
Armin Rauschenberger committed
248

Armin Rauschenberger's avatar
Armin Rauschenberger committed
249 250
#' @export
#' @title
Armin Rauschenberger's avatar
Armin Rauschenberger committed
251
#' Make Predictions
Armin Rauschenberger's avatar
Armin Rauschenberger committed
252 253
#'
#' @description
Armin Rauschenberger's avatar
Armin Rauschenberger committed
254
#' Predicts outcome from features with stacked model.
Armin Rauschenberger's avatar
Armin Rauschenberger committed
255
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
256
#' @param object
Armin Rauschenberger's avatar
Armin Rauschenberger committed
257
#' \link[joinet]{joinet} object
Armin Rauschenberger's avatar
Armin Rauschenberger committed
258
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
259 260 261 262
#' @param newx
#' covariates\strong{:}
#' numeric matrix with \eqn{n} rows (samples)
#' and \eqn{p} columns (variables)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
263
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
264 265
#' @param type
#' character "link" or "response"
Armin Rauschenberger's avatar
Armin Rauschenberger committed
266 267
#' 
#' @param ...
Armin Rauschenberger's avatar
Armin Rauschenberger committed
268
#' further arguments (not applicable)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
269
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
270 271 272 273 274
#' @return 
#' This function returns predictions from base and meta learners.
#' The slots \code{base} and \code{meta} each contain a matrix
#' with \eqn{n} rows (samples) and \eqn{q} columns (variables).
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
275
#' @examples
Armin Rauschenberger's avatar
Armin Rauschenberger committed
276
#' n <- 50; p <- 100; q <- 3
Armin Rauschenberger's avatar
Armin Rauschenberger committed
277
#' X <- matrix(rnorm(n*p),nrow=n,ncol=p)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
278
#' Y <- replicate(n=q,expr=rnorm(n=n,mean=rowSums(X[,1:5])))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
279 280
#' Y[,1] <- 1*(Y[,1]>median(Y[,1]))
#' object <- joinet(Y=Y,X=X,family=c("binomial","gaussian","gaussian"))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
281
#' predict(object,newx=X)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
282
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
283
predict.joinet <- function(object,newx,type="response",...){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
284
  if(length(list(...))!=0){warning("Ignoring argument.",call.=FALSE)}
Armin Rauschenberger's avatar
Armin Rauschenberger committed
285
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
286
  x <- object; rm(object)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
287
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
288
  newx <- as.matrix(newx)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
289
  cornet:::.check(x=newx,type="matrix")
Armin Rauschenberger's avatar
Armin Rauschenberger committed
290
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
291 292 293
  q <- length(x$base)
  n <- nrow(newx)
  base <- meta <- matrix(NA,nrow=n,ncol=q)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
294
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
295 296
  # base learners
  for(i in seq_len(q)){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
297 298
    base[,i] <- as.numeric(stats::predict(object=x$base[[i]]$glmnet.fit,newx=newx,s=x$base[[i]]$lambda.min,type="link"))
    #base[,i] <- as.numeric(glmnet:::predict.cv.glmnet(object=x$base[[i]],newx=newx,s="lambda.min",type="link"))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
299 300
    # check whether fine for "binomial" family
  }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
301
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
302 303 304 305 306
  # meta learners
  for(i in seq_len(q)){
    meta[,i] <- as.numeric(stats::predict(object=x$meta[[i]],
                                          newx=base,s="lambda.min",type="link"))
  }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
307
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
308
  list <- list(base=base,meta=meta)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
309
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
310 311 312 313 314 315 316
  if(type=="response"){
    for(i in seq_len(q)){
      base[,i] <- .mean.function(x=base[,i],family=x$info$family[i])
      meta[,i] <- .mean.function(x=meta[,i],family=x$info$family[i])
    }
  } else if(type!="link"){
    stop("Invalid type.",call.=FALSE)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
317 318
  }
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
319 320 321
  list <- list(base=base,meta=meta)
  return(list)
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
322 323
}

Armin Rauschenberger's avatar
Armin Rauschenberger committed
324 325
#' @export
#' @title
Armin Rauschenberger's avatar
Armin Rauschenberger committed
326
#' Extract Coefficients
Armin Rauschenberger's avatar
Armin Rauschenberger committed
327 328
#'
#' @description
Armin Rauschenberger's avatar
Armin Rauschenberger committed
329
#' Extracts pooled coefficients.
Armin Rauschenberger's avatar
Armin Rauschenberger committed
330 331
#' (The meta learners linearly combines
#' the coefficients from the base learners.)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
332
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
333
#' @param object
Armin Rauschenberger's avatar
Armin Rauschenberger committed
334
#' \link[joinet]{joinet} object
Armin Rauschenberger's avatar
Armin Rauschenberger committed
335 336
#' 
#' @param ...
Armin Rauschenberger's avatar
Armin Rauschenberger committed
337
#' further arguments (not applicable)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
338
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
339 340 341 342 343 344 345
#' @return
#' This function returns the pooled coefficients.
#' The slot \code{alpha} contains the intercepts
#' in a vector of length \eqn{q},
#' and the slot \code{beta} contains the slopes
#' in a matrix with \eqn{p} rows (inputs) and \eqn{q} columns.
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
346
#' @examples
Armin Rauschenberger's avatar
Armin Rauschenberger committed
347 348
#' if(!grepl('SunOS',Sys.info()['sysname'])){
#' 1+1
Armin Rauschenberger's avatar
Armin Rauschenberger committed
349
#' n <- 50; p <- 100; q <- 3
Armin Rauschenberger's avatar
Armin Rauschenberger committed
350
#' X <- matrix(rnorm(n*p),nrow=n,ncol=p)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
351
#' Y <- replicate(n=q,expr=rnorm(n=n,mean=rowSums(X[,1:5])))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
352
#' object <- joinet(Y=Y,X=X)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
353
#' coef <- coef(object)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
354
#' }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
355
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
356
coef.joinet <- function(object,...){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
357 358 359 360
  if(length(list(...))!=0){warning("Ignoring argument.",call.=FALSE)}
  
  # base coefficients
  base <- list()
Armin Rauschenberger's avatar
Armin Rauschenberger committed
361
  coef <- sapply(object$base,function(x) stats::coef(object=x$glmnet.fit,s=x$lambda.min))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
362 363 364 365 366 367
  base$alpha <- sapply(coef,function(x) x[1,])
  base$beta <- sapply(coef,function(x) x[-1,])
  names(base$alpha) <- colnames(base$beta) <- names(object$base)
  
  # meta coefficients
  meta <- list()
Armin Rauschenberger's avatar
Armin Rauschenberger committed
368
  weights <- weights.joinet(object)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
  meta$alpha <- weights[1,]
  meta$beta <- weights[-1,]
  
  # pooled coefficients
  pool <- list()
  pool$alpha <- meta$alpha + base$alpha %*% meta$beta
  pool$beta <- base$beta %*% meta$beta
  
  # q <- unique(object$info$q)
  # p <- unique(object$info$p)
  # pool$alpha <- rep(NA,times=q)
  # for(i in seq_len(q)){
  #   pool$alpha[i] <-  meta$alpha[i] + sum(meta$beta[,i] * base$alpha)
  # }
  # pool$beta <- matrix(NA,nrow=p,ncol=q)
  # for(i in seq_len(p)){
  #   for(j in seq_len(q)){
  #     pool$beta[i,j] <-  sum(meta$beta[,j] * base$beta[i,])
  #   }
  # }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
389
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
390
  return(pool)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
391 392
}

Armin Rauschenberger's avatar
Armin Rauschenberger committed
393 394
#' @export
#' @importFrom stats weights
Armin Rauschenberger's avatar
Armin Rauschenberger committed
395
#' @title
Armin Rauschenberger's avatar
Armin Rauschenberger committed
396
#' Extract Weights
Armin Rauschenberger's avatar
Armin Rauschenberger committed
397 398
#'
#' @description
Armin Rauschenberger's avatar
Armin Rauschenberger committed
399 400
#' Extracts coefficients from the meta learner,
#' i.e. the weights for the base learners.
Armin Rauschenberger's avatar
Armin Rauschenberger committed
401
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
402
#' @param object
Armin Rauschenberger's avatar
Armin Rauschenberger committed
403
#' \link[joinet]{joinet} object
Armin Rauschenberger's avatar
Armin Rauschenberger committed
404
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
405 406
#' @param ...
#' further arguments (not applicable)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
407
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
408 409 410 411 412 413 414 415
#' @return
#' This function returns a matrix with
#' \eqn{1+q} rows and \eqn{q} columns.
#' The first row contains the intercepts,
#' and the other rows contain the slopes,
#' which are the effects of the outcomes
#' in the row on the outcomes in the column.
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
416
#' @examples
Armin Rauschenberger's avatar
Armin Rauschenberger committed
417
#' n <- 50; p <- 100; q <- 3
Armin Rauschenberger's avatar
Armin Rauschenberger committed
418
#' X <- matrix(rnorm(n*p),nrow=n,ncol=p)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
419
#' Y <- replicate(n=q,expr=rnorm(n=n,mean=rowSums(X[,1:5])))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
420
#' object <- joinet(Y=Y,X=X)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
421 422
#' weights(object)
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
423
weights.joinet <- function(object,...){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
424 425
  if(length(list(...))!=0){warning("Ignoring argument.",call.=FALSE)}
  x <- object$meta
Armin Rauschenberger's avatar
Armin Rauschenberger committed
426
  coef <- lapply(object$meta,function(x) stats::coef(object=x,s=x$lambda.min))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
427 428 429 430
  coef <- do.call(what="cbind",args=coef)
  coef <- as.matrix(coef)
  colnames(coef) <- names(object$meta)
  return(coef)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
431 432
}

Armin Rauschenberger's avatar
Armin Rauschenberger committed
433 434
print.joinet <- function(x,...){
  cat(paste0("joinet object"),"\n")
Armin Rauschenberger's avatar
Armin Rauschenberger committed
435 436 437 438
}

#--- Manuscript functions ------------------------------------------------------

Armin Rauschenberger's avatar
Armin Rauschenberger committed
439
#' @export
Armin Rauschenberger's avatar
Armin Rauschenberger committed
440
#' @title
Armin Rauschenberger's avatar
Armin Rauschenberger committed
441
#' Model comparison
Armin Rauschenberger's avatar
Armin Rauschenberger committed
442 443
#'
#' @description
Armin Rauschenberger's avatar
Armin Rauschenberger committed
444
#' Compares univariate and multivariate regression.
Armin Rauschenberger's avatar
Armin Rauschenberger committed
445
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
446
#' @inheritParams joinet
Armin Rauschenberger's avatar
Armin Rauschenberger committed
447
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
448 449
#' @param nfolds.ext
#' number of external folds
Armin Rauschenberger's avatar
Armin Rauschenberger committed
450
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
451 452
#' @param nfolds.int
#' number of internal folds
Armin Rauschenberger's avatar
Armin Rauschenberger committed
453
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
454 455 456 457 458
#' @param foldid.ext
#' external fold identifiers\strong{:}
#' vector of length \eqn{n} with entries
#' between \eqn{1} and \code{nfolds.ext};
#' or \code{NULL}
Armin Rauschenberger's avatar
Armin Rauschenberger committed
459
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
460 461 462 463 464
#' @param foldid.int
#' internal fold identifiers\strong{:}
#' vector of length \eqn{n} with entries
#' between \eqn{1} and \code{nfolds.int};
#' or \code{NULL}
Armin Rauschenberger's avatar
Armin Rauschenberger committed
465
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
466
#' @param compare
Armin Rauschenberger's avatar
Armin Rauschenberger committed
467
#' experimental arguments\strong{:}
Armin Rauschenberger's avatar
Armin Rauschenberger committed
468 469 470
#' character vector with entries "mnorm", "spls", "mrce",
#' "sier", "mtps", "rmtl", "gpm" and others
#' (requires packages \code{spls}, \code{MRCE}, \code{SiER}, \code{MTPS}, \code{RMTL} or \code{GPM})
Armin Rauschenberger's avatar
Armin Rauschenberger committed
471 472 473 474
#' 
#' @param mice
#' missing data imputation\strong{:}
#' logical (\code{mice=TRUE} requires package \code{mice})
Armin Rauschenberger's avatar
Armin Rauschenberger committed
475
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
476
#' @param cvpred
Armin Rauschenberger's avatar
Armin Rauschenberger committed
477
#' return cross-validated predictions: logical
Armin Rauschenberger's avatar
Armin Rauschenberger committed
478
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
479 480 481 482
#' @param times
#' measure computation time\strong{:}
#' logical
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
483
#' @param ...
Armin Rauschenberger's avatar
Armin Rauschenberger committed
484 485 486 487 488
#' further arguments passed to \code{\link[glmnet]{glmnet}}
#' and \code{\link[glmnet]{cv.glmnet}}
#' 
#' @return 
#' This function returns a matrix with \eqn{q} columns,
Armin Rauschenberger's avatar
Armin Rauschenberger committed
489 490 491
#' including the cross-validated loss from the univariate models
#' (\code{base}), the multivariate models (\code{meta}),
#' and the intercept-only models (\code{none}).
Armin Rauschenberger's avatar
Armin Rauschenberger committed
492
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
493
#' @examples
Armin Rauschenberger's avatar
Armin Rauschenberger committed
494
#' if(!grepl('SunOS',Sys.info()['sysname'])){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
495
#' n <- 50; p <- 100; q <- 3
Armin Rauschenberger's avatar
Armin Rauschenberger committed
496
#' X <- matrix(rnorm(n*p),nrow=n,ncol=p)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
497 498
#' Y <- replicate(n=q,expr=rnorm(n=n,mean=rowSums(X[,1:5])))
#' cv.joinet(Y=Y,X=X)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
499
#' }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
500 501 502
#' 
#' \dontrun{
#' # correlated features
Armin Rauschenberger's avatar
Armin Rauschenberger committed
503
#' n <- 50; p <- 100; q <- 3
Armin Rauschenberger's avatar
Armin Rauschenberger committed
504 505 506 507
#' mu <- rep(0,times=p)
#' Sigma <- 0.90^abs(col(diag(p))-row(diag(p)))
#' X <- MASS::mvrnorm(n=n,mu=mu,Sigma=Sigma)
#' mu <- rowSums(X[,sample(seq_len(p),size=5)])
Armin Rauschenberger's avatar
Armin Rauschenberger committed
508 509 510
#' Y <- replicate(n=q,expr=rnorm(n=n,mean=mu))
#' #Y <- t(MASS::mvrnorm(n=q,mu=mu,Sigma=diag(n)))
#' cv.joinet(Y=Y,X=X)}
Armin Rauschenberger's avatar
Armin Rauschenberger committed
511 512 513
#' 
#' \dontrun{
#' # other distributions
Armin Rauschenberger's avatar
Armin Rauschenberger committed
514
#' n <- 50; p <- 100; q <- 3
Armin Rauschenberger's avatar
Armin Rauschenberger committed
515
#' X <- matrix(rnorm(n*p),nrow=n,ncol=p)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
516
#' eta <- rowSums(X[,1:5])
Armin Rauschenberger's avatar
Armin Rauschenberger committed
517 518 519
#' Y <- replicate(n=q,expr=rbinom(n=n,size=1,prob=1/(1+exp(-eta))))
#' cv.joinet(Y=Y,X=X,family="binomial")
#' Y <- replicate(n=q,expr=rpois(n=n,lambda=exp(scale(eta))))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
#' cv.joinet(Y=Y,X=X,family="poisson")}
#' 
#' \dontrun{
#' # uncorrelated outcomes
#' n <- 50; p <- 100; q <- 3
#' X <- matrix(rnorm(n*p),nrow=n,ncol=p)
#' y <- rnorm(n=n,mean=rowSums(X[,1:5]))
#' Y <- cbind(y,matrix(rnorm(n*(q-1)),nrow=n,ncol=q-1))
#' cv.joinet(Y=Y,X=X)}
#' 
#' \dontrun{
#' # sparse and dense models
#' n <- 50; p <- 100; q <- 3
#' X <- matrix(rnorm(n*p),nrow=n,ncol=p)
#' Y <- replicate(n=q,expr=rnorm(n=n,mean=rowSums(X[,1:5])))
#' set.seed(1) # fix folds
#' cv.joinet(Y=Y,X=X,alpha.base=1) # lasso
#' set.seed(1)
#' cv.joinet(Y=Y,X=X,alpha.base=0) # ridge}
Armin Rauschenberger's avatar
Armin Rauschenberger committed
539
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
540
cv.joinet <- function(Y,X,family="gaussian",nfolds.ext=5,nfolds.int=10,foldid.ext=NULL,foldid.int=NULL,type.measure="deviance",alpha.base=1,alpha.meta=1,compare=FALSE,mice=FALSE,cvpred=FALSE,times=FALSE,...){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
541
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
542
  if(FALSE){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
543
  fold <- foldid.ext
Armin Rauschenberger's avatar
Armin Rauschenberger committed
544
  family <- "gaussian"; nfolds.ext <- 5; nfolds.int <- 10; foldid.ext <- foldid.int <- NULL; type.measure <- "deviance"; alpha.base <- alpha.meta <- 1; mice <- cvpred <- times <- FALSE
Armin Rauschenberger's avatar
Armin Rauschenberger committed
545 546
  foldid.ext <- fold; nfolds.ext <- 1
  #nfolds.ext <- 1; nfolds.int <- 10; foldid.int <- NULL; compare <- TRUE
Armin Rauschenberger's avatar
Armin Rauschenberger committed
547 548
  }
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
549
  if(length(compare)==1 && compare==TRUE){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
550 551 552 553 554 555 556
    if(all(family=="gaussian")){
      compare <- c("mnorm","mars","spls","mrce","map","mrf","sier","mcen","gpm","rmtl","mtps")
    } else if(all(family=="binomial")){
      compare <- c("mars","mcen","rmtl","mtps")
    } else {
      stop("Comparison not implemented for mixed families.",call.=FALSE)
    }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
557
  }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
558
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
559 560 561
  n <- nrow(Y)
  q <- ncol(Y)
  p <- ncol(X)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
562
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
563 564 565 566
  #--- fold identifiers ---
  if(is.null(foldid.ext)){
    foldid.ext <- palasso:::.folds(y=Y[,1],nfolds=nfolds.ext) # temporary Y[,1]
  } else {
Armin Rauschenberger's avatar
Armin Rauschenberger committed
567 568
    #nfolds.ext <- length(unique(foldid.ext))
    nfolds.ext <- max(foldid.ext)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
569 570
  }
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
571 572 573 574 575
  #--- family ---
  if(length(family)==1){
    family <- rep(family,times=q)
  } else if(length(family)!=q){
    stop("Invalid argument family",call.=FALSE)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
576 577
  }
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
578 579
  # check packages
  pkgs <- .packages(all.available=TRUE)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
580
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
581
  if(is.character(compare)){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
582 583
    for(i in seq_along(compare)){
      pkg <- switch(compare[i],mnorm="glmnet",mars="earth",spls="spls",
Armin Rauschenberger's avatar
Armin Rauschenberger committed
584 585 586
                  mrce="MRCE",map="remMap",mrf="MultivariateRandomForest",
                  sier="SiER",mcen="mcen",gpm="GPM",rmtl="RMTL",mtps="MTPS",
                  stop("Invalid method.",call.=FALSE))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
587 588 589
      if(!pkg %in% pkgs){
        stop("Method \"",compare[i],"\" requires package \"",pkg,"\".",call.=FALSE)
      }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
590
    }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
591
  }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
592 593 594 595 596 597 598 599

  #--- checks ---
  #if(any( & any(family!="gaussian")){
  #  stop("\"mnorm\", \"spls\", \"mrce\" and \"sier\" require family \"gaussian\".",call.=FALSE)
  #}
  #if(any(mtps,rmtl) & any(!family %in% c("gaussian","binomial"))){
  #  stop("\"mtps\" and \"rmtl\" require family \"gaussian\" or \"binomial\".",call.=FALSE)
  #}
Armin Rauschenberger's avatar
Armin Rauschenberger committed
600
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
601
  #--- cross-validated predictions ---
Armin Rauschenberger's avatar
Armin Rauschenberger committed
602
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
603
  models <- c("base","meta",compare,"none")
Armin Rauschenberger's avatar
Armin Rauschenberger committed
604
  pred <- lapply(X=models,function(x) matrix(data=NA,nrow=n,ncol=q))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
605 606
  time <- lapply(X=models,function(x) NA)
  names(pred) <- names(time) <- models
Armin Rauschenberger's avatar
Armin Rauschenberger committed
607
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
608 609 610
  for(i in seq_len(nfolds.ext)){
    
    Y0 <- Y[foldid.ext!=i,,drop=FALSE]
Armin Rauschenberger's avatar
Armin Rauschenberger committed
611
    #Y1 <- Y[foldid.ext==i,,drop=FALSE]
Armin Rauschenberger's avatar
Armin Rauschenberger committed
612 613
    X0 <- X[foldid.ext!=i,,drop=FALSE]
    X1 <- X[foldid.ext==i,,drop=FALSE]
Armin Rauschenberger's avatar
Armin Rauschenberger committed
614
    
Armin Rauschenberger's avatar
Armin Rauschenberger committed
615 616 617 618 619 620 621
    # standardise features (trial)
    #mu <- apply(X=X0,MARGIN=2,FUN=function(x) mean(x))
    #sd <- apply(X=X0,MARGIN=2,FUN=function(x) stats::sd(x))
    #X0 <- t((t(X0)-mu)/sd)[,sd!=0]
    #X1 <- t((t(X1)-mu)/sd)[,sd!=0]
    # or standardise once before cv?
    
Armin Rauschenberger's avatar
Armin Rauschenberger committed
622 623 624 625
    # remove constant features
    cond <- apply(X=X0,MARGIN=2,FUN=function(x) stats::sd(x)!=0)
    X0 <- X0[,cond]; X1 <- X1[,cond]
    
Armin Rauschenberger's avatar
Armin Rauschenberger committed
626 627 628 629 630 631 632
    if(is.null(foldid.int)){
      foldid <- palasso:::.folds(y=Y0[,1],nfolds=nfolds.int) # temporary Y0[,1]
    } else {
      foldid <- foldid.int[foldid.ext!=i]
    }
    
    # base and meta learners
Armin Rauschenberger's avatar
Armin Rauschenberger committed
633
    start <- Sys.time()
Armin Rauschenberger's avatar
Armin Rauschenberger committed
634
    fit <- joinet(Y=Y0,X=X0,family=family,type.measure=type.measure,alpha.base=alpha.base,alpha.meta=alpha.meta,foldid=foldid) # add ellipsis (...)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
635
    # also do not standardise!
Armin Rauschenberger's avatar
Armin Rauschenberger committed
636
    temp <- predict.joinet(fit,newx=X1)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
637 638
    pred$base[foldid.ext==i,] <- temp$base
    pred$meta[foldid.ext==i,] <- temp$meta
Armin Rauschenberger's avatar
Armin Rauschenberger committed
639 640
    end <- Sys.time()
    time$meta <- as.numeric(difftime(end,start,units="secs"))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
641
    
Armin Rauschenberger's avatar
Armin Rauschenberger committed
642
    # missing values
Armin Rauschenberger's avatar
Armin Rauschenberger committed
643 644 645 646
    if(mice & any(is.na(Y0))){
      if(requireNamespace("mice",quietly=TRUE)){
        y0 <- as.matrix(mice::complete(data=mice::mice(Y0,m=1,method="pmm",seed=1,printFlag=FALSE),action="all")[[1]])
      } else {
Armin Rauschenberger's avatar
Armin Rauschenberger committed
647
        stop("Imputation by PMM requires install.packages(\"mice\").",call.=FALSE)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
648 649 650 651
      }
    } else {
      y0 <- apply(X=Y0,MARGIN=2,FUN=function(x) ifelse(is.na(x),stats::median(x[!is.na(x)]),x))
    }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
652
    all(Y0==y0,na.rm=TRUE)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
653
    
Armin Rauschenberger's avatar
Armin Rauschenberger committed
654
    # other learners
Armin Rauschenberger's avatar
Armin Rauschenberger committed
655 656
    
    if("mnorm" %in% compare){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
657 658 659 660 661
      cat("mnorm"," ")
      start <- Sys.time()
      if(any(family!="gaussian")){
        stop("mnorm requires \"gaussian\" family.",call.=FALSE)
      }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
662
      net <- glmnet::cv.glmnet(x=X0,y=y0,family="mgaussian",foldid=foldid,alpha=alpha.base) # add ellipsis (...)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
663
      pred$mnorm[foldid.ext==i,] <- stats::predict(object=net,newx=X1,s="lambda.min",type="response")
Armin Rauschenberger's avatar
Armin Rauschenberger committed
664 665 666 667
      end <- Sys.time()
      time$mnorm <- as.numeric(difftime(end,start,units="secs"))
    } else {
      net <- glmnet::glmnet(x=X0,y=y0,family="mgaussian")
Armin Rauschenberger's avatar
Armin Rauschenberger committed
668
    }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
669 670
    
    if("mars" %in% compare){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
671 672
      cat("mars"," ")
      start <- Sys.time()
Armin Rauschenberger's avatar
Armin Rauschenberger committed
673
      if(all(family=="gaussian")){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
674
        object <- earth::earth(x=X0,y=y0)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
675
        # equivalent: object <- mda::mars(x=X0,y=y0)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
676
      } else if(all(family=="binomial")){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
677
        object <- earth::earth(x=X0,y=y0,glm=list(family=stats::binomial))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
678
      } else {
Armin Rauschenberger's avatar
Armin Rauschenberger committed
679
        stop("MARS requires either \"gaussian\" or \"binomial\" family.",call.=FALSE)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
680
      }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
681
      # pmethod="cv" not available for multivariate outputs
Armin Rauschenberger's avatar
Armin Rauschenberger committed
682
      
Armin Rauschenberger's avatar
Armin Rauschenberger committed
683 684 685 686 687 688 689 690 691
      ### start trial ###
      if(FALSE){
      #nk <- min(200, max(20, 2 * ncol(X0))) + 1
      #nprune <- round(seq(from=2,to=nk,length.out=10))
      #object <- list()
      #for(j in seq_along(nprune)){
      #  object[[j]] <- earth::earth(x=X0,y=y0,nprune=nprune[j],pmethod="cv",nfold=nfolds.int)
      #}
      #sapply(object,function(x) x$gcv)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
692 693 694
      ## i.e. run earth/mars with tryCatch for each nprune
      ## and select run with best cvm (here gcv)
      # tune nprune (use default nk)!
Armin Rauschenberger's avatar
Armin Rauschenberger committed
695
      }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
696
      
Armin Rauschenberger's avatar
Armin Rauschenberger committed
697 698
      #pred$mars[foldid.ext==i,] <- earth:::predict.earth(object=object,newdata=X1,type="response") # original
      pred$mars[foldid.ext==i,] <- stats::predict(object=object,newdata=X1,type="response") # trial
Armin Rauschenberger's avatar
Armin Rauschenberger committed
699 700
      end <- Sys.time()
      time$mars <- as.numeric(difftime(end,start,units="secs"))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
701
    }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
702 703
    
    if("spls" %in% compare){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
704 705 706 707 708 709
      cat("spls"," ")
      start <- Sys.time()
      if(any(family!="gaussian")){
        stop("spls requires \"gaussian\" family.")
      }
      invisible(utils::capture.output(cv.spls <- spls::cv.spls(x=X0,y=y0,fold=nfolds.int,K=seq_len(min(ncol(X0),10)),
Armin Rauschenberger's avatar
Armin Rauschenberger committed
710
                               eta=seq(from=0.0,to=0.9,by=0.1),plot.it=FALSE))) #scale.x=FALSE
Armin Rauschenberger's avatar
Armin Rauschenberger committed
711
      object <- spls::spls(x=X0,y=y0,K=cv.spls$K.opt,eta=cv.spls$eta.opt) #scale.x=FALSE
Armin Rauschenberger's avatar
Armin Rauschenberger committed
712
      pred$spls[foldid.ext==i,] <- spls::predict.spls(object=object,newx=X1,type="fit")
Armin Rauschenberger's avatar
Armin Rauschenberger committed
713 714
      end <- Sys.time()
      time$spls <- as.numeric(difftime(end,start,units="secs"))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
715
    }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
716
    
Armin Rauschenberger's avatar
Armin Rauschenberger committed
717 718
    if("mrce" %in% compare){
      cat("mrce"," ")
Armin Rauschenberger's avatar
Armin Rauschenberger committed
719
      start <- Sys.time()
Armin Rauschenberger's avatar
Armin Rauschenberger committed
720 721
      if(any(family!="gaussian")){
        stop("MRCE requires \"gaussian\" family.",call.=FALSE)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
722
      }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
723
      lam1 <- lam2 <- 10^seq(from=1,to=-4,length.out=11)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
724
      invisible(utils::capture.output(trials <- lapply(lam2,function(x) tryCatch(expr=MRCE::mrce(X=X0,Y=y0,lam1.vec=lam1,lam2.vec=x,method="cv",kfold=nfolds.int),error=function(x) NULL))))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
725 726 727
      cv.err <- sapply(trials,function(x) ifelse(is.null(x),Inf,min(x$cv.err)))
      object <- trials[[which.min(cv.err)]]
      pred$mrce[foldid.ext==i,] <- matrix(object$muhat,nrow=nrow(X1),ncol=q,byrow=TRUE) + X1 %*% object$Bhat
Armin Rauschenberger's avatar
Armin Rauschenberger committed
728
      end <- Sys.time()
Armin Rauschenberger's avatar
Armin Rauschenberger committed
729
      time$mrce <- as.numeric(difftime(end,start,units="secs"))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
730
    }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
731
    
Armin Rauschenberger's avatar
Armin Rauschenberger committed
732 733
    if("map" %in% compare){
      cat("map"," ")
Armin Rauschenberger's avatar
Armin Rauschenberger committed
734
      start <- Sys.time()
Armin Rauschenberger's avatar
Armin Rauschenberger committed
735 736
      if(any(family!="gaussian")){
        stop("map requires \"gaussian\" family.")
Armin Rauschenberger's avatar
Armin Rauschenberger committed
737
      }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
738 739
      mean <- colMeans(y0)
      y0s <- y0-matrix(data=mean,nrow=nrow(X0),ncol=ncol(y0),byrow=TRUE)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
740
      lamL1.v <- lamL2.v <- exp(seq(from=0,to=5,length.out=11))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
741
      cv <- remMap::remMap.CV(X=X0,Y=y0s,lamL1.v=lamL1.v,lamL2.v=lamL2.v,fold=nfolds.int)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
742
      #graphics::plot(x=lamL1.v,y=log(as.numeric(cv$ols.cv[,3])))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
743 744 745 746 747 748 749 750
      pick <- which.min(as.vector(cv$ols.cv))
      lamL1 <- cv$l.index[1,pick]
      lamL2 <- cv$l.index[2,pick]
      # index <- which(cv$ols.cv==min(cv$ols.cv),arr.ind=TRUE)[1,]
      # rev(lamL1.v)[index[1]]
      # rev(lamL2.v)[index[2]]
      ##cat("lam1:",lamL1,", lam2:",lamL2)
      object <- remMap::remMap(X.m=X0,Y.m=y0s,lamL1=lamL1,lamL2=lamL2)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
751
      pred$map[foldid.ext==i,] <- matrix(data=mean,nrow=nrow(X1),ncol=ncol(y0),byrow=TRUE) + X1 %*% object$phi
Armin Rauschenberger's avatar
Armin Rauschenberger committed
752
      end <- Sys.time()
Armin Rauschenberger's avatar
Armin Rauschenberger committed
753
      time$map <- as.numeric(difftime(end,start,units="secs"))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
754
    }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
755 756
    
    if("mrf" %in% compare){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
757 758 759 760 761 762
      cat("mrf"," ")
      start <- Sys.time()
      if(any(family!="gaussian")){
        stop("mrf requires \"gaussian\" family.")
      }
      pred$mrf[foldid.ext==i,] <- MultivariateRandomForest::build_forest_predict(trainX=X0,trainY=y0,
Armin Rauschenberger's avatar
Armin Rauschenberger committed
763
                                   n_tree=100,m_feature=min(ncol(X0)-1,5),min_leaf=min(nrow(X0),5),testX=X1)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
764
      # use n_tree=500, m_feature=floor(ncol(X0)/3)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
765
      # alternative: IntegratedMRF
Armin Rauschenberger's avatar
Armin Rauschenberger committed
766 767 768
      # Check why this does not work well!
      end <- Sys.time()
      time$mrf <- as.numeric(difftime(end,start,units="secs"))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
769 770
    }
    
Armin Rauschenberger's avatar
Armin Rauschenberger committed
771 772 773 774 775 776
    if("sier" %in% compare){
      cat("sier"," ")
      start <- Sys.time()
      if(any(family!="gaussian")){
        stop("SiER requires \"gaussian\" family.",call.=FALSE)
      }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
777
      invisible(utils::capture.output(object <- SiER::cv.SiER(X=X0,Y=y0,K.cv=3)))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
778 779 780 781 782 783 784
      # trial with K.cv=3 (for spped-up)
      # use upper.comp=10 and thres=0.01  (changed for speed-up)
      pred$sier[foldid.ext==i,] <- SiER::pred.SiER(cv.fit=object,X.new=X1)
      end <- Sys.time()
      time$sier <- as.numeric(difftime(end,start,units="secs"))
    }
    
Armin Rauschenberger's avatar
Armin Rauschenberger committed
785
    if("mcen" %in% compare){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
786 787 788 789 790 791 792 793 794 795
      cat("mcen"," ")
      start <- Sys.time()
      if(all(family=="gaussian")){
        type <- "mgaussian"
      } else if(all(family=="binomial")){
        type <- "mbinomial"
      } else {
        stop("mcen requires either \"gaussian\" or \"binomial\".",call.=FALSE)
      }
      object <- mcen::cv.mcen(x=X0,y=y0,family=type,folds=foldid,ky=1,
Armin Rauschenberger's avatar
Armin Rauschenberger committed
796 797
                              gamma_y=seq(from=0.1,to=5.1,by=1),ndelta=5)
      # TEMPORARY gamma_y=seq(from=0.1,to=5.1,length.out=3) and ndelta=3 (for speed-up)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
798 799
      #temp <- mcen:::predict.cv.mcen(object=object,newx=X1) # original
      temp <- stats::predict(object=object,newx=X1) # trial
Armin Rauschenberger's avatar
Armin Rauschenberger committed
800
      pred$mcen[foldid.ext==i,] <- as.matrix(temp)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
801 802 803
      # single cluster (ky=1) due to setting and error
      end <- Sys.time()
      time$mcen <- as.numeric(difftime(end,start,units="secs"))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
804 805
    }