🔎 How to download & run the codes?

All the source codes of the aggregation methods are available here . To run the codes, you can clone the repository directly or simply load the R script source file from the repository using devtools package in Rstudio as follow:

  1. Install devtools package using command:

    install.packages("devtools")

  2. Loading the source codes from GitHub repository using source_url function by:

    devtools::source_url("https://raw.githubusercontent.com/hassothea/AggregationMethods/main/MixCOBRARegressor.R")


✎ Note: All codes contained in this Rmarkdown are built with recent version of (version \(>\) 4.1, available here) and Rstudio (version > 2022.02.2+485, available here). Note also that the code chucks are hidden by default.

To see the codes, you can:


1 MixCobra & important packages

1.1 MixCobra method

This Rmarkdown provides the implementation of an aggregation method using input and output trade-off by Fischer and Mougeot (2019). Let \(\mathcal{D}_n=\{(x_1,y_1),...,(x_n,y_n)\}\) be a training data of size \(n\), where the input-output couples \((x_i,y_i)\in\mathbb{R}^d\times\mathbb{R}\) for all \(i=1,...,n\). \(\mathcal{D}_{n}\) is first randomly partitioned into \(\mathcal{D}_{k}\) and \(\mathcal{D}_{\ell}\) of size \(k\) and \(\ell\) respectively such that \(k+\ell=n\). We construct \(M\) regression estimators (machines) \(r_1,...,r_M\) using only \(\mathcal{D}_{k}\). Let \({\bf r}(x)=(r_1(x),...,r_M(x))^T\in\mathbb{R}^M\) be the vector of predictions of \(x\in\mathbb{R}^d\), the aggregation method evaluated at point \(x\) is defined by

\[\begin{equation} g_n(x)=\frac{\sum_{i=1}^{\ell}y_iK_{\alpha,\beta}(x-x_i,{\bf r}(x)-{\bf r}(x_i))}{\sum_{j=1}^{\ell}K_{\alpha,\beta}(x-x_j,{\bf r}(x)-{\bf r}(x_j))} \end{equation}\] where \(K:\mathbb{R}^{d+M}\to\mathbb{R}_+\) is a non-increasing kernel function with \(K_{\alpha,\beta}(u,v)=K(\frac{u}{\alpha},\frac{v}{\beta})\) for some smoothing parameter \(\alpha,\beta>0\) to be tuned, with the convention \(0/0=0\).

1.2 Important packages

We prepare all the necessary tools for this Rmarkdown. pacman package allows us to load (if exists) or install (if does not exist) any available packages from The Comprehensive R Archive Network (CRAN) of .

# Check if package "pacman" is already installed 

lookup_packages <- installed.packages()[,1]
if(!("pacman" %in% lookup_packages)){
  install.packages("pacman")
}

# To be installed or loaded
pacman::p_load(magrittr)
pacman::p_load(ggplot2)
pacman::p_load(tidyverse)

## package for "generateMachines"
pacman::p_load(tree)
pacman::p_load(glmnet)
pacman::p_load(randomForest)
pacman::p_load(FNN)
pacman::p_load(xgboost)
pacman::p_load(keras)
pacman::p_load(pracma)
pacman::p_load(latex2exp)
pacman::p_load(plotly)
pacman::p_load(dash)
rm(lookup_packages)

2 Basic Machine generator

This section provides functions to generate basic machines (regressors) to be aggregated.

2.1 Function : setBasicParameter_Mix

This function allows us to set the values of some key parameters of the basic machines.

  • Argument:

    • lambda : the penalty parameter \(\lambda\) used in penalized linear models: ridge or lasso.
    • k : the parameter \(k\) of \(k\)NN (knn) regression model and the default value is \(k=10\).
    • ntree : the number of trees in random forest (rf). By default, ntree = 300.
    • mtry : the number of random features chosen in each split of random forest procedure. By default, mtry = NULL and the default value of mtry of randomForest function from randomForest library is used.
    • eta_xgb : the learning rate \(\eta>0\) in gradient step of extreme gradient boosting method (xgb) of xgboost library.
    • nrounds_xgb : the parameter nrounds indicating the max number of boosting iterations. By default, nrounds_xgb = 100.
    • early_stop_xgb : the early stopping round criterion of xgboost function. By, default, early_stop_xgb = NULL and the early stopping function is not triggered.
    • max_depth_xgb : maximum depth of trees constructed in xgboost.
  • Value:

    This function returns a list of all the parameters given in its arguments, to be fed to the basicMachineParam argument of function generateMachines_Mix defined in the next section.


🧾 Remark.1: lambda, k, ntree can be a single value or a vector. In other words, each type of models can be constructed several times according to the values of the parameters \((\alpha, \beta)\) of the method.


setBasicParameter_Mix <- function(lambda = NULL,
                              k = 5, 
                              ntree = 300, 
                              mtry = NULL, 
                              eta_xgb = 1, 
                              nrounds_xgb = 100, 
                              early_stop_xgb = NULL,
                              max_depth_xgb = 3){
  return(list(
    lambda = lambda,
    k = k,
    ntree = ntree, 
    mtry = mtry, 
    eta_xgb = eta_xgb, 
    nrounds_xgb = nrounds_xgb, 
    early_stop_xgb = early_stop_xgb,
    max_depth_xgb = max_depth_xgb)
  )
}

2.2 Function : generateMachines_Mix

