R/elasticnet.R

Defines functions cv_elasticnet

Documented in cv_elasticnet

#' Cross validate elastic net tuning parameters
#'
#' @param formula a model formula
#' @param data a training data set
#' @param cv.method preferably one of "boot632" (the default), "cv", or "repeatedcv".
#' @param nfolds the number of bootstrap or cross-validation folds to use. defaults to 5.
#' @param nrep the number of repetitions for cv.method = "repeatedcv". defaults to 4.
#' @param folds a vector of pre-set cross-validation or bootstrap folds from caret::createResample or
#' caret::createFolds.
#' @param select the selection rule to use. Should be one of "best" or "oneSE" (the default).
#' @param tunlen the number of values for the unknown hyperparameter to test. defaults to 10.
#' @param crit the criterion by which to evaluate the model performance. must be one of "MAE" (the default)
#' or "MSE".
#'
#' @return
#' a train object
#' @export
#'
cv_elasticnet = function(formula, data, cv.method = "boot632", nfolds = 5, nrep = 4, tunlen = 10, folds = NULL, crit = c("MAE","MSE"), select = "oneSE"){

  if (!is.null(folds)) {
    nfolds = NULL
  }

  ELASTICNET <- list(type = "Regression",
                library = "glmnet",
                loop = NULL)

  ELASTICNET$parameters <- data.frame(parameter = c("alpha", "lambda"),
                                 class = rep("numeric", 2),
                                 label = c("alpha", "lambda"))


  elasticnetGrid <- function(x, y, len = NULL, search = "grid") {
    alpha <- seq(0, 1, length.out = 11)
    lambda <- exp(seq(log(0.001464844), log(10), len = len))
    ## use grid search:
    if(search == "grid"){search = "grid"} else {search = "grid"}
    grid <- expand.grid(alpha = alpha, lambda = lambda)
    out <- grid
    return(out)
  }

  ELASTICNET$grid <- elasticnetGrid

  elasticnetFit <- function(x, y, param, ...) {

    glmnet::glmnet(
      x = as.matrix(x),
      y = as.vector(y),
      lambda = param$lambda,
      alpha = param$alpha,
      standardize = FALSE
    )
  }

  ELASTICNET$fit <- elasticnetFit
  ELASTICNET$prob <- elasticnetFit

  elasticnetPred <- function(modelFit, newdata, preProc = NULL, submodels = NULL){

    newdata <- cbind.data.frame(y = rep(1, nrow(newdata)), newdata)
    as.vector(coef(modelFit)[,1] %*% t(as.matrix(newdata)))

  }

  ELASTICNET$predict <- elasticnetPred

  postRobResamp = function(pred, obs) {

    isNA <- is.na(pred)
    pred <- pred[!isNA]
    obs <- obs[!isNA]
    if (!is.factor(obs) && is.numeric(obs)) {
      if (length(obs) + length(pred) == 0) {
        out <- rep(NA, 2)
      }
      else {
        mse <- mean((pred - obs)^2)
        mae <- mean(abs(pred - obs))
        out <- c(mse, mae)
      }
      names(out) <- c("MSE", "MAE")
    }
    else {
      if (length(obs) + length(pred) == 0) {
        out <- rep(NA, 2)
      }
      else {
        pred <- factor(pred, levels = levels(obs))
        requireNamespaceQuietStop("e1071")
        out <- unlist(e1071::classAgreement(table(obs, pred)))[c("diag", "kappa")]
      }
      names(out) <- c("Accuracy", "Kappa")
    }
    if (any(is.nan(out)))
      out[is.nan(out)] <- NA
    out
  }

  glmnetSummary = function (data, lev = NULL, model = NULL){
    if (is.character(data$obs))
      data$obs <- factor(data$obs, levels = lev)
    postRobResamp(data[, "pred"], data[, "obs"])
  }


  if (cv.method == "repeatedcv") {
    fitControl <- trainControl(method = cv.method,
                               number = nfolds,
                               repeats = nrep,
                               index = folds,
                               savePredictions = "all",
                               allowParallel = TRUE,
                               selectionFunction = select,
                               summaryFunction = glmnetSummary,
                               search = "grid")
  } else {

    fitControl <- trainControl(method = cv.method,
                               number = nfolds,
                               index = folds,
                               allowParallel = TRUE,
                               selectionFunction = select,
                               savePredictions = "all",
                               summaryFunction = glmnetSummary,
                               search = "grid")
  }


  fitted.models <- train(formula, data,
                         method = ELASTICNET,
                         metric = crit,
                         tuneLength = tunlen,
                         maximize = FALSE,
                         preProcess = c("center", "scale"),
                         trControl = fitControl)


  return(fitted.models)

}
abnormally-distributed/cvreg documentation built on May 3, 2020, 3:45 p.m.