# AutoDiff by Symboic Representation in Julia


```julia
using Symbolics
```


```julia
function forward_fn(w_vec, x, i::Int)
    y = w_vec[i](x)
    i == size(w_vec)[1] ? y : [y; forward_fn(w_vec,y,i+1)] 
end

function reverse_autodiff(w_vec, x_vec, i::Int)
    if i == 1
        1
    else
        dy = expand_derivatives(Differential(x)(w_vec[i](x)))
        dy_x = substitute(dy, (Dict(x=>x_vec[i-1],)))
        dy_x * reverse_autodiff(w_vec, x_vec, i-1)
    end
end

i(x) = x
f(x) = 3x^2
g(x) = 2x^2
h(x) = 1x^2

@variables x 
w_vec = [i, h, g, f]
x_vec = forward_fn(w_vec, x, 1)
y_sad = x_vec[end]
display(y_sad)
dy_sad = reverse_autodiff(w_vec, x_vec, size(w_vec)[1])
display(dy_sad)

# Check by theory
y_th = f(g(h(x)))
display(y_th)
dy_th = expand_derivatives(Differential(x)(y_th))
display(dy_th)
```


\begin{equation}
12 x^{8}
\end{equation}




\begin{equation}
96 x^{7}
\end{equation}




\begin{equation}
12 x^{8}
\end{equation}




\begin{equation}
96 x^{7}
\end{equation}




```julia

```

60b5e0f15b1aa2802540540b2a8d3c078dbe310e
ipynb
Jupyter Notebook
diffprog/julia_dp/repository/autodiff_chain_rule-symb-Copy2.ipynb
jskDr/keraspp_2021
dc46ebb4f4dea48612135136c9837da7c246534a
MIT
2021-09-21T15:35:04.000Z
2021-12-14T12:14:44.000Z
diffprog/julia_dp/repository/autodiff_chain_rule-symb-Copy2.ipynb
jskDr/keraspp_2021
dc46ebb4f4dea48612135136c9837da7c246534a
MIT
diffprog/julia_dp/repository/autodiff_chain_rule-symb-Copy2.ipynb
jskDr/keraspp_2021
dc46ebb4f4dea48612135136c9837da7c246534a
MIT
Qwen/Qwen-72B
1. YES
2. YES