# AutoDiff by Symboic Representation in Julia


```julia
using Symbolics
```


```julia
i(x) = x
f(x) = 3x^2
g(x) = 2x^2
h(x) = x^2
w_vec = [i, h, g, f]

@variables x 
```




\begin{equation}
\left[
\begin{array}{c}
x \\
\end{array}
\right]
\end{equation}





```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
```




    forward_fn (generic function with 1 method)




```julia
x_vec = forward_fn(w_vec, x, 1)
display(x_vec)
```


\begin{equation}
\left[
\begin{array}{c}
x \\
x^{2} \\
2 x^{4} \\
12 x^{8} \\
\end{array}
\right]
\end{equation}




```julia
function gradient(w_i, x_i_1, x)
    dy = expand_derivatives(Differential(x)(w_i(x)))
    substitute(dy, (Dict(x=>x_i_1,)))
end

function reverse_autodiff(w_vec, x_vec, x, i::Int)
    if i == 1
        1
    else
        gradient(w_vec[i],x_vec[i-1],x) * 
            reverse_autodiff(w_vec, x_vec, x, i-1)
    end
end
```




    reverse_autodiff (generic function with 1 method)




```julia
y_sad = x_vec[end]
display(y_sad)
dy_sad = reverse_autodiff(w_vec, x_vec, x, size(w_vec)[1])
display(dy_sad)
```


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




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



## Check by theory


```julia
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}




```julia

```

80f411540c753c93f2d298e312435d19f0fc63e5
ipynb
Jupyter Notebook
diffprog/julia_dp/repository/autodiff_chain_rule-symb-Copy3.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-Copy3.ipynb
jskDr/keraspp_2021
dc46ebb4f4dea48612135136c9837da7c246534a
MIT
diffprog/julia_dp/repository/autodiff_chain_rule-symb-Copy3.ipynb
jskDr/keraspp_2021
dc46ebb4f4dea48612135136c9837da7c246534a
MIT
Qwen/Qwen-72B
1. YES
2. YES