This function generates all the basic machines to be aggregated.

  • Argument:

    • train_input : a matrix or data frame of the training input data.
    • train_response : a vector of training response variable corresponding to the train_input.
    • scale_input : logical value specifying whether to scale the input data (to be between \(0\) and \(1\)) or not. By default, scale_input = FALSE.
    • scale_machine : logical value specifying whether to scale the predictions of the remaining part \(\mathcal{D}_{\ell}\) of the training data (to be between \(0\) and \(1\)) or not. By default, scale_machine = FALSE.
    • machines : types of basic machines to be constructed. It is a subset of {“lasso”, “ridge”, “knn”, “tree”, “rf”, “xgb”}. By default, machines = NULL and all the six types of basic machines are built.
    • splits : real number between \(0\) and \(1\) specifying the proportion of training data used to train the basic machines (\(\mathcal{D}_k\)). The remaining proportion of (\(1-\) splits) is used for the aggregation (\(\mathcal{D}_{\ell}\)). By default, splits = 0.5.
    • basicMachineParam : the option used to setup the values of parameters of each machines. One should feed the function setBasicParameter_Mix() defined above to this argument.
    • silent : a logical value to silent all the messages or information to be printed during the process of the method. By default, silent = FALSE.
  • Value:

    This function returns a list of the following objects.

    • fitted_remain : the predictions of the remaining part (\(\mathcal{D}_{\ell}\)) of the training data, used for the aggregation.
    • models : all the constructed basic machines (it contains only the values of parameter \(k\) for knn).
    • id2 : a logical vector of size equals to the number of lines of the training data indicating the location of the points, used to build the basic machines (FALSE) and the remaining ones (TRUE).
    • train_data : a list of the following objects:
      • train_input : training input data (scale or non-scaling accordingly).
      • predict_remain_org : predictions of the second part \({\cal D}_{\ell}\) of the training data without scaling.
      • train_response : the trainging response variable.
      • min_machine, max_machine : vectors of minimum and maximum predicted values of the remaining part \(\mathcal{D}_{\ell}\) of the training data. They are NULL if scale_machine = FALSE.
      • min_input, max_input : vectors of minimum and maximum values of each variable of the training input. They are NULL if scale_input = FALSE.

✎ Note: You may need to modify the function accordingly if you want to build different types of basic machines.


