# Deep Learning From Scratch - Theory and Implementation

DanielSabinasz
159.2K views

Generally, if we want to find the minimum of a function, we set the derivative to zero and solve for the parameters. It turns out, however, that it is impossible to obtain a closed-form solution for and . Instead, we iteratively search for a minimum using a method called gradient descent.

As a visual analogy, imagine yourself standing on a mountain and trying to find the way down. At every step, you walk into the steepest direction, since this direction is the most promising to lead you towards the bottom.

If taking steep steps seems a little dangerous to you, imagine that you are a mountain goat (which are amazing rock climbers).

Gradient descent operates in a similar way when trying to find the minimum of a function: It starts at a random location in parameter space and then iteratively reduces the error until it reaches a local minimum. At each step of the iteration, it determines the direction of steepest descent and takes a step along that direction. This process is depicted for the 1-dimensional case in the following image.

As you might remember, the direction of steepest ascent of a function at a certain point is given by the gradient at that point. Therefore, the direction of steepest descent is given by the negative of the gradient. So now we have a rough idea how to minimize :

2. Compute the gradients of with respect to and
3. Take a small step along the direction of the negative gradient
4. Go back to 2

Let's implement an operation that minimizes the value of a node using gradient descent. We require the user to specify the magnitude of the step along the gradient as a parameter called learning_rate.

from queue import Queue
def __init__(self, learning_rate):
self.learning_rate = learning_rate
def minimize(self, loss):
learning_rate = self.learning_rate
class MinimizationOperation(Operation):
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

The following image depicts an example iteration of gradient descent. We start out with a random separating line (marked as 1), take a step, arrive at a slightly better line (marked as 2), take another step, and another step, and so on until we arrive at a good separating line.

## Backpropagation

In our implementation of gradient descent, we have used a function compute_gradient(loss) that computes the gradient of a operation in our computational graph with respect to the output of every other node (i.e. the direction of change for along which the loss increases the most). We now need to figure out how to compute gradients.

Consider the following computational graph:

By the chain rule, we have

As we can see, in order to compute the gradient of with respect to , we can start at an go backwards towards , computing the gradient of every node's output with respect to its input along the way until we reach . Then, we multiply them all together.

Now consider the following scenario:

In this case, contributes to along two paths: The path , , , and the path , , , . Hence, the total derivative of with respect to is given by:

This gives us an intuition for the general algorithm that computes the gradient of the loss with respect to another node: We perform a backwards breadth-first search starting from the loss node. At each node that we visit, we compute the gradient of the loss with respect do 's output by doing the following for each of 's consumers :

• retrieve the gradient of the loss with respect to the output of
• multiply by the gradient of 's output with respect to 's output

And then we sum those gradients over all consumers.

As a prerequisite to implementing backpropagation, we need to specify a function for each operation that computes the gradients with respect to the inputs of that operation, given the gradients with respect to the output. Let's define a decorator @RegisterGradient(operation_name) for this purpose:

# A dictionary that will map operations to gradient functions
"""A decorator for registering the gradient function for an op type.
"""
def __init__(self, op_type):
"""Creates a new decorator with op_type as the Operation type.
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Now assume that our _gradient_registry dictionary is already filled with gradient computation functions for all of our operations. We can now implement backpropagation:

Backpropagation
from queue import Queue
# grad_table[node] will contain the gradient of the loss w.r.t. the node's output
# The gradient of the loss with respect to the loss is just 1
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

For each of our operations, we now need to define a function that turns a gradient of the loss with respect to the operation's output into a list of gradients of the loss with respect to each of the operation's inputs. Computing a gradient with respect to a matrix can be somewhat tedious. Therefore, the details have been omitted and I just present the results. You may skip this section and still understand the overall picture. The implementations for add, reduce_sum and softmax are a little more involved, and I'd recommend not spending too much time trying to understand them.

If you want to comprehend how to arrive at the results, the general approach is as follows:

• Find the partial derivative of each output value with respect to each input value. This can be a tensor of a rank greater than 2, i.e. neither scalar nor vector nor matrix, involving a lot of summations.
• Compute the gradient of the loss with respect to the node's inputs given a gradient with respect to the node's output by applying the chain rule. This is now a tensor of the same shape as the input tensor, so if the input is a matrix, the result is also a matrix
• Rewrite this result as a sequence of matrix operations in order to compute it efficiently. This step can be somewhat tricky.

#### Gradient for negative

Given a gradient with respect to , the gradient with respect to is given by .

"""Computes the gradients for negative.
Args:
op: The negative Operation that we are differentiating
grad: Gradient with respect to the output of the negative op.
Returns:
Gradients with respect to the input of negative.
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

