functions.R 39.7 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
#' n <- 50; p <- 100; q <- 3
Armin Rauschenberger's avatar
Armin Rauschenberger committed
85
#' X <- matrix(rnorm(n*p),nrow=n,ncol=p)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
86
#' Y <- replicate(n=q,expr=rnorm(n=n,mean=rowSums(X[,1:5])))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
87
#' object <- joinet(Y=Y,X=X)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
88
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
89 90 91
#' \dontrun{
#' browseVignettes("joinet") # further examples}
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
92
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
93
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
94
  #--- temporary ---
Armin Rauschenberger's avatar
Armin Rauschenberger committed
95
  # family <- "gaussian"; nfolds <- 10; foldid <- NULL; type.measure <- "deviance"
Armin Rauschenberger's avatar
Armin Rauschenberger committed
96
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
97
  #--- checks ---
Armin Rauschenberger's avatar
Armin Rauschenberger committed
98 99 100
  Y <- as.matrix(Y)
  X <- as.matrix(X)
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
101
  cornet:::.check(x=Y,type="matrix",miss=TRUE)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
102 103 104 105 106 107 108 109 110 111 112 113 114
  
  ### 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
115
  cornet:::.check(x=X,type="matrix")
Armin Rauschenberger's avatar
Armin Rauschenberger committed
116
  #cornet:::.check(x=family,type="vector",values=c("gaussian","binomial","poisson"))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
117 118 119 120 121 122 123 124
  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
125 126
  }
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
127 128 129 130 131 132 133 134 135 136
  #--- 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
137
  }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
138
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
139 140 141 142
  #--- 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
143
  } else {
Armin Rauschenberger's avatar
Armin Rauschenberger committed
144
    nfolds <- length(unique(foldid))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
145 146
  }
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
147 148 149 150 151 152 153 154 155 156
  #--- 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
157
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
158 159 160 161
  #--- 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
162
  }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
163 164
  
  #--- base cross-validation ---
Armin Rauschenberger's avatar
Armin Rauschenberger committed
165
  for(k in seq_len(nfolds)){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
166 167
    Y0 <- Y[foldid!=k,,drop=FALSE]
    Y1 <- Y[foldid==k,,drop=FALSE]
Armin Rauschenberger's avatar
Armin Rauschenberger committed
168 169
    X0 <- X[foldid!=k,,drop=FALSE]
    X1 <- X[foldid==k,,drop=FALSE]
Armin Rauschenberger's avatar
Armin Rauschenberger committed
170 171 172 173 174 175 176
    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
177
    }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
178 179
  }
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
180 181 182 183 184 185 186
  #--- 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
187
    class(base[[i]]) <- "cv.glmnet" # trial 2020-01-10
Armin Rauschenberger's avatar
Armin Rauschenberger committed
188
  }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
189
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
190 191 192 193 194
  #--- 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
195
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
196 197 198 199 200 201 202 203 204 205 206 207 208
  #--- 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
209 210
  }
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
211
  #--- return ---
Armin Rauschenberger's avatar
Armin Rauschenberger committed
212 213 214
  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
215
  class(list) <- "joinet"
Armin Rauschenberger's avatar
Armin Rauschenberger committed
216
  return(list)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
217 218
}