generateMachines_Mix <- function(train_input, 
                             train_response,
                             scale_input = FALSE,
                             scale_machine = FALSE,
                             machines = NULL, 
                             splits = 0.5, 
                             basicMachineParam = setBasicParameter_Mix()){
  lambda = basicMachineParam$lambda
  k <- basicMachineParam$k 
  ntree <- basicMachineParam$ntree 
  mtry <- basicMachineParam$mtry
  eta_xgb <- basicMachineParam$eta_xgb 
  nrounds_xgb <- basicMachineParam$nrounds_xgb
  early_stop_xgb <- basicMachineParam$early_stop_xgb
  max_depth_xgb <- basicMachineParam$max_depth_xgb
  
  # Packages
  pacman::p_load(tree)
  pacman::p_load(glmnet)
  pacman::p_load(randomForest)
  pacman::p_load(FNN)
  pacman::p_load(xgboost)
  # pacman::p_load(keras)
  
  # Preparing data
  input_names <- colnames(train_input)
  input_size <- dim(train_input)
  df_input <- train_input_scale <- train_input
  maxs <- mins <- NULL
  if(scale_input){
    maxs <- map_dbl(.x = df_input, .f = max)
    mins <- map_dbl(.x = df_input, .f = min)
    train_input_scale <- scale(train_input, center = mins, scale = maxs - mins)
  }
  if(is.matrix(train_input_scale)){
    df_input <- as_tibble(train_input_scale)
    matrix_input <- train_input_scale
  } else{
    df_input <- train_input_scale
    matrix_input <- as.matrix(train_input_scale)
  }
  
  # Machines
  lasso_machine <- function(x, lambda0){
    if(is.null(lambda)){
      cv <- cv.glmnet(matrix_train_x1, train_y1, alpha = 1, lambda = 10^(seq(-3,2,length.out = 50)))
      mod <- glmnet(matrix_train_x1, train_y1, alpha = 1, lambda = cv$lambda.min)
    } else{
      mod <- glmnet(matrix_train_x1, train_y1, alpha = 1, lambda = lambda0)
    }
    res <- predict.glmnet(mod, newx = x)
    return(list(pred = res,
                model = mod))
  }
  ridge_machine <- function(x, lambda0){
    if(is.null(lambda)){
      cv <- cv.glmnet(matrix_train_x1, train_y1, alpha = 0, lambda = 10^(seq(-3,2,length.out = 50)))
      mod <- glmnet(matrix_train_x1, train_y1, alpha = 0, lambda = cv$lambda.min)
    } else{
      mod <- glmnet(matrix_train_x1, train_y1, alpha = 0, lambda = lambda0)
    }
    res <- predict.glmnet(mod, newx = x)
    return(list(pred = res,
                model = mod))
  }
  tree_machine <- function(x, pa = NULL) {
    mod <- tree(as.formula(paste("train_y1~", 
                                 paste(input_names, sep = "", collapse = "+"), 
                                 collapse = "", 
                                 sep = "")), 
                data = df_train_x1)
    res <- as.vector(predict(mod, x))
    return(list(pred = res,
                model = mod))
  }
  knn_machine <- function(x, k0) {
    mod <- knn.reg(train = matrix_train_x1, test = x, y = train_y1, k = k0)
    res = mod$pred
    return(list(pred = res,
                model = k0))
  }
  RF_machine <- function(x, ntree0) {
    if(is.null(mtry)){
      mod <- randomForest(x = df_train_x1, y = train_y1, ntree = ntree0)
    }else{
      mod <- randomForest(x = df_train_x1, y = train_y1, ntree = ntree0, mtry = mtry)
    }
    res <- as.vector(predict(mod, x))
    return(list(pred = res,
                model = mod))
  }
  xgb_machine = function(x, nrounds_xgb0){
    mod <- xgboost(data = matrix_train_x1, 
                   label = train_y1, 
                   eta = eta_xgb,
                   nrounds = nrounds_xgb0,
                   objective = "reg:squarederror",
                   early_stopping_rounds = early_stop_xgb,
                   max_depth = max_depth_xgb,
                   verbose = 0)
    res <- predict(mod, x)
    return(list(pred = res,
                model = mod))
  }
  
  # All machines
  all_machines <- list(lasso = lasso_machine, 
                       ridge = ridge_machine, 
                       knn = knn_machine, 
                       tree = tree_machine, 
                       rf = RF_machine,
                       xgb = xgb_machine)
  # All parameters
  all_parameters <- list(lasso = lambda, 
                         ridge = lambda, 
                         knn = k, 
                         tree = 1, 
                         rf = ntree,
                         xgb = nrounds_xgb)
  if(is.null(machines)){
    mach <- c("lasso", "ridge", "knn", "tree", "rf", "xgb")
  }else{
    mach <- machines
  }
  # Extracting data
  M <- length(mach)
  size_D1 <- floor(splits*input_size[1])
  id_D1 <- logical(input_size[1])
  id_D1[sample(input_size[1], size_D1)] <- TRUE
  
  df_train_x1 <- df_input[id_D1,]
  matrix_train_x1 <- matrix_input[id_D1,]
  train_y1 <- train_response[id_D1]
  df_train_x2 <- df_input[!id_D1,]
  matrix_train_x2 <- matrix_input[!id_D1,]
  
  # Function to extract df and model from 'map' function
  extr_df <- function(x, id){
    return(tibble("r_{{id}}":= as.vector(pred_m[[x]]$pred)))
  }
  extr_mod <- function(x, id){
    return(pred_m[[x]]$model)
  }
  
  pred_D2 <- c()
  all_mod <- c()
  cat("\n* Building basic machines ...\n")
  cat("\t~ Progress:")
  for(m in 1:M){
    if(mach[m] %in% c("tree", "rf")){
      x0_test <- df_train_x2
    } else {
      x0_test <- matrix_train_x2
    }
    if(is.null(all_parameters[[mach[m]]])){
      para_ <- 1
    }else{
      para_ <- all_parameters[[mach[m]]]
    }
    pred_m <-  map(para_, 
                   .f = ~ all_machines[[mach[m]]](x0_test, .x))
    tem0 <- imap_dfc(.x = 1:length(para_), 
                     .f = extr_df)
    tem1 <- imap(.x = 1:length(para_), 
                 .f = extr_mod)
    names(tem0) <- names(tem1) <- paste0(mach[m], 1:length(para_))
    pred_D2 <- bind_cols(pred_D2, as_tibble(tem0))
    all_mod[[mach[m]]] <- tem1
    cat(" ... ", round(m/M, 2)*100L,"%", sep = "")
  }
  max_M <- min_M <- NULL
  pred_D2_ <- pred_D2
  if(scale_machine){
    max_M <- map_dbl(.x = pred_D2, .f = max)
    min_M <- map_dbl(.x = pred_D2, .f = min)
    pred_D2 <- scale(pred_D2, center = min_M, scale = max_M - min_M)
  }
  return(list(fitted_remain = pred_D2,
              models = all_mod,
              id2 = !id_D1,
              train_data = list(train_input = train_input_scale, 
                                train_response = train_response,
                                predict_remain_org = pred_D2_,
                                min_machine = min_M,
                                max_machine = max_M,
                                min_input = mins,
                                max_input = maxs)))
}

Example.1: In this example, the method is implemented on Boston data of MASS library. The basic machines “rf”, “knn” and “xgb” are built on the first part of the training data (\(\mathcal{D}_{k}\)), and the Root Mean Square Errors (RMSE) evaluated on the second part of the training data (\(\mathcal{D}_{\ell}\)) used for aggregation) are reported.


pacman::p_load(MASS)
df <- Boston
basic_machines <- generateMachines_Mix(train_input = df[,1:13],
                 train_response = df[,14],
                 scale_input = TRUE,
                 machines = c("rf", "knn", "xgb"),
                 basicMachineParam = setBasicParameter_Mix(lambda = 1:10/10, 
                                                ntree = 10:20 * 25,
                                                k = c(2:10)))

* Building basic machines ...
    ~ Progress: ... 33% ... 67% ... 100%
basic_machines$train_data$predict_remain_org %>%
  sweep(1, df[basic_machines$id2, "medv"]) %>%
  .^2 %>%
  colMeans %>%
  t %>%
  sqrt %>%
  as_tibble

3 Optimization algorithm

This part provides functions to approximate the key parameters \((\alpha,\beta)\in(\mathbb{R}_+^*)^2\) of the aggregation. Two important optimization methods are implemented: gradient descent algorithm (grad) and grid search (grid).

3.1 Gradient descent algorithm

3.1.1 Function : setGradParameter_Mix