#### Gradient for log

Given a gradient with respect to , the gradient with respect to is given by .

"""Computes the gradients for log.
Args:
op: The log Operation that we are differentiating
grad: Gradient with respect to the output of the log op.
Returns:
Gradients with respect to the input of log.
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

#### Gradient for sigmoid

Given a gradient with respect to , the gradient with respect to is given by .

"""Computes the gradients for sigmoid.
Args:
op: The sigmoid Operation that we are differentiating
grad: Gradient with respect to the output of the sigmoid op.
Returns:
Gradients with respect to the input of sigmoid.
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

#### Gradient for multiply

Given a gradient with respect to , the gradient with respect to is given by and the gradient with respect to is given by .

"""Computes the gradients for multiply.
Args:
op: The multiply Operation that we are differentiating
grad: Gradient with respect to the output of the multiply op.
Returns:
Gradients with respect to the input of multiply.
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

#### Gradient for matmul

Given a gradient with respect to , the gradient with respect to is given by and the gradient with respect to is given by .

"""Computes the gradients for matmul.
Args:
op: The matmul Operation that we are differentiating
grad: Gradient with respect to the output of the matmul op.
Returns:
Gradients with respect to the input of matmul.
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

#### Gradient for add

Given a gradient with respect to , the gradient with respect to is given by and the gradient with respect to is also given by , provided that and are of the same shape. If and are of different shapes, e.g. one matrix with 100 rows and one row vector , we assume that is added to each row of . In this case, the gradient computation is a little more involved, but I will not spell out the details here.

"""Computes the gradients for add.
Args:
op: The add Operation that we are differentiating
grad: Gradient with respect to the output of the add op.
Returns:
Gradients with respect to the input of add.
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

#### Gradient for reduce_sum

Given a gradient with respect to the output of reduce_sum, the gradient with respect to the input is given by repeating along the specified axis.

"""Computes the gradients for reduce_sum.
Args:
op: The reduce_sum Operation that we are differentiating
grad: Gradient with respect to the output of the reduce_sum op.
Returns:
Gradients with respect to the input of reduce_sum.
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

#### Gradient for softmax

"""Computes the gradients for softmax.
Args:
op: The softmax Operation that we are differentiating
grad: Gradient with respect to the output of the softmax op.
Returns:
Gradients with respect to the input of softmax.
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

### Example

Let's now test our implementation to determine the optimal weights for our perceptron.

Example: Training the perceptron
# Create a new graph
Graph().as_default()
X = placeholder()
c = placeholder()
# Initialize weights randomly
W = Variable(np.random.randn(2, 2))
b = Variable(np.random.randn(2))
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Notice that we started out with a rather high loss and incrementally reduced it. Let's plot the final line to check that it is a good separator:

Example: Plot result
W_value = np.array([[ 1.27496197 -1.77251219], [ 1.11820232 -2.01586474]])
b_value = np.array([-0.45274057 -0.39071841])
# Plot a line y = -x
x_axis = np.linspace(-4, 4, 100)
y_axis = -W_value[0][0]/W_value[1][0] * x_axis - b_value[0]/W_value[1][0]
plt.plot(x_axis, y_axis)
# Add the red and blue points
plt.scatter(red_points[:,0], red_points[:,1], color='red')
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX