R/pense_fa.R

Defines functions cv_pense_fa

Documented in cv_pense_fa

#' Cross Validate Penalized Elastic Net S-Estimator with a Fixed Alpha Parameter (PENSE)
#'
#' @param formula a model formula
#' @param data a training data set
#' @param alpha the mixing parameter for the elastic net. alpha = 0 yields ridge regression, and alpha = 1 yields the LASSO.
#' @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 folds a vector of pre-set cross-validation or bootstrap folds from caret::createResample or
#' caret::createFolds.
#' @param nrep the number of repetitions for cv.method = "repeatedcv". defaults to 4.
#' @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 "RobustMAE" (the default)
#' or "RobustMSE".
#' @param max.c the largest value of the constant for calculating lambda. defaults to 8, but
#' may be adjusted. for example, if the error metric becomes constant after a certain
#' value of C, it may be advisable to lower max.c to a smaller value to obtain
#' a more fine-grained grid over the plausible values.
#'
#' @return
#' a train object
#' @export
#'
cv_pense_fa = function(formula, data, alpha = 1,  cv.method = "boot632", nfolds = 5, nrep = 4, folds = NULL, tunlen = 25, crit = "RobustMAE", max.c = 50){

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

  PENSE <- list(type = "Regression",
                library = "pense",
                loop = NULL)

  PENSE$alpha <- alpha

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

  huber.scale = function(y){
    MASS::hubers(y,
                 initmu =
                   hubers(y,
                          initmu = MASS::hubers(y)$mu,
                          s = sqrt(mean(c(sd(y)^2, mad(y)^2)))
                   )$mu)$s
  }

  lm.betas <- lmSolve(formula, data)
  model.mat <- model.matrix(formula, data)
  lm.pred <- as.vector(lm.betas) %*% t(model.mat)
  lm.res <- as.vector(model.frame(formula, data)[,1]) - lm.pred
  PENSE$noiseSD <- huber.scale(lm.res)

  PENSE$max.c <- max.c
  penseGrid <- function(x, y, max.c = PENSE$max.c, alpha = PENSE$alpha, noise.sd = PENSE$noiseSD, len = NULL, search = "grid") {

    D = nrow(x)
    N = length(y)
    lambda0 = noise.sd * sqrt(log(D) / N)
    f = function(alpha){
      sqrt((2 - alpha)^3 / (2 - (1 - alpha)))
    }
    C <- seq(0.50, max.c, length.out = len)
    lambdas <- C * f(alpha) * lambda0

    ## use grid search:
    if(search == "grid"){
      search = "grid"
    } else {
      search = "grid"
    }

    grid <- expand.grid(lambda = lambdas, alpha = alpha)

    out <- grid
    return(out)
  }

  PENSE$grid <- penseGrid

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

    pense::pense(
      x = as.matrix(x),
      y = as.vector(y),
      lambda = param$lambda,
      alpha = param$alpha,
      options = pense_options(delta = 0.30,
                              maxit = 2500,
                              mscale_maxit = 1000,
                              eps = 1e-04,
                              mscale_eps = 1e-05),
      standardize = FALSE
    )
  }

  PENSE$fit <- penseFit
  PENSE$prob <- penseFit

  pensePred <- function(modelFit, newdata, preProc = NULL, submodels = NULL){
    pense:::predict.pense(modelFit, newdata, exact = TRUE)
  }

  PENSE$predict <- pensePred

  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 {

        huber.mean = function(y) {
          MASS::hubers(y, initmu =
                         MASS::hubers(y,
                                      initmu = MASS::hubers(y, s = sd(y))$mu,
                                      s = sqrt(mean(c(sd(y)^2, mad(y)^2))))$mu)$mu
        }

        robmse <- huber.mean((pred - obs)^2)
        robmae <- huber.mean(abs(pred - obs))
        out <- c(robmse, robmae)
      }
      names(out) <- c("RobustMSE", "RobustMAE")
    }
    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
  }

  robustSummary = 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",
                               summaryFunction = robustSummary,
                               search = "grid")
  } else {

    fitControl <- trainControl(method = cv.method,
                               number = nfolds,
                               index = folds,
                               savePredictions = "all",
                               summaryFunction = robustSummary,
                               search = "grid")
  }


  fitted.models <- train(formula, data,
                         method = PENSE,
                         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.