This function allows us to set the values of parameters needed to process the gradient descent algorithm to approximate the hyperparameter of the method.

  • Argument:

    • val_init : a 2D vector of initial values of gradient descent iteration. By default, val_init = NULL and the algorithm will select the best value (with smallest cost function) among alpha_range and beta_range values of parameters.
    • rate : the 2D real-valued vector or a string of learning rate in gradent descent algorithm. By default, rate = NULL (or “auto”) and the value coef_auto = c(1, 1) will be used. It can also be a functional rate, which is a string, an element of {“logarithm”, “sqrtroot”, “linear”, “polynomial”, “exponential”}. Each rate is defined according to coef_ type arguments bellow.
    • alpha_range : a range vector of \(\alpha\) values to be considered as the initial value in gradient step. By default, alpha_range = seq(0.0001, 10, length.out = 5).
    • beta_range : a range vector of \(\beta\) values to be considered as the initial value in gradient step. By default, beta_range = seq(0.0001, 50, length.out = 5).
    • max_iter : maximum itertaion of gradient descent algorithm. By default, max_iter = 100.
    • print_step : a logical value controlling whether to print the result of each gradient step or not in order to keep track of the algorithm. By default, print_step = TRUE.
    • print_result : a logical value controlling whether to print the result of the algorithm or not. By default, print_result = TRUE.
    • figure : a logical value controlling whether to plot a graphic of the result or not. By default, figure = TRUE.
    • coef_auto : the constant learning rate when rate = NULL. By default, coef_auto = c(1, 1).
    • coef_log : the coefficinet multiplying to the logarithmic increment of the learning rate, i.e., rate \(=\) coef_log\(\times \log(1+t)\) where \(t\) is the numer number of iteration. By default, coef_log = 1.
    • coef_sqrt : the coefficinet multiplying to the square root increment of the learning rate, i.e., rate \(=\) coef_sqrt\(\times \sqrt{t}\). By default, coef_sqrt = 1.
    • coef_lm : the coefficinet multiplying to the linear increment of the learning rate, i.e., rate \(=\) coef_lm\(\times t\). By default, coef_lm = 1.
    • deg_poly : the degree of the polynomial increment of the learning rate, i.e., rate \(=t^{\texttt{deg_poly}}\). By default, deg_poly = 2.
    • base_exp : the base of the exponential increment of the learning rate, i.e., rate \(=\) base_exp\(^t\). By default, base_exp = 1.5.
    • axes : names of \(x,y\) and \(z\)-axis respectively. By default, axes = c("alpha", "beta", "L1 norm of gradient").
    • title : the title of the plot. By default, title = NULL and the default title is Gradient step.
    • threshold : the threshold to stop the algorithm what relative change is smaller than this value. By default, threshold = 1e-10.
  • Value:

    This function returns a list of all the parameters given in its arguments.

setGradParameter_Mix <- function(val_init = NULL,
                             rate = NULL, 
                             alpha_range = seq(0.0001, 10, length.out = 5),
                             beta_range = seq(0.0001, 50, length.out = 5),
                             max_iter = 100, 
                             print_step = TRUE, 
                             print_result = TRUE,
                             figure = TRUE, 
                             coef_auto = c(1, 1),
                             coef_log = 1,
                             coef_sqrt = 1,
                             coef_lm = 1,
                             deg_poly = 2,
                             base_exp = 1.5,
                             axes = c("alpha", "beta", "L1 norm of gradient"),
                             title = NULL,
                             threshold = 1e-10) {
  return(
    list(val_init = val_init,
      rate = rate,
      alpha_range = alpha_range,
      beta_range = beta_range,
      max_iter = max_iter,
      print_step = print_step,
      print_result = print_result,
      figure = figure,
      coef_auto = coef_auto,
      coef_log = coef_log,
      coef_sqrt = coef_sqrt,
      coef_lm = coef_lm,
      deg_poly = deg_poly,
      base_exp = base_exp,
      axes = axes,
      title = title,
      threshold = threshold
    )
  )
}

3.1.2 Function : gradOptimizer_Mix

This function performs gradient descent algorithm to approximate the minimizer of any given functions (convex or locally convex around its optimizer).

  • Argument:

    • obj_fun : the objective function for which its minimizer is to be estimated. It should take a 2D vector as an input.
    • setParameter : the control of gradient descent parameters which should be the output of function setGradParameter_Mix() defined earlier.
    • silent : a logical value to silent all the messages or information to be printed during the process of the method. By default, silent = FALSE.
  • Value:

    This function returns a list of the following objects:

    • opt_param : the observed value of the minimizer.
    • opt_error : the value of the optimal risk.
    • all_grad : the matrix of all the gradients collected during the walk of the algorithm (by row).
    • all_param : the matrix of all parameters collected during the walk of the algorithm (by row).
    • run_time : the running time of the algorithm.
