R/pnn.parpred.R

Defines functions pnn.parpred

Documented in pnn.parpred

#' Calculate predicted probabilities of PNN by using parallelism
#'
#' The function \code{pnn.parpred} calculates a matrix of PNN predicted probabilities based on an input matrix
#'
#' @param net A PNN object generated by pnn.fit() 
#' @param x   A matrix of input predictors 
#'
#' @return A matrix of predicted probabilities 
#'
#' @seealso \code{\link{pnn.predict}}
#'
#' @examples
#' data(iris, package = "datasets")
#' Y <- iris[, 5]
#' X <- scale(iris[, 1:4])
#' pnet <- pnn.fit(x = X, y = Y)
#' pnn.parpred(pnet, X[seq(5), ])

pnn.parpred <- function(net, x) {
  if (class(net) != "Probabilistic Neural Net") stop("net needs to be a PNN object.", call. = F)
  if (is.matrix(x) == F) stop("x needs to be a matrix.", call. = F)
  if (anyNA(x) == T) stop("NA found in x.", call. = F)
  if (ncol(x) != ncol(net$x)) stop("x dimension is not consistent with grnn.", call. = F)

  cls <- parallel::makeCluster(min(floor(nrow(x) / 3), parallel::detectCores() - 1), type = "PSOCK")
  obj <- c("net", "x", "pnn.predone", "pnn.predict")
  parallel::clusterExport(cls, obj, envir = environment())
  spx <- parallel::parLapplyLB(cls, parallel::clusterSplit(cls, seq(nrow(x))), function(c_) x[c_, ])
  rst <- parallel::parLapplyLB(cls, spx, function(x_) pnn.predict(net, x_))
  parallel::stopCluster(cls)
  return(Reduce(rbind, rst))
}

Try the yap package in your browser

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

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