In R, both symbolic differentiation vs computational graph are implemented.
Suppose we want to calculate the gradient of function f(x, y)=sin(x + y2). First, let’s look at symbolic differentiation:
library(Deriv)
f <- function(x, y) sin(x + y^2)
x <- c(1, 1)
gradient <- Deriv(f)
f <- function(x, y) sin(x + y^2)
x <- c(1, 1)
gradient <- Deriv(f)
cat(gradient(x[1], x[2]), '\n')
# output
# -0.4161468 -0.8322937
Next is the code for computational graph:
library(cgraph)
graph <- cg_graph()
x <- cg_input(name = "x")
y <- cg_input(name = "y")
f <- cg_sin(cg_add(x, cg_pow(y, 2)))
x$value <- 1
y$value <- 1
cg_graph_forward(graph, f)
cg_graph_backward(graph, f)
cat(x$grad, y$grad, '\n')
# output
-0.4161468 -0.8322937
We can see that the results are the same.