gradOptimizer_Mix <- function(obj_fun,
                          setParameter = setGradParameter_Mix(),
                          silent = FALSE) {
  start.time <- Sys.time()
  # Optimization step:
  # ==================
  spec_print <- function(x, dig = 5) return(ifelse(x > 1e-6, 
                                          format(x, digit = dig, nsmall = dig), 
                                          format(x, scientific = TRUE, digit = dig, nsmall = dig)))
  collect_val <- c()
  gradients <- c()
  if (is.null(setParameter$val_init)){
    range_alp <- rep(setParameter$alpha_range, length(setParameter$beta_range))
    range_bet <- rep(setParameter$beta_range, length(setParameter$alpha_range))
    tem <- map2_dbl(.x = range_alp,
                    .y = range_bet,
                    .f = ~ obj_fun(c(.x, .y)))
    id0 <- which.min(tem)
    val <- val0 <- c(range_alp[id0], range_bet[id0])
    grad_ <- pracma::grad(
      f = obj_fun,
      x0 = val0,
      heps = .Machine$double.eps ^ (1 / 3))
  } else{
    val <- val0 <- setParameter$val_init
    grad_ <- pracma::grad(
      f = obj_fun, 
      x0 = val0, 
      heps = .Machine$double.eps ^ (1 / 3))
  }
  if(setParameter$print_step & !silent){
    cat("\n* Gradient descent algorithm ...")
    cat("\n  Step\t|  alpha    ;  beta   \t|  Gradient (alpha ; beta)\t|  Threshold \n")
    cat(" ", rep("-", 80), sep = "")
    cat("\n   0 \t| ", spec_print(val0[1])," ; ", spec_print(val0[2]),
        "\t| ", spec_print(grad_[1], 6), " ; ", spec_print(grad_[2], 5), 
        " \t| ", setParameter$threshold, "\n")
    cat(" ", rep("-",80), sep = "")
  }
  if (is.numeric(setParameter$rate)){
    lambda0 <- setParameter$rate / abs(grad_)
    rate_GD <- "auto"
  } else{
    r0 <- setParameter$coef_auto / abs(grad_)
    # Rate functions
    rate_func <- list(auto = r0, 
                      logarithm = function(i)  setParameter$coef_log * log(2 + i) * r0,
                      sqrtroot = function(i) setParameter$coef_sqrt * sqrt(i) * r0,
                      linear = function(i) setParameter$coef_lm * (i) * r0,
                      polynomial = function(i) i ^ setParameter$deg_poly * r0,
                      exponential = function(i) setParameter$base_exp ^ i * r0)
    rate_GD <- match.arg(setParameter$rate, 
                         c("auto", 
                          "logarithm", 
                          "sqrtroot", 
                          "linear", 
                          "polynomial", 
                          "exponential"))
    lambda0 <- rate_func[[rate_GD]]
  }
  i <- 0
  grad0 <- 10*grad_ 
  if (is.numeric(setParameter$rate) | rate_GD == "auto") {
    while (i < setParameter$max_iter) {
      if(any(is.na(grad_))){
        val0 <- c(runif(1, val0[1]*0.99, val0[1]*1.01), 
                  runif(1, val0[2]*0.99, val0[2]*1.01)) 
        grad_ = pracma::grad(
          f = obj_fun, 
          x0 = val0, 
          heps = .Machine$double.eps ^ (1 / 3)
       )
      }
      val <- val0 - lambda0 * grad_
      if (any(val < 0)){
        val[val < 0] <- val0[val < 0]/2
        lambda0[val < 0] <- lambda0[val < 0] / 2
      }
      if(i > 5){
        sign_ <- sign(grad_) != sign(grad0)
        if(any(sign_)){
          lambda0[sign_] = lambda0[sign_]/2
        }
      }
      relative <- sum(abs(val - val0)) / sum(abs(val0))
      test_threshold <- max(relative, sum(abs(grad_ - grad0)))
      if (test_threshold > setParameter$threshold){
        val0 <- val
        grad0 <- grad_
      } else{
        break
      }
      grad_ <- pracma::grad(
        f = obj_fun, 
        x0 = val0, 
        heps = .Machine$double.eps ^ (1 / 3)
      )
      i <- i + 1
      if(setParameter$print_step & !silent){
        cat("\n  ", i, "\t| ", spec_print(val[1], 4), " ; ", spec_print(val[2], 4), 
            "\t| ", spec_print(grad_[1], 5), " ; ", spec_print(grad_[2], 5), 
            "\t| ", test_threshold, "\r")
      }
      collect_val <- rbind(collect_val, val)
      gradients <- rbind(gradients, grad_)
    }
  }
  else{
    while (i < setParameter$max_iter) {
      if(any(is.na(grad_))){
        val0 <- c(runif(1, val0[1]*0.99, val0[1]*1.01), 
                  runif(1, val0[2]*0.99, val0[2]*1.01)) 
        grad_ = pracma::grad(
          f = obj_fun, 
          x0 = val0, 
          heps = .Machine$double.eps ^ (1 / 3)
       )
      }
      val <- val0 - lambda0(i) * grad_
      if (any(val < 0)){
        val[val < 0] <- val0[val < 0]/2
        r0[val < 0] <- r0[val < 0] / 2
      }
      if(i > 5){
        sign_ <- sign(grad_) != sign(grad0)
        if(any(sign_)){
          r0[sign_] <- r0[sign_] / 2
        }
      }
      relative <- sum(abs(val - val0)) / sum(abs(val0))
      test_threshold <- max(relative, sum(abs(grad_ - grad0)))
      if (test_threshold > setParameter$threshold){
        val0 <- val
        grad0 <- grad_
      }else{
        break
      }
      grad_ <- pracma::grad(
        f = obj_fun, 
        x0 = val0, 
        heps = .Machine$double.eps ^ (1 / 3)
      )
      if(setParameter$print_step & !silent){
        cat("\n  ", i, "\t| ", spec_print(val[1], 4), " ; ", spec_print(val[2], 4), 
            "\t| ", spec_print(grad_[1], 5), " ; ", spec_print(grad_[2], 5), 
            "\t| ", test_threshold, "\r")
      }
      i <- i + 1
      collect_val <- rbind(collect_val, val)
      gradients <- rbind(gradients, grad_)
    }
  }
  opt_ep <- val
  opt_risk <- obj_fun(opt_ep)
  if(setParameter$print_step & !silent){
    cat(rep("-", 80), sep = "")
    if(sum(abs(grad_)) == 0){
      cat("\n Stopped| ", spec_print(val[1], 4), " ; ", spec_print(val[2], 4), 
        "\t|\t ", 0, 
        "\t\t| ", test_threshold)
    }else{
      cat("\n Stopped| ", spec_print(val[1], 4), " ; ", spec_print(val[2], 4), 
        "\t| ", spec_print(grad_[1]), " ; ", spec_print(grad_[2]), 
        "\t| ", test_threshold)
    } 
  }
  if(setParameter$print_result & !silent){
    cat("\n ~ Observed parameter: (alpha, beta) = (", opt_ep[1], ", ", opt_ep[2], ") in",i, "itertaions.")
  }
  if (setParameter$figure) {
    if(is.null(setParameter$title)){
      tit <- paste("<b> L1 norm of gradient as a function of</b> (",
      setParameter$axes[1],",", 
      setParameter$axes[2], 
      ")")
    } else{
      tit <- setParameter$title
    }
    siz = length(collect_val[,1])
    fig <- tibble(x = collect_val[,1],
           y = collect_val[,2],
           z = apply(abs(gradients), 1, sum)) %>%
      plot_ly(x = ~x, y = ~y) %>% 
      add_trace(z = ~z,
                type = "scatter3d",
                mode = "lines",
                line = list(width = 6, 
                            color = ~z, 
                            colorscale = 'Viridis'),
                name = "Gradient step") %>%
      add_trace(x = c(opt_ep[1], opt_ep[1]),
                y = c(0, opt_ep[2]),
                z = ~c(z[siz], z[siz]),
                type = "scatter3d",
                mode = 'lines+markers',
                line = list( 
                  width = 2,
                  color = "#5E88FC", 
                  dash = TRUE),
                marker = list(
                  size = 4,
                  color = ~c("#5E88FC", "#38DE25")),
                name = paste("Optimal",setParameter$axes[1])) %>%
      add_trace(x = c(0, opt_ep[1]),
                y = c(opt_ep[2], opt_ep[2]),
                z = ~c(z[siz], z[siz]),
                type = "scatter3d",
                mode = 'lines+markers',
                line = list( 
                  width = 2,
                  color = "#F31536", 
                  dash = TRUE),
                marker = list(
                  size = 4,
                  color = ~c("#F31536", "#38DE25")),
                name = paste("Optimal",setParameter$axes[2]))  %>%
      add_trace(x = opt_ep[1],
                y = opt_ep[2],
                z = ~z[siz],
                type = "scatter3d",
                mode = 'markers',
                marker = list(
                  size = 5,
                  color = "#38DE25"),
                name = "Optimal point") %>%
      layout(title = list(text = tit,
                          x = 0.075, 
                          y = 0.925,
                          font = list(family = "Verdana",
                                      color = "#5E88FC")),
             legend = list(x = 100, y = 0.5),
             scene = list(
               xaxis = list(title = setParameter$axes[1]),
               yaxis = list(title = setParameter$axes[2]),
               zaxis = list( title = setParameter$axes[3])))
    fig %>% print
  }
  end.time = Sys.time()
  return(list(
    opt_param = opt_ep,
    opt_error = opt_risk,
    all_grad = gradients,
    all_param = collect_val,
    run_time = difftime(end.time, 
                        start.time, 
                        units = "secs")[[1]]
  ))
}

