grad_share: Split function and gradient calculation

Description Usage Arguments Value Examples

Description

Calculate function and gradient together but access separately. Reduces computation since they share data in calculation. Doesn't have to be function and gradient, can be any two values calculated together but accessed separately. Useful in optimization when function evaluation is expensive since the chain rule means many parts of function and gradient are the same.

Usage

1
grad_share(fn_gr)

Arguments

fn_gr

A function that returns a list of two values. Both are calculated when fn is called, but only the first is returned. The second is returned when gr is called but nothing is recalculated.

Value

An environment with two functions, fn and gr.

Examples

1
2
3
4
5
6
7
quad_share <- function(x){list(sum(x^4), 4*x^3)}
share <- grad_share(quad_share)
share$fn(1)
share$gr(1)
share$gr(2)
share$fn(2)
share$gr(2)

Example output

[1] 1
[1] 4
[1] 32
[1] 16
[1] 32

splitfngr documentation built on May 2, 2019, 8:54 a.m.