# Backpropagation - Exercise: Computational Graphs

## Table of Contents

## Introduction

In this exercise, you will apply the backpropagation algorithm to computational graphs. Backpropagation is the method we use to calculate the gradients of all learnable parameters in an artificial neural network efficiently and conveniently. Approaching the algorithm from the perspective of computational graphs gives a good intuition about its operations.

## Requirements

### Knowledge

You should already be familiar with the backpropagation algorithm, as well as differential calculus. Following resources we recommend if this topic is new to you:

- Chapter 6.5 of Deep Learning by Ian Goodfellow gives a brief introduction into the field
- MOOC Calculus from Khan Academy

### Python and System Packages

To run that Notebook you should have the `graphviz`

package installed on your System. Look at the Graphviz-Website for installation guidance. Further, the Python module `Digraph`

is only working with Jupyter Notebook (not Lab) at the moment.

```
# External Modules
from graphviz import Digraph
import numpy as np
import hashlib
```

```
def round_and_hash(value, precision=4, dtype=np.float32):
"""
Function to round and hash a scalar or numpy array of scalars.
Used to compare results with true solutions without spoiling the solution.
"""
rounded = np.array([value], dtype=dtype).round(decimals=precision)
hashed = hashlib.md5(rounded).hexdigest()
return hashed
```

## Pen and Paper Backpropagation

Given the function $f(a,b,c)$ as a computational graph with the following values for the parameters:

```
a = 2 \\
b = e \; (Euler \;number, \;b \approx 2.7183) \\
c = 3
```

**Tasks:**

- Give an equation that expresses the graph.
- Calculate the partial derivative $\frac {\partial out} {\partial a}$, $\frac {\partial out} {\partial b}$. and $\frac {\partial out} {\partial c}$ using calculus on pen & paper
- For b use the the true $Euler \;number$ and not the approximation
- Assign your results to variables
`partial_a`

,`partial_b`

and`partial_c`

to verify your solution with the software test below

```
# creating empty graph ad set some attributes
f = Digraph('computat:onal_graph', filename='graph_clean.gv')
f.attr(rankdir='LR')
f.attr('node', shape='circle')
# create the graph
f.node('a')
f.node('b')
f.node('c')
f.edge('a', '+', label=' ')
f.edge('b', 'ln', label=' ')
f.edge('ln', '+', label=' ')
f.edge('+','* ', label=' ')
f.edge('c','* ')
f.edge('* ', '*')
f.edge('1/3 ', '*')
f.edge('*','1/x')
f.edge('1/x','out')
f
```

```
partial_a = 42 ### assign what u have calculated
partial_b = 42 ### assign what u have calculated
partial_c = 42 ### assign what u have calculated
```

## Implement the Example

**Task:**

In the pen and paper exercise, you calculated the partial derivatives for some specific values of $a$, $b$, and $c$ of the graph $f(a,b,c)$. Your task now is to generalize that solution. Implement the used functions $+$, $*$ and $1/x$ and their derivatives. Chain the functions to calculate $f(a,b,c)$ in a forward pass and $\frac {\partial out} {\partial a}$, $\frac {\partial out} {\partial b}$, $\frac {\partial out} {\partial c}$ in the backward pass for arbitrary values of $a$, $b$, and $c$.

**Hint:**

Complete function:

So...

Remember chain rule:

```
### Your implementation here
# 1/x is the same like "x to the power of minus one"
def pow_minus_one(x, derivative=False):
if derivative:
raise NotImplementedError()
else:
raise NotImplementedError()
def addition(x,y, derivative=False):
if derivative:
raise NotImplementedError()
else:
raise NotImplementedError()
def multi(x,y, derivative=False):
if derivative:
raise NotImplementedError()
else:
raise NotImplementedError()
```

```
a = 2
b = np.e
c = 3
### complete the forward pass:
# forward = pow_minus_one(multi(...
### complete the backwards pass for "a"
#part_a = (pow_minus_one(multi(multi(addition(a,np.log(b)),c),1/3), derivative=True)
# * multi(multi(addition(a,np.log(b)),c),1/3, derivative=True)
# * ...
### complete the backwards pass for "b"
#part_b = ...
### complete the backwards pass for "c"
#part_c = ...
### print for self control
#print(part_a)
#print(part_b)
#print(part_b)
```

```
assert round_and_hash(forward) == '8565183eaf4b5c6356d6abb81b8e139d'
assert round_and_hash(part_a) == '2fb0a82d3fe965c8a0d9ce85970058d8'
assert round_and_hash(part_b) == 'b6bfa6042c097c90ab76a61300d2429a'
assert round_and_hash(part_c) == '2fb0a82d3fe965c8a0d9ce85970058d8'
```

## Summary and Outlook

This exercise covered basic operations on vectors and matrices. If the exercise was too complicated, consider the sources mentioned above for a recap.

## Licenses

### Notebook License (CC-BY-SA 4.0)

*The following license applies to the complete notebook, including code cells. It does however not apply to any referenced external media (e.g., images).*

Exercise: Computational Graphs

by Benjamin Voigt

is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

Based on a work at https://gitlab.com/deep.TEACHING.

### Code License (MIT)

*The following license only applies to code cells of the notebook.*

Copyright 2018 Benjamin Voigt

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.