R/nn_sum.R

Defines functions `%nn_sum%` nn_sum

Documented in nn_sum

source("R/comp.R")
source("R/stacking.R")
source("R/aux_fun.R")
source("R/Aff.R")
source("R/is_nn.R")

#' @title nn_sum
#' @description A function that performs the neural network sum for two
#' neural networks of the type generated by
#' create_nn().
#'
#' For a specific definition, see:
#'
#' @references Proposition 2.25. Grohs, P., Hornung, F., Jentzen, A. et al.
#' Space-time error estimates for deep neural network approximations
#' for differential equations. (2019).
#' \url{https://arxiv.org/abs/1908.03833}.
#'
#' @param nu_1 A neural network.
#' @param nu_2 A neural network.
#'
#' @return A neural network that is the neural network sum of \eqn{\nu_1} and \eqn{\nu_2}
#' i.e. \eqn{\nu_1 \oplus \nu_2}.
#'
#' \emph{Note:} We have two versions, an infix version and a prefix version.
#'
#' @examples
#' Prd(2.1, 0.1) |> nn_sum(Prd(2.1, 0.1))
#'
#' @export

nn_sum <- function(nu_1, nu_2) {
  if (nu_1 |> is_nn() &&
    nu_2 |> is_nn() &&
    inn(nu_1) == inn(nu_2) &&
    out(nu_1) == out(nu_2)) {
    Cpy(2, inn(nu_1)) -> first_third
    nu_1 |> stk(nu_2) -> mid_third
    Sum(2, out(nu_1)) -> last_third

    last_third |>
      comp(mid_third) |>
      comp(first_third) -> return_network
    return(return_network)
  } else {
    stop("Only neural networks with same end-widths may be summed")
  }
}


#' Function for calculating neural network sums
#'
#' @param nu_1 A neural network.
#' @param nu_2 A neural network.
#'
#' @rdname nn_sum
#' @export
#'
`%nn_sum%` <- function(nu_1, nu_2) {
  if (nu_1 |> is_nn() &&
    nu_2 |> is_nn() &&
    inn(nu_1) == inn(nu_2) &&
    out(nu_1) == out(nu_2)) {
    Cpy(2, inn(nu_1)) -> first_third
    nu_1 |> stk(nu_2) -> mid_third
    Sum(2, out(nu_1)) -> last_third

    last_third |>
      comp(mid_third) |>
      comp(first_third) -> return_network
    return(return_network)
  } else {
    stop("Only neural networks of same end widths may be summed")
  }
}

Try the nnR package in your browser

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

nnR documentation built on May 29, 2024, 2:02 a.m.