Example.2: Approximate \[(x^*,y^*)=\text{arg}\min_{x,y)\in\mathbb{R}^2}f(x,y),\] where \[f(x,y)=(x-1)^2(1+\sin^2(2.5(x-1)))+(y-1)^2(1+\sin^2(2.5(y-1)))\] Note that argument val_init is crucial since \(f\) is not convex.


object_func <- function(x) sum((x-1)^2*(1+sin(2.5*(x-1))^2))
p <- tibble::tibble(x = rep(seq(-4,6, length.out = 30),30), 
                      y = rep(seq(-3,7, length.out = 30), each = 30)) %>%
  mutate(z = map2_dbl(.x = x, .y = y, .f = ~ object_func(c(.x,.y)))) %>%
  plot_ly(x = ~x, y = ~y, z = ~z, type = "mesh3d") %>%
  add_trace(x = 1,
            y = 1,
            z = 0,
            type = "scatter3d", mode = "markers",
            name = "Optimal point") %>%
  layout(title = "Cost function")
show(p)
gd <- gradOptimizer_Mix(obj_fun = object_func,
                  setParameter = setGradParameter_Mix(val_init = c(2.4, 3.5),
                                                rate = "log",
                                                coef_auto = c(0.7, 0.7),
                                                print_step = TRUE,
                                                figure = TRUE,
                                                axes = c("x", "y")))