Armin Rauschenberger's avatar
Armin Rauschenberger committed
219
.mean.function <- function(x,family){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
220
  if(family %in% c("gaussian","cox")){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
221 222 223 224 225 226 227 228 229
    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
230

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

Armin Rauschenberger's avatar
Armin Rauschenberger committed
245
#--- Methods for class "joinet" -----------------------------------------------
Armin Rauschenberger's avatar
Armin Rauschenberger committed
246

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

Armin Rauschenberger's avatar
Armin Rauschenberger committed
322 323
#' @export
#' @title
Armin Rauschenberger's avatar
Armin Rauschenberger committed
324
#' Extract Coefficients
Armin Rauschenberger's avatar
Armin Rauschenberger committed
325 326
#'
#' @description
Armin Rauschenberger's avatar
Armin Rauschenberger committed
327
#' Extracts pooled coefficients.
Armin Rauschenberger's avatar
Armin Rauschenberger committed
328 329
#' (The meta learners linearly combines
#' the coefficients from the base learners.)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
330
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
331
#' @param object
Armin Rauschenberger's avatar
Armin Rauschenberger committed
332
#' \link[joinet]{joinet} object
Armin Rauschenberger's avatar
Armin Rauschenberger committed
333 334
#' 
#' @param ...
Armin Rauschenberger's avatar
Armin Rauschenberger committed
335
#' further arguments (not applicable)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
336
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
337 338 339 340 341 342 343
#' @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
344
#' @examples
Armin Rauschenberger's avatar
Armin Rauschenberger committed
345
#' n <- 50; p <- 100; q <- 3
Armin Rauschenberger's avatar
Armin Rauschenberger committed
346
#' X <- matrix(rnorm(n*p),nrow=n,ncol=p)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
347
#' Y <- replicate(n=q,expr=rnorm(n=n,mean=rowSums(X[,1:5])))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
348
#' object <- joinet(Y=Y,X=X)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
349 350
#' coef <- coef(object)
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
351
coef.joinet <- function(object,...){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
352 353 354 355
  if(length(list(...))!=0){warning("Ignoring argument.",call.=FALSE)}
  
  # base coefficients
  base <- list()
Armin Rauschenberger's avatar
Armin Rauschenberger committed
356
  coef <- sapply(object$base,function(x) stats::coef(object=x$glmnet.fit,s=x$lambda.min))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
357 358 359 360 361 362
  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
363
  weights <- weights.joinet(object)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
  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
384
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
385
  return(pool)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
386 387
}

Armin Rauschenberger's avatar
Armin Rauschenberger committed
388 389
#' @export
#' @importFrom stats weights
Armin Rauschenberger's avatar
Armin Rauschenberger committed
390
#' @title
Armin Rauschenberger's avatar
Armin Rauschenberger committed
391
#' Extract Weights
Armin Rauschenberger's avatar
Armin Rauschenberger committed
392 393
#'
#' @description
Armin Rauschenberger's avatar
Armin Rauschenberger committed
394 395
#' Extracts coefficients from the meta learner,
#' i.e. the weights for the base learners.
Armin Rauschenberger's avatar
Armin Rauschenberger committed
396
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
397
#' @param object
Armin Rauschenberger's avatar
Armin Rauschenberger committed
398
#' \link[joinet]{joinet} object
Armin Rauschenberger's avatar
Armin Rauschenberger committed
399
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
400 401
#' @param ...
#' further arguments (not applicable)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
402
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
403 404 405 406 407 408 409 410
#' @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
411
#' @examples
Armin Rauschenberger's avatar
Armin Rauschenberger committed
412
#' n <- 50; p <- 100; q <- 3
Armin Rauschenberger's avatar
Armin Rauschenberger committed
413
#' X <- matrix(rnorm(n*p),nrow=n,ncol=p)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
414
#' Y <- replicate(n=q,expr=rnorm(n=n,mean=rowSums(X[,1:5])))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
415
#' object <- joinet(Y=Y,X=X)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
416 417
#' weights(object)
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
418
weights.joinet <- function(object,...){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
419 420
  if(length(list(...))!=0){warning("Ignoring argument.",call.=FALSE)}
  x <- object$meta
Armin Rauschenberger's avatar
Armin Rauschenberger committed
421
  coef <- lapply(object$meta,function(x) stats::coef(object=x,s=x$lambda.min))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
422 423 424 425
  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
426 427
}

Armin Rauschenberger's avatar
Armin Rauschenberger committed
428 429
print.joinet <- function(x,...){
  cat(paste0("joinet object"),"\n")
Armin Rauschenberger's avatar
Armin Rauschenberger committed
430 431 432 433
}

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

Armin Rauschenberger's avatar
Armin Rauschenberger committed
434
#' @export
Armin Rauschenberger's avatar
Armin Rauschenberger committed
435
#' @title
Armin Rauschenberger's avatar
Armin Rauschenberger committed
436
#' Model comparison
Armin Rauschenberger's avatar
Armin Rauschenberger committed
437 438
#'
#' @description
Armin Rauschenberger's avatar
Armin Rauschenberger committed
439
#' Compares univariate and multivariate regression.
Armin Rauschenberger's avatar
Armin Rauschenberger committed
440
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
441
#' @inheritParams joinet
Armin Rauschenberger's avatar
Armin Rauschenberger committed
442
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
443 444
#' @param nfolds.ext
#' number of external folds
Armin Rauschenberger's avatar
Armin Rauschenberger committed
445
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
446 447
#' @param nfolds.int
#' number of internal folds
Armin Rauschenberger's avatar
Armin Rauschenberger committed
448
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
449 450 451 452 453
#' @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
454
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
455 456 457 458 459
#' @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
460
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
461
#' @param compare
Armin Rauschenberger's avatar
Armin Rauschenberger committed
462
#' experimental arguments\strong{:}
Armin Rauschenberger's avatar
Armin Rauschenberger committed
463 464 465
#' 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
466 467 468 469
#' 
#' @param mice
#' missing data imputation\strong{:}
#' logical (\code{mice=TRUE} requires package \code{mice})
Armin Rauschenberger's avatar
Armin Rauschenberger committed
470
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
471
#' @param cvpred
Armin Rauschenberger's avatar
Armin Rauschenberger committed
472
#' return cross-validated predictions: logical
Armin Rauschenberger's avatar
Armin Rauschenberger committed
473
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
474 475 476 477
#' @param times
#' measure computation time\strong{:}
#' logical
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
478
#' @param ...
Armin Rauschenberger's avatar
Armin Rauschenberger committed
479 480 481 482 483
#' 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
484 485 486
#' 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
487
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
488
#' @examples
Armin Rauschenberger's avatar
Armin Rauschenberger committed
489
#' n <- 50; p <- 100; q <- 3
Armin Rauschenberger's avatar
Armin Rauschenberger committed
490
#' X <- matrix(rnorm(n*p),nrow=n,ncol=p)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
491 492 493 494 495
#' Y <- replicate(n=q,expr=rnorm(n=n,mean=rowSums(X[,1:5])))
#' cv.joinet(Y=Y,X=X)
#' 
#' \dontrun{
#' # correlated features
Armin Rauschenberger's avatar
Armin Rauschenberger committed
496
#' n <- 50; p <- 100; q <- 3
Armin Rauschenberger's avatar
Armin Rauschenberger committed
497 498 499 500
#' 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
501 502 503
#' 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
504 505 506
#' 
#' \dontrun{
#' # other distributions
Armin Rauschenberger's avatar
Armin Rauschenberger committed
507
#' n <- 50; p <- 100; q <- 3
Armin Rauschenberger's avatar
Armin Rauschenberger committed
508
#' X <- matrix(rnorm(n*p),nrow=n,ncol=p)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
509
#' eta <- rowSums(X[,1:5])
Armin Rauschenberger's avatar
Armin Rauschenberger committed
510 511 512
#' 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
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
#' 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
532
#' 
Armin Rauschenberger's avatar
Armin Rauschenberger committed
533
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
534
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
535
  if(FALSE){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
536
  fold <- foldid.ext
Armin Rauschenberger's avatar
Armin Rauschenberger committed
537
  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
538 539
  foldid.ext <- fold; nfolds.ext <- 1
  #nfolds.ext <- 1; nfolds.int <- 10; foldid.int <- NULL; compare <- TRUE
Armin Rauschenberger's avatar
Armin Rauschenberger committed
540 541
  }
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
542
  if(length(compare)==1 && compare==TRUE){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
543 544 545 546 547 548 549
    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
550
  }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
551
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
552 553 554
  n <- nrow(Y)
  q <- ncol(Y)
  p <- ncol(X)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
555
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
556 557 558 559
  #--- 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
560 561
    #nfolds.ext <- length(unique(foldid.ext))
    nfolds.ext <- max(foldid.ext)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
562 563
  }
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
564 565 566 567 568
  #--- 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
569 570
  }
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
571 572
  # check packages
  pkgs <- .packages(all.available=TRUE)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
