R/grnn.partial.R

Defines functions grnn.partial

Documented in grnn.partial

#' Derive the partial effect of a predictor used in a GRNN 
#'
#' The function \code{grnn.partial} derives the partial effect of a predictor used in a GRNN
#' by average-out values of the rest predictors.
#'
#' @param net  The GRNN object generated by grnn.fit() 
#' @param i    The ith predictor in the GRNN
#' @param plot TRUE or FALSE to plot the partial effect
#'
#' @return A plot of the partial effect or a dataframe of the partial effect
#'
#' @seealso \code{\link{grnn.margin}}
#'
#' @examples
#' data(iris, package = "datasets")
#' Y <- ifelse(iris[, 5] == "setosa", 1, 0)
#' X <- scale(iris[, 1:4])
#' gnet <- grnn.fit(x = X, y = Y)
#' \dontrun{
#' grnn.partial(gnet, 1, plot = FALSE)
#' }

grnn.partial <- function(net, i, plot = TRUE) {
  if (class(net) != "General Regression Neural Net") stop("net needs to be a GRNN.", call. = F)
  if (i > ncol(net$x)) stop("the selected variable is out of bound.", call. = F)
  if (!(plot %in% c(T, F))) stop("the plot input is not correct.", call. = F)

  xname <- colnames(net$x)[i]
  xi <- sort(unique(net$x[, i]))
  partial <- function(x_i) {
    x <- net$x
    x[, i] <-  rep(x_i, length(net$y))
    return(data.frame(x = x_i, p = mean(grnn.predict(net, x))))
  }

  cls <- parallel::makeCluster(min(length(xi), parallel::detectCores() - 1), type = "PSOCK")
  obj <- c("net", "grnn.fit", "grnn.predone", "grnn.predict")
  parallel::clusterExport(cls, obj,  envir = environment())
  rst <- Reduce(rbind, parallel::parLapply(cls, xi, partial))
  parallel::stopCluster(cls)
  if (plot == T) {
    plot(rst[, 1], rst[, 2], type = "b", lty = 4, lwd = 3, ylab = '', xlab = xname,
         main = "Partial Dependence", pch = 16, cex = 1.5, col = "royalblue", cex.main = 1, cex.lab = 1, yaxt = 'n')
    rug(rst[, 1], col = 'green4', ticksize = 0.03, lwd = 3)
  } else {
    return(rst)
  }
}

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.