* Gradient descent algorithm ...
  Step  |  alpha    ;  beta     |  Gradient (alpha ; beta)  |  Threshold 
 --------------------------------------------------------------------------------
   0    |  2.40000  ;  3.50000  |  6.363771  ;  3.96922     |  1e-10 
 --------------------------------------------------------------------------------
   0    |  1.9148  ;  3.0148    |  0.79847  ;  1.51397  |  92.99696 

   1    |  1.8183  ;  2.7215    |  1.56931  ;  11.74586     |  8.020555 

   2    |  1.5790  ;  1.3607    |  2.50307  ;  1.48199  |  11.00273 

   3    |  1.1359  ;  0.9401    |  0.33091  ;  -1.2513e-01  |  11.19763 

   4    |  1.0707  ;  0.9796    |  0.14999  ;  -4.0947e-02  |  3.779282 

   5    |  1.0385  ;  0.9937    |  0.078525  ;  -1.2638e-02     |  0.2651093 

   6    |  1.0206  ;  0.9983    |  0.041395  ;  -3.3626e-03     |  0.09977258 

   7    |  1.0106  ;  0.9996    |  0.021197  ;  -7.565e-04  |  0.04640585 

   8    |  1.0052  ;  0.9999    |  0.010433  ;  -1.421e-04  |  0.02280361 

   9    |  1.0025  ;  1.0000    |  0.0049263  ;  -2.1917e-05    |  0.01137799 

   10   |  1.0011  ;  1.0000    |  0.0022329  ;  -2.7076e-06    |  0.005627254 

   11   |  1.0005  ;  1.0000    |  0.00097291  ;  -2.5805e-07   |  0.002712624 

   12   |  1.0002  ;  1.0000    |  0.00040805  ;  -1.7849e-08   |  0.001262474 

   13   |  1.0001  ;  1.0000    |  0.00016495  ;  -8.0023e-10   |  0.0005650944 

   14   |  1.0000  ;  1.0000    |  6.4339e-05  ;  -1.7661e-11   |  0.000243119 

   15   |  1.0000  ;  1.0000    |  2.4237e-05  ;  -1.2212e-14   |  0.0001006146 

   16   |  1.0000  ;  1.0000    |  8.8254e-06  ;  3.3307e-16    |  4.010183e-05 

   17   |  1.0000  ;  1.0000    |  3.1086e-06  ;  -1.1102e-16   |  1.541137e-05 

   18   |  1.0000  ;  1.0000    |  1.0599e-06  ;  -1.1102e-16   |  5.716742e-06 

   19   |  1.0000  ;  1.0000    |  3.5e-07  ;  -1.1102e-16  |  2.048728e-06 

   20   |  1.0000  ;  1.0000    |  1.1199e-07  ;  -1.1102e-16   |  7.09896e-07 

   21   |  1.0000  ;  1.0000    |  3.4741e-08  ;  -1.1102e-16   |  2.380033e-07 

   22   |  1.0000  ;  1.0000    |  1.0452e-08  ;  -1.1102e-16   |  7.72527e-08 

   23   |  1.0000  ;  1.0000    |  3.0504e-09  ;  -1.1102e-16   |  2.428952e-08 

   24   |  1.0000  ;  1.0000    |  8.6399e-10  ;  -1.1102e-16   |  7.401194e-09 

   25   |  1.0000  ;  1.0000    |  2.3754e-10  ;  -1.1102e-16   |  2.18645e-09 

   26   |  1.0000  ;  1.0000    |  6.3406e-11  ;  -1.1102e-16   |  6.264504e-10 

   27   |  1.0000  ;  1.0000    |  1.6436e-11  ;  -1.1102e-16   |  1.741309e-10 
--------------------------------------------------------------------------------
 Stopped|  1.0000  ;  1.0000    |  1.6436e-11  ;  -1.1102e-16   |  4.697043e-11
 ~ Observed parameter: (alpha, beta) = ( 1 ,  1 ) in 28 itertaions.

3.2 Grid search algorithm

3.2.1 Function : setGridParameter_Mix

This function allows us to set the values of parameters needed to process the grid search algorithm to approximate the hyperparameter of the method.

  • Argument:

    • min_alpha : mininum value of \(\alpha\) in the grid. By defualt, min_alpha = 1e-5.
    • max_alpha : maxinum value of \(\alpha\) in the grid. By defualt, max_alpha = 10.
    • min_beta : mininum value of \(\beta\) in the grid. By defualt, min_beta = 1e-5.
    • max_beta : maximum value of \(\beta\) in the grid. By defualt, max_alpha = 50.
    • n_alpha, n_beta = 30 : the number of \(\alpha\) and \(\beta\) respectively in the grid. By defualt, n_alpha = n_beta = 30.
    • parameters : the list of parameter \(\alpha\) and \(\beta\) in case non-uniform grid is considered. It should be a list of two vectors containing the values of \(\alpha\) and \(\beta\) respectively. By default, parameters = NULL and the default uniform grid is used.
    • axes : names of \(x,y\) and \(z\)-axis respectively. By default, axes = c("alpha", "beta", "Risk").
    • title : the title of the plot. By default, title = NULL and the default title is Cross-validation risk VS \((\alpha, \beta)\).
    • print_result : a logical value specifying whether to print the observed result or not.
    • figure : a logical value specifying whether to plot the graphic of cross-validation error or not.
    • silent : a logical value to silent all the messages or information to be printed during the process of the method. By default, silent = FALSE.
  • Value:

    This function returns a list of all the parameters given in its arguments.

setGridParameter_Mix <- function(min_alpha = 1e-5,
                                 max_alpha = 10,
                                 min_beta = 0.1,
                                 max_beta = 50,
                                 n_alpha = 30,
                                 n_beta = 30,
                                 parameters = NULL,
                                 axes = c("alpha", "beta", "Risk"),
                                 title = NULL,
                                 print_result = TRUE,
                                 figure = TRUE,
                                 silent = FALSE){
  return(list(min_alpha = min_alpha,
              max_alpha = max_alpha,
              min_beta = min_beta,
              max_beta = max_beta,
              n_alpha = n_alpha,
              n_beta = n_beta,
              axes = axes,
              title = title,
              parameters = parameters,
              print_result = print_result,
              figure = figure))
}

