The forward propagation process of neural networks can be very concisely written using a series of
Matrix-Vector multiplications.
The same can be said about the back propagation process. In this article
I will show step by step how derivatives propagate through Matrix-Vector multiplications and how to use
these results in
a neural network.
Forward Propagation
Lets consider a portion of a neural network: two layers and the weights between, and an activation
function f.
Let the first layer have n neurons and the second one m neurons. Since these two layers are
nothing more than arrays of numbers, they can be represented
using vectors:
first layer:second layer:v1∈Rnv2∈Rm
Let Wi,j be the weight connecting the ith neuron of the second layer and the
jth neuron of the first layer. This way, the forward propagation for each of the individual neurons
can be written as:
vi2=f(∑k=1nWi,kvk1)
Or more compactly:
v2=f(Wv1)
To simplify things, lets split the above step into two:
s2=Wv1v2=f(s2)
So far we have:
v1∈Rns2∈Rmv2∈RmW∈Rm×ns2=Wv1v2=f(s2)
Back Propagation
Let the derivative of the second layer with respect to the loss function be given:
∂v2∂L
So the partial derivative of the loss with respect to the ith neuron in the second layer will be
the ith element of the above vector:
∂vi2∂L=(∂v2∂L)i
Going a step back, let’s write how the ith element of s2 is propagation:
vi2=f(si2)
Then by taking the derivative:
∂si2∂vi2=f′(si2)
We can write the following vector:
∂s2∂v2=f′(s2)
And apply the chain rule:
∂si2∂L=∂vi2∂L∂si2∂vi2=∂vi2∂Lf′(s2)
And in vector form:
∂s2∂L=∂v2∂L∘f′(s2)
(where ∘ represents element wise multiplication).
Next, the propagation towards v1 will be more complicated, because unlike there is no longer a one
to one relation
between elements in v1 and s2. Each element of v1 depends on each element of s2 in
the following way:
si2=∑∗k=1nW∗i,kvk1
So by taking the derivative of the ith element of s2 with respect to the jth element of
v1 we get:
∂vj1∂si2=Wi,j
This means that when we apply the chain rule to get ∂L/∂vi1, we need to consider
how every element
of s2 will impact the total derivative:
So the ith element of ∂L/∂vi1 equals to the dot product of the ith row
of matrix WT with the vector ∂L/∂sj2. This is exactly what matrix
multiplication does, so we can write:
∂v1∂L=WT∂s2∂L
Finally, we need to calculate the derivatives with respect to each of the weights in the matrix W.
Using the above forward propagation formula:
si2=∑k=1nWi,kvk1
We can find the partial derivative:
∂W∗i,j∂s2∗i=vj1
Notice that the index of the element of s2 has to match the index of the row of W. Since only
the ith row has an effect on that element.
And now by applying the chain rule:
∂Wi,j∂L=∂si2∂L∂Wi,j∂si2=∂si2∂Lvj1
It is a bit hard to see at first, but we can rewrite this expression as a multiplication of a column
vector by a row vector:
∂W∂L=∂s2∂L(v1)T
Here is a small example of how that multiplication would work: