R/io.R

#' Transfer
#'
#' Copy, convert or load your network.
#'
#' @inheritParams architecture
#' @param import An object of class \code{brain_export} as returned by \code{export}.
#'
#' @section Functions:
#' \itemize{
#'   \item{\code{export}: Export the network to a \code{list}.}
#'   \item{\code{import}: Import a pre-trained network.}
#'   \item{\code{copy}: Copy the current network.}
#' }
#'
#' @examples
#' df <- dplyr::tibble(
#'   x = c(0, 0, 1, 1),
#'   y = c(0, 1, 0, 1),
#'   z = c(0, 1, 1, 0)
#' )
#'
#' br <- brain() %>%
#'   perceptron(c(2,3,1)) %>%
#'   train_data(df) %>%
#'   train_input(x, y) %>%
#'   train_output(z) %>%
#'   train(
#'     cost = cost_function("mse")
#'   ) %>%
#'   export()
#'
#' test_data <- dplyr::tibble(
#'   x = c(0, 0),
#'   y = c(0, 1)
#' )
#'
#' import(br) %>%
#'   activate_data(test_data) %>%
#'   activate(x, y)
#'
#' @details Training a large network may take some time, these functions allows you to export the trained
#' brain to later import it, avoiding having to re-train it.
#'
#' @return \code{\link{copy}} returns a copy of the brain, \code{\link{export}} returns a list of class
#' \code{brain_export} that can be imported by \code{\link{import}} which returns a brain of class \code{brain},
#' just like \code{\link{brain}}.
#'
#' @name transfer
#' @export
export <- function(brain){
  brain$brain$eval("var exported = net.toJSON();")
  export <- brain$brain$get("exported", simplifyVector = FALSE)
  structure(export, class = c("brain_export", "list"))
}

#' @rdname transfer
#' @export
import <- function(import){

  if(missing(import))
    stop("missing import", call. = FALSE)

  if(inherits(import, "brain_object"))
    stop("import must be an object of class brain_export")

  br <- brain()
  br$brain$assign("json", import)
  br$brain$eval("var net = synaptic.Network.fromJSON(json);")

  return(br)
}

#' @rdname transfer
#' @export
copy <- function(brain){
  export <- export(brain)
  import(export)
}
brain-r/brain documentation built on May 21, 2019, 4:05 a.m.