573
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
574
  if(is.character(compare)){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
575 576
    for(i in seq_along(compare)){
      pkg <- switch(compare[i],mnorm="glmnet",mars="earth",spls="spls",
Armin Rauschenberger's avatar
Armin Rauschenberger committed
577 578 579
                  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
580 581 582
      if(!pkg %in% pkgs){
        stop("Method \"",compare[i],"\" requires package \"",pkg,"\".",call.=FALSE)
      }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
583
    }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
584
  }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
585 586 587 588 589 590 591 592

  #--- 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
593
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
594
  #--- cross-validated predictions ---
Armin Rauschenberger's avatar
Armin Rauschenberger committed
595
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
596
  models <- c("base","meta",compare,"none")
Armin Rauschenberger's avatar
Armin Rauschenberger committed
597
  pred <- lapply(X=models,function(x) matrix(data=NA,nrow=n,ncol=q))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
598 599
  time <- lapply(X=models,function(x) NA)
  names(pred) <- names(time) <- models
Armin Rauschenberger's avatar
Armin Rauschenberger committed
600
  
Armin Rauschenberger's avatar
Armin Rauschenberger committed
601 602 603
  for(i in seq_len(nfolds.ext)){
    
    Y0 <- Y[foldid.ext!=i,,drop=FALSE]
Armin Rauschenberger's avatar
Armin Rauschenberger committed
604
    #Y1 <- Y[foldid.ext==i,,drop=FALSE]
Armin Rauschenberger's avatar
Armin Rauschenberger committed
605 606
    X0 <- X[foldid.ext!=i,,drop=FALSE]
    X1 <- X[foldid.ext==i,,drop=FALSE]
Armin Rauschenberger's avatar
Armin Rauschenberger committed
607
    
Armin Rauschenberger's avatar
Armin Rauschenberger committed
608 609 610 611 612 613 614
    # 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
615 616 617 618
    # 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
619 620 621 622 623 624 625
    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
626
    start <- Sys.time()
Armin Rauschenberger's avatar
Armin Rauschenberger committed
627
    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
628
    # also do not standardise!
Armin Rauschenberger's avatar
Armin Rauschenberger committed
629
    temp <- predict.joinet(fit,newx=X1)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
630 631
    pred$base[foldid.ext==i,] <- temp$base
    pred$meta[foldid.ext==i,] <- temp$meta
Armin Rauschenberger's avatar
Armin Rauschenberger committed
632 633
    end <- Sys.time()
    time$meta <- as.numeric(difftime(end,start,units="secs"))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
634
    
Armin Rauschenberger's avatar
Armin Rauschenberger committed
635
    # missing values
Armin Rauschenberger's avatar
Armin Rauschenberger committed
636 637 638 639
    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
640
        stop("Imputation by PMM requires install.packages(\"mice\").",call.=FALSE)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
641 642 643 644
      }
    } 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