3.2.2 Function : gridOptimizer_Mix

This function performs grid search algorithm in approximating the values of parameters \(\alpha, \beta\) of the method.

  • Argument:

    • obj_fun : the objective function for which its minimizer is to be estimated. It should be a univarate function of real positive variables.
    • setParameter : the control of grid search algorithm parameters which should be the function setGridParameter_Mix() defined above.
    • silent : a logical value to silent all the messages or information to be printed during the process of the method. By default, silent = FALSE.
  • Value:

    This function returns a list of the following objects:

    • opt_param : the observed value of the minimizer.
    • opt_error : the value of optimal risk.
    • all_risk : the vector of all the errors evaluated at all the values of the considered parameters.
    • run_time : the running time of the algorithm.
gridOptimizer_Mix <- function(obj_func,
                         setParameter = setGridParameter_Mix(),
                         silent = FALSE){
  t0 <- Sys.time()
  if(is.null(setParameter$parameters)){
    param_list <- list(alpha =  rep(seq(setParameter$min_alpha, 
                                        setParameter$max_alpha,
                                        length.out = setParameter$n_alpha), 
                                    setParameter$n_beta),
                       beta =  rep(seq(setParameter$min_beta, 
                                       setParameter$max_beta,
                                       length.out = setParameter$n_beta),
                                   each = setParameter$n_alpha))
  } else{
    param_list <- list(alpha = rep(setParameter$parameters[[1]], 
                                   length(setParameter$parameters[[2]])),
                       beta = rep(setParameter$parameters[[2]], 
                                   each = length(setParameter$parameters[[1]])))
  }
  risk <- map2_dbl(.x = param_list$alpha,
                      .y = param_list$beta,
                      .f = ~ obj_func(c(.x, .y)))
  id_opt <- which.min(risk)
  opt_ep <- c(param_list$alpha[id_opt], param_list$beta[id_opt])
  opt_risk <- risk[id_opt]
  if(setParameter$print_result & !silent){
    cat("\n* Grid search algorithm...", "\n ~ Observed parameter: (alpha, beta) = (", opt_ep[1], 
        ", ", 
        opt_ep[2], ")", 
        sep = "")
  }
  if(setParameter$figure){
    if(is.null(setParameter$title)){
      tit <- paste("<b> Cross-validation risk as a function of</b> (",
                   setParameter$axes[1],",", 
                   setParameter$axes[2],
                   ")")
    } else{
      tit <- setParameter$title
    }
    fig <- tibble(alpha = param_list$alpha, 
                  beta = param_list$beta,
                  risk = risk) %>%
      plot_ly(x = ~alpha, y = ~beta, z = ~risk, type = "mesh3d") %>%
      add_trace(x = c(opt_ep[1], opt_ep[1]),
                y = c(0, opt_ep[2]),
                z = c(opt_risk, opt_risk),
                type = "scatter3d",
                mode = 'lines+markers',
                line = list( 
                  width = 2,
                  color = "#5E88FC", 
                  dash = TRUE),
                marker = list(
                  size = 4,
                  color = ~c("#5E88FC", "#38DE25")),
                name = paste("Optimal",setParameter$axes[1])) %>%
      add_trace(x = c(0, opt_ep[1]),
                y = c(opt_ep[2], opt_ep[2]),
                z = c(opt_risk, opt_risk),
                type = "scatter3d",
                mode = 'lines+markers',
                line = list( 
                  width = 2,
                  color = "#F31536", 
                  dash = TRUE),
                marker = list(
                  size = 4,
                  color = ~c("#F31536", "#38DE25")),
                name = paste("Optimal",setParameter$axes[2]))  %>%
      add_trace(x = opt_ep[1],
                y = opt_ep[2],
                z = opt_risk,
                type = "scatter3d",
                mode = 'markers',
                marker = list(
                  size = 5,
                  color = "#38DE25"),
                name = "Optimal point") %>%
      layout(title = list(text = tit,
                          x = 0.075, 
                          y = 0.925,
                          font = list(family = "Verdana",
                                      color = "#5E88FC")),
             legend = list(x = 100, y = 0.5),
             scene = list(xaxis = list(title = setParameter$axes[1]),
                          yaxis = list(title = setParameter$axes[2]),
                          zaxis = list( title = setParameter$axes[3])))
    print(fig)
  }
  t1 <- Sys.time()
  return(list(opt_param = opt_ep,
              opt_error = opt_risk,
              all_risk = risk,
              run_time = difftime(t1, 
                        t0, 
                        units = "secs")[[1]])
  )
}

Example.2: Again with grid search.


grid <- gridOptimizer_Mix(obj_fun = object_func,
                     setParameter = setGridParameter_Mix(min_alpha = -2,
                                                     max_alpha = 4,
                                                     min_beta = -2,
                                                     max_beta = 4,
                                                     n_alpha = 150,
                                                     n_beta = 150,
                                                     axes = c("x", "y", "z"),
                                                     title = "z = f(x,y)",
                                                     figure = TRUE))

* Grid search algorithm...
 ~ Observed parameter: (alpha, beta) = (1.020134, 1.020134)