cg_graph_gradients {cgraph} | R Documentation |
Differentiate a graph with respect to a given target node by reverse automatic differentiation.
cg_graph_gradients(graph, target, values = new.env(), index = NULL)
graph |
cg_graph object, graph that is differentiated. |
target |
cg_node object, node in the graph that is differentiated. |
values |
named list or environment, values that are subsituted for the input nodes in the graph. |
index |
numeric scalar, index of the target node that is differentiated. Defaults to NULL (i.e. all elements are differentiated element-wise). |
environment, the gradients of all ancestors of the node (including the target node itself) with respect to the target node.
All nodes required to compute the target node must have a value, or their value must be able to be computed at run-time. The values of the nodes can be obtained by first evaluating function cg_graph_run. The values obtained by this function for the nodes can then be supplied to argument values
.
In case the value of target node name
is a vector or an array, argument index
can be used to specify which element of the vector or array is differentiated.
The gradients of all ancestors of the node are returned. The gradients have the same shape as the values of the nodes.
Ron Triepels
# Initialize a computational graph x <- cg_graph() # Add some parameters a <- cg_parameter(2, name = "a") b <- cg_parameter(4, name = "b") # Perform some operations on the parameters c <- cg_sin(a) + cg_cos(b) - cg_tan(a) # Differentiate the graph with respect to c grads <- cg_graph_gradients(x, c, cg_graph_run(x, c)) # Retrieve the gradient of c with respect to a grads$a