645
    all(Y0==y0,na.rm=TRUE)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
646
    
Armin Rauschenberger's avatar
Armin Rauschenberger committed
647
    # other learners
Armin Rauschenberger's avatar
Armin Rauschenberger committed
648 649
    
    if("mnorm" %in% compare){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
650 651 652 653 654
      cat("mnorm"," ")
      start <- Sys.time()
      if(any(family!="gaussian")){
        stop("mnorm requires \"gaussian\" family.",call.=FALSE)
      }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
655
      net <- glmnet::cv.glmnet(x=X0,y=y0,family="mgaussian",foldid=foldid,alpha=alpha.base) # add ellipsis (...)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
656
      pred$mnorm[foldid.ext==i,] <- stats::predict(object=net,newx=X1,s="lambda.min",type="response")
Armin Rauschenberger's avatar
Armin Rauschenberger committed
657 658 659 660
      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
661
    }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
662 663
    
    if("mars" %in% compare){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
664 665
      cat("mars"," ")
      start <- Sys.time()
Armin Rauschenberger's avatar
Armin Rauschenberger committed
666
      if(all(family=="gaussian")){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
667
        object <- earth::earth(x=X0,y=y0)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
668
        # equivalent: object <- mda::mars(x=X0,y=y0)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
669
      } else if(all(family=="binomial")){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
670
        object <- earth::earth(x=X0,y=y0,glm=list(family=stats::binomial))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
671
      } else {
Armin Rauschenberger's avatar
Armin Rauschenberger committed
672
        stop("MARS requires either \"gaussian\" or \"binomial\" family.",call.=FALSE)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
673
      }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
674
      # pmethod="cv" not available for multivariate outputs
Armin Rauschenberger's avatar
Armin Rauschenberger committed
675
      
Armin Rauschenberger's avatar
Armin Rauschenberger committed
676 677 678 679 680 681 682 683 684
      ### 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
685 686 687
      ## 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
688
      }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
689
      
Armin Rauschenberger's avatar
Armin Rauschenberger committed
690 691
      #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
692 693
      end <- Sys.time()
      time$mars <- as.numeric(difftime(end,start,units="secs"))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
694
    }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
695 696
    
    if("spls" %in% compare){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
697 698 699 700 701 702
      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
703
                               eta=seq(from=0.0,to=0.9,by=0.1),plot.it=FALSE))) #scale.x=FALSE
