R/hopfield.R

#' Learn & Feed
#'
#' Learn and feed a \code{\link{hopfield}} brain.
#'
#' @inheritParams architecture
#' @param ... Bare column names.
#' @param data A data.frame of training or test data.
#' @param print Whether to print results in the console.
#' @param scale Set to \code{TRUE} to scale the data with \code{\link{balance}}.
#'
#' @examples
#' train_data <- dplyr::tibble(
#'   a = c(0, 1),
#'   b = c(1, 1),
#'   c = c(0, 1),
#'   d = c(1, 1)
#' )
#'
#' test_data <- dplyr::tibble(
#'   a = c(0, 0),
#'   b = c(1, 1),
#'   c = c(0, 1),
#'   d = c(1, 1)
#' )
#'
#' brain() %>%
#'   hopfield(10) %>%
#'   learn_data(train_data) %>%
#'   learn_pattern(a, b, c, d) %>%
#'   learn() %>%
#'   feed_data(test_data) %>%
#'   feed(a, b, c, d)
#'
#' @seealso \code{\link{get_training}}
#'
#' @rdname hopfield
#' @export
learn <- function(brain){

  brain$brain$assign("lrn", brain$opts$training$input)
  brain$brain$eval("var history = net.learn(lrn)")

  if(isTRUE(print))
    print(get_training(brain))

  brain$opts$training <- TRUE

  return(brain)

}

#' @rdname hopfield
#' @export
feed <- function(brain, ..., scale = FALSE, data = NULL, print = FALSE){

  data <- .get_data(data, brain, "activate")

  data <- data %>%
    dplyr::select(...) %>%
    unname() %>%
    apply(2, function(x, scale){
      if(isTRUE(scale))
        balance(x)
      else
        x
    }, scale = scale) %>%
    apply(1, as.list)

  brain$brain$eval("var activation = []")

  for(i in 1:length(data)){
    brain$brain$assign("act", data[[i]])
    brain$brain$eval(
      paste0("activation.push(net.feed(act))")
    )
  }

  brain$opts$activate <- TRUE

  if(isTRUE(print))
    print(get_activations(brain))

  return(brain)

}
brain-r/brain documentation built on May 21, 2019, 4:05 a.m.