R/grnn.search_rsq.R

Defines functions grnn.search_rsq

Documented in grnn.search_rsq

#' Search for the optimal value of GRNN smoothing parameter based on r-square
#'
#' The function \code{grnn.search_rsq} searches for the optimal value of GRNN smoothing parameter by cross-validation.
#' It is applicable to the functional approximation
#'
#' @param net    A GRNN object generated by grnn.fit() 
#' @param sigmas A numeric vector to search for the best smoothing parameter
#' @param nfolds A scalar for the number of n-fold, 4 by default
#' @param seed   The seed value for the n-fold cross-validation, 1 by default
#'
#' @return The list of all searching outcomes and the best outcome
#'
#' @examples
#' data(iris, package = "datasets")
#' Y <- ifelse(iris[, 5] == "setosa", 1, 0)
#' X <- scale(iris[, 1:4])
#' gnet <- grnn.fit(x = X, y = Y)
#' grnn.search_rsq(net = gnet, sigmas = seq(3), nfolds = 2)

grnn.search_rsq <- function(net, sigmas, nfolds = 4, seed = 1) {
  if (class(net) != "General Regression Neural Net") stop("net needs to be a GRNN.", call. = F)
  if (is.vector(sigmas) != T) stop("sigmas needs to be a vector.", call. = F)

  fd <- folds(seq(nrow(net$x)), n = nfolds, seed = seed)
  cv <- function(s) {
    rs <- Reduce(rbind,
            lapply(fd,
              function(f) data.frame(ya = net$y[f],
                                     yp = grnn.predict(grnn.fit(net$x[-f, ], net$y[-f],  sigma = s),
                                                       net$x[f, ]))))
    return(data.frame(sigma = s, r2 = MLmetrics::R2_Score(y_pred = rs$yp, y_true = rs$ya)))
  }

  cls <- parallel::makeCluster(min(nfolds, parallel::detectCores() - 1), type = "PSOCK")
  obj <- c("fd", "net", "grnn.fit", "grnn.predone", "grnn.predict")
  parallel::clusterExport(cls, obj,  envir = environment())
  rst <- Reduce(rbind, parallel::parLapply(cls, sigmas, cv))
  parallel::stopCluster(cls)
  return(list(test = rst, best = rst[rst$r2 == max(rst$r2), ]))
}

Try the yager package in your browser

Any scripts or data that you put into this service are public.

yager documentation built on Oct. 26, 2020, 1:06 a.m.