Armin Rauschenberger's avatar
Armin Rauschenberger committed
704
      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
705
      pred$spls[foldid.ext==i,] <- spls::predict.spls(object=object,newx=X1,type="fit")
Armin Rauschenberger's avatar
Armin Rauschenberger committed
706 707
      end <- Sys.time()
      time$spls <- as.numeric(difftime(end,start,units="secs"))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
708
    }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
709
    
Armin Rauschenberger's avatar
Armin Rauschenberger committed
710 711
    if("mrce" %in% compare){
      cat("mrce"," ")
Armin Rauschenberger's avatar
Armin Rauschenberger committed
712
      start <- Sys.time()
Armin Rauschenberger's avatar
Armin Rauschenberger committed
713 714
      if(any(family!="gaussian")){
        stop("MRCE requires \"gaussian\" family.",call.=FALSE)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
715
      }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
716
      lam1 <- lam2 <- 10^seq(from=1,to=-4,length.out=11)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
717
      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
718 719 720
      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
721
      end <- Sys.time()
Armin Rauschenberger's avatar
Armin Rauschenberger committed
722
      time$mrce <- as.numeric(difftime(end,start,units="secs"))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
723
    }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
724
    
Armin Rauschenberger's avatar
Armin Rauschenberger committed
725 726
    if("map" %in% compare){
      cat("map"," ")
Armin Rauschenberger's avatar
Armin Rauschenberger committed
727
      start <- Sys.time()
Armin Rauschenberger's avatar
Armin Rauschenberger committed
728 729
      if(any(family!="gaussian")){
        stop("map requires \"gaussian\" family.")
Armin Rauschenberger's avatar
Armin Rauschenberger committed
730
      }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
731 732
      mean <- colMeans(y0)
      y0s <- y0-matrix(data=mean,nrow=nrow(X0),ncol=ncol(y0),byrow=TRUE)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
733
      lamL1.v <- lamL2.v <- exp(seq(from=0,to=5,length.out=11))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
734
      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
735
      #graphics::plot(x=lamL1.v,y=log(as.numeric(cv$ols.cv[,3])))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
736 737 738 739 740 741 742 743
      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
744
      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
745
      end <- Sys.time()
Armin Rauschenberger's avatar
Armin Rauschenberger committed
746
      time$map <- as.numeric(difftime(end,start,units="secs"))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
747
    }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
748 749
    
    if("mrf" %in% compare){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
750 751 752 753 754 755
      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
756
                                   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
757
      # use n_tree=500, m_feature=floor(ncol(X0)/3)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
758
      # alternative: IntegratedMRF
Armin Rauschenberger's avatar
Armin Rauschenberger committed
759 760 761
      # 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
762 763
    }
    
Armin Rauschenberger's avatar
Armin Rauschenberger committed
764 765 766 767 768 769
    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
770
      invisible(utils::capture.output(object <- SiER::cv.SiER(X=X0,Y=y0,K.cv=3)))
Armin Rauschenberger's avatar
Armin Rauschenberger committed
771 772 773 774 775 776 777
      # 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
778
    if("mcen" %in% compare){
Armin Rauschenberger's avatar
Armin Rauschenberger committed
779 780 781 782 783 784 785 786 787 788
      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
789 790
                              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
791 792
      #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
793
      pred$mcen[foldid.ext==i,] <- as.matrix(temp)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
794 795 796
      # 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
797 798
    }
    
Armin Rauschenberger's avatar
Armin Rauschenberger committed
799 800 801
    if("gpm" %in% compare){
      cat("gpm"," ")
      start <- Sys.time()
Armin Rauschenberger's avatar
Armin Rauschenberger committed
802 803 804
      if(any(family!="gaussian")){
        stop("GPM requires \"gaussian\" family.",call.=FALSE)
      }
Armin Rauschenberger's avatar
Armin Rauschenberger committed
805
      object <- GPM::Fit(X=X0,Y=y0)
Armin Rauschenberger's avatar
Armin Rauschenberger committed
806
      pred$gpm[foldid.ext==i,] <- GPM::Predict(XF=X1,Model=object)$YF
Armin Rauschenberger's avatar
Armin Rauschenberger committed
807 808 809 810
      end <- Sys.time()
      time$gpm <- as.numeric(difftime(end,start,units="secs"))
    }