L = the number of layers in the network (the input layer is not counted).
nl = the number of nodes (neurons) in the lth layer. The input layer is called layer 0, so n0 is the number of input values (features).
Z[l] = a vector of the weighted sums of all the nodes in the lth layer (before applying the activation function).
Zj[l] = a scalar that represents the weighted sum of the jth node in the lth layer.
A[l] = a vector of the outputs (activations) of all the nodes in the lth layer.
Aj[l] = a scalar that represents the output of the jth node in the lth layer.
W[l] = a matrix of the weights that connect the layer (l−1) to the layer l.
Wjk[l] = a scalar that represents the weight that connects the kth node of the layer (l−1) to the jth node of the layer l.
b[l] = a vector of the biases of the lth layer and bj[l] is the bias of its jth node.
x(i) = a vector of features of the ith example and y(i) is the vector of its target values.
y^(i) = a vector of the predicted values of the ith example, i.e., the outputs of the last layer A[L].
m = the number of examples in the dataset.
Note: the square brackets [l] always refer to a layer, the parentheses (i) always refer to an example, and the curly braces {t} always refer to a minibatch (Section(4)). When we work with a single example, we will drop the superscript (i) and simply write x, y, and y^.
Note: for the subscripts, we will always use j for a node of the current layer l, k for a node of the previous layer (l−1), and p for a node of the next layer (l+1).
Note: the numbers under braces show the dimensions of matrices, i.e., rows × columns.
Each layer l takes the outputs of the previous layer A[l−1] as its input. It multiplies them by its weights, adds its biases, and then passes the result to an activation function σ (we will define it in Section(2.1)). The equation of a single layer is:
i.e., the node j computes a weighted sum of all the outputs of the previous layer, exactly like the equation of a line in linear regression [1], and then applies the activation function to it. We will explain these equations in detail in Section(2.4).
The weights matrix W[l] that is used in equation(1) is:
In equation(2), the weight Wjk[l] multiplies the output Ak[l−1] of the kth node of the layer (l−1) and the result is added to Zj[l] of the jth node of the layer l. Hence, the first index j of Wjk[l] is the row number and it tells us where the weight goes to (the jth node of the layer l). The second index k is the column number and it tells us where the weight comes from (the kth node of the layer (l−1)). This is the reason why the matrix W[l] has nl rows and nl−1 columns. For example, W21[3] is the weight that connects the 1st node of the layer 2 to the 2nd node of the layer 3.
All the vectors in this paper are column-vectors. For example, the outputs of the layer (l−1) are:
Throughout this paper, we will use the network shown in Figure(1) as a running example. It has 3 input values, two hidden layers with 5 and 4 nodes, respectively, and an output layer with 3 nodes, i.e., L=3, n0=3, n1=5, n2=4, and n3=3. Each output node j has its own error Ej that we will define in Section(2.5).
Figure 1: the running example network. The bold path connects the 1st node of every layer to the error E1 of the 1st output node.
2 Background
2.1 The Sigmoid Function and Its Derivative
Every node in our network computes a weighted sum Z of its inputs and then passes it to an activation function. We will use the sigmoid function which is defined as:
σ(z)=1+e−z1(3)
The backpropagation algorithm needs the derivative of the activation function. We can write the sigmoid function as σ(z)=(1+e−z)−1 and by applying the chain rule, we will get:
σ′(z)=dzdσ(z)=−1⋅(1+e−z)−2⋅(−e−z)=(1+e−z)2e−z
and by splitting the fraction into the product of two fractions
σ′(z)=1+e−z1⋅1+e−ze−z
The first fraction is σ(z) itself. For the second fraction, we can add and subtract 1 in the numerator:
The Hadamard product, denoted with the symbol ⊙, is the element-wise product of two matrices (or vectors) that have the same dimensions. Each element of the result is the product of the two elements in the same position. For example,
Note: unlike the matrix product ·, the Hadamard product does not change the dimensions.
2.3 The Outer Product
If we multiply a column-vector u by the transpose of another column-vector v, we will get a matrix. This product is called the outer product. For example, if we have the vectors
Equation(6) is very similar to the equation of a line that we used in linear regression. The difference is that each layer has many nodes and each node has its own weights. If we put all the weighted sums of the first layer of our network together, we can write them in the matrix form as follows:
The outputs of the last layer are the predicted values of the network. Therefore, we will write them as y^:
3×1y^=3×1A[3],y^j=Aj[3]
To measure how close the prediction y^j of the jth output node is to its target value yj, we will use the squared residual error that we used in linear regression. The error of the jth output node is:
Ej=Loss(yj,y^j)=21⋅(yj−y^j)2(9)
Note: the 21 is added only to cancel the 2 that comes from the derivative of the square. It does not change the location of the minimum.
The total error of the network for a single example is the sum of the errors of all output nodes:
which is the same eT⋅e form of the residual sum of squares that we derived in linear regression, where e=y−y^ is the vector of residual errors. Finally, if we have m examples, the cost function J is the average of the errors of all examples, where E(i) is the total error E of the ith example:
Our Goal: we want to find the weights W[1], W[2], W[3] and the biases b[1], b[2], b[3] such that the cost J is as small as possible.
In linear regression [1], we found the best weights directly with the normal equation (closed-form solution). We could do that because the prediction was a linear function of the weights:
m×1y^=m×(n+1)X⋅(n+1)×1w
Note: here X,y, and n have their meanings from the linear regression paper [1]: X has the examples as rows, y holds the targets of all m examples, and n is the number of features. In this paper, X will have the examples as columns (Section(3.5)), y is the target vector of a single example, and the number of features is n0.
Hence, the RSS was a quadratic function of w and its gradient was a linear function of w. When we set the gradient to zero, we got a system of linear equations that we solved with the inverse matrix:
∇wRSS=2⋅XT⋅X⋅w−2⋅XT⋅y=0⟹w=(XT⋅X)−1⋅XT⋅y
In our network, if we substitute each layer of the forward propagation equation(8) into the next one, the prediction becomes:
We can see clearly that y^ is not a linear function of the weights. The weights are inside sigmoid functions, i.e., inside exponentials e−z, and these sigmoid functions are nested inside each other. This causes two problems:
If we set the gradient to zero, we will get a system of nonlinear equations. For example, we will see in Section(3) that one of these equations is:
where Z1[3] and A1[2] depend on all the weights of the previous layers. Unlike XT⋅X⋅w=XT⋅y, we cannot move the weights to one side and take an inverse matrix, since the weights cannot be separated from the exponentials. There is no algebraic formula that solves these equations.
Even if we could solve them, the solution would not be unique. The cost J of linear regression is shaped like a bowl, so it has only one point where the gradient is zero, which is the minimum. The cost J of a neural network is not shaped like a bowl. It has many points where the gradient is zero: many local minima and saddle points. For example, if we swap two nodes of a hidden layer together with their weights, the network will give exactly the same outputs and the same cost, so every minimum has many copies.
Therefore, we will use gradient descent instead. Gradient descent does not need to solve ∇J=0. As we saw in linear regression, it only needs to evaluate the gradient at the current weights and then take a small step in the opposite direction. This means that we need the partial derivative of the error with respect to every single weight and bias in the network. The backpropagation algorithm is an efficient way to compute all these partial derivatives.
3 Mathematical Derivation
We will first derive the partial derivatives for a single example and then we will extend them to m examples. We will start from the output layer and move backward towards the input layer, hence the name backpropagation.
Note: to keep track of the dimensions of the matrices, we will show the dimensions under each term.
3.1 The Output Layer (Layer 3)
Let's start with the weight W11[3] which is the last weight on the bold path in Figure(1). This weight affects the error E1 through the following chain:
W11[3]⟶Z1[3]⟶y^1⟶E1
The weight W11[3] appears only in Z1[3]. It does not appear in Z2[3] or Z3[3], so it does not affect E2 or E3. Hence, ∂W11[3]∂E=∂W11[3]∂E1 and by applying the chain rule, we will get:
The first two terms of equation(13) depend only on the output node and not on the weight. We will give their product a special name, δ1[3], and we will call it the error of the 1st node of the layer 3:
Similarly, let's put all the partial derivatives of the weights of the layer 3 in a matrix that has the same dimensions as W[3]. By using equation(19) for every element, we will get:
For the biases, we can see from equation(6) that ∂bj[3]∂Zj[3]=1. If we replace the third term of the chain rule in equation(13) with this value, we will get ∂bj[3]∂E=δj[3]⋅1=δj[3], i.e.,
3×1∂b[3]∂E=3×1δ[3](22)
3.2 The Second Hidden Layer (Layer 2)
Now, let's move one step backward to the weight W11[2] in Figure(1). If we follow the bold path, this weight affects the error E1 through the following chain:
The third term is the derivative of Z1[3] with respect to A1[2] (not with respect to the weight as before). In the sum Z1[3]=∑k=14W1k[3]Ak[2]+b1[3], only the term W11[3]A1[2] contains A1[2], hence,
But, this is not the complete derivative of the total error E. In the output layer, the weight W11[3] affected only E1. Here, the weight W11[2] changes A1[2],
Figure 2: the three paths from the weight W11[2] to the errors E1,E2, and E3.
and A1[2] is an input to every node of the layer 3 as shown in Figure(2). Hence, W11[2] affects E1, E2, and E3 through three different paths.
Since the total error is E=E1+E2+E3 and the derivative of a sum is the sum of the derivatives:
The path to E2 goes through the 2nd output node instead of the 1st one, so we can repeat the derivation of equation(27) by replacing every index 1 of the layer 3 with 2. The derivative ∂A1[2]∂Z2[3] is the weight that connects A1[2] to the 2nd output node, i.e., W21[3]. The same applies to E3:
Note: if the network had only one output node, the sum would have only one term and δ1[2] would be δ1[3]⋅∂A1[2]∂Z1[3]⋅∂Z1[2]∂A1[2], i.e., the terms of the single path in equation(23). With many output nodes, we add up the errors of all output nodes, each one weighted by the weight that connects it to A1[2]. Again, δ1[2]=∂Z1[2]∂E.
We can see clearly that equation(30) has exactly the same form as equation(18) of the output layer. The only difference is how the error δ is computed. For any weight Wjk[2] of the layer 2, we will get:
The first vector is a matrix multiplication. Notice that the jth row uses the jth column of W[3], which means that it is the jth row of the transposed matrix W[3]T:
We can see the pattern: each time we move one layer backward, we multiply the error of the next layer by a weight and an activation's derivative. As we saw in the layer 2, the braces above are the single-path versions of the errors. To get the complete derivative, we have to add up all the paths.
The output A1[1] goes to all the 4 nodes of the layer 2, and each of them goes to all the 3 output nodes, so there are 4×3=12 paths from W11[1] to the error E. Fortunately, we do not need to follow all of them. Recall that δp[2]=∂Zp[2]∂E already contains the sum over all the paths from Zp[2] to the error.
Therefore, we only need to add up the 4 paths that go from A1[1] to the layer 2:
This is the main idea of backpropagation: the errors δ of a layer are computed once and then they are reused to compute the errors of the previous layer. The errors are propagated backward one layer at a time.
By following the same steps that we used to get equation(32) and equation(33), we will get:
If we compare the results of the three layers, we can write the general equations of backpropagation for any network with L layers. The error of the last layer comes from equation(20), where y^=A[L] is the output of the last layer:
Note: equation(39) uses the transposed weights matrix of the next layer. In the forward propagation, W[l+1] carries the outputs forward from the layer l to the layer (l+1). In the backward propagation, W[l+1]T carries the errors backward from the layer (l+1) to the layer l through the same connections.
Note: if we write the errors as row-vectors instead of column-vectors, i.e., δ[l]T, then by taking the transpose of both sides of equation(39), it becomes δ[l]T=(δ[l+1]T⋅W[l+1])⊙σ′(Z[l])T. Both forms are the same equation.
3.5 Backpropagation over m Examples
So far, we have derived the partial derivatives of the error E of a single example. However, the cost function J in equation(11) is the average over m examples. Since the derivative of a sum is the sum of the derivatives:
where δ[l](i) and A[l−1](i) are the error and the input of the layer l when the ith example is fed to the network. Instead of running the network m times with a loop, we can process all the examples at once by stacking them as columns next to each other. We will use the bold letters A[l] and Z[l] for the stacked versions of A[l] and Z[l], the bold capital letter Δ[l] for the stacked version of δ[l], and the capital letters X, Y, and Y^ for the stacked versions of x, y, and y^:
and Z[l] is stacked in the same way as A[l]. The ith column of each matrix belongs to the ith example.
For the forward propagation, if we multiply W[l] by A[l−1], each column of A[l−1] is multiplied by W[l] separately. The bias vector must be added to every column, so we multiply it by a row-vector of ones 1T, where 1 is an m×1 vector of ones:
Note: the product b[l]⋅1T copies the bias vector m times, once for every example. This is exactly what is called broadcasting in NumPy and PyTorch. In code, we simply write Z=W⋅dot(Aprev)+b, where b has the shape (nl,1), and the library adds b to every column of W⋅dot(Aprev) without building the
nl×m matrix in memory. The bias must be stored as a column-vector of shape (nl,1). If it is stored as a 1-D array of shape (nl,), NumPy matches it with the last dimension of the matrix, which is the number of examples m, not the number of nodes nl.
The backward pass does the opposite of broadcasting. Since the forward pass copies b[l] into all the m columns, the gradient of b[l] adds up the m columns of the errors. We will see this in equation(45), where Δ[l]⋅1 is the same as delta.sum(axis=1, keepdims=True) in NumPy.
The equations(38) and (39) work on each column separately too, since the matrix product and the Hadamard product do not mix the columns. Hence,
For the weights, the sum of outer products in equation(42) is exactly a matrix multiplication. If we multiply Δ[l] by A[l−1]T, each column of the first matrix is multiplied by the corresponding row of the second one and the results are added up:
By plugging this result into equation(42), and by following the same steps for the biases (adding up the columns of Δ[l] is the same as multiplying it by 1), we will get:
Gradient descent updates the weights with the following update rule: wnew=wold−α⋅∇wRSS, where α is the learning rate. We showed how to derive this rule using the Taylor series in the linear regression paper [1], and the reader can refer to it for more details. The same rule is applied here to every weight and every bias. For a single example, the update of the first column of W[1] is shown below, where the arrow ← means that the old value is replaced by the new one:
Note: all the errors Δ[l] must be computed with the old weights. In Algorithm(1), we compute all the gradients first and update the weights only after the backward pass is finished. In the algorithm, we write ∇W[l] and ∇b[l] for the gradients ∂W[l]∂J and ∂b[l]∂J.
Note: one pass over all the m examples of the dataset is called an epoch. In Algorithm(1), every epoch computes the gradients of all the examples and then updates the weights only one time. The number of epochs T is the number of times we repeat this.
Algorithm 1 Batch Gradient Descent with Backpropagation
1: W[l] = a randomly initialized matrix of size nl×nl−1, for l=1,…,L
2: b[l] = a vector of zeros of size nl×1, for l=1,…,L
3: α = the learning rate
4: T = the number of epochs
5: for e=1 to T do
6: // forward propagation
7: A[0]=X
8: for l=1 to L do
9: Z[l]=W[l]⋅A[l−1]+b[l]⋅1T
10: A[l]=σ(Z[l])
11: end for
12: Y^=A[L]
13: // backward propagation
14: Δ[L]=−(Y−Y^)⊙σ′(Z[L])
15: for l=L down to 1 do
16: ∇W[l]=m1⋅Δ[l]⋅A[l−1]T
17: ∇b[l]=m1⋅Δ[l]⋅1
18: if l>1 then
19: Δ[l−1]=(W[l]T⋅Δ[l])⊙σ′(Z[l−1])
20: end if
21: end for
22: // update
23: for l=1 to L do
24: W[l]←W[l]−α⋅∇W[l]
25: b[l]←b[l]−α⋅∇b[l]
26: end for
27: end for
4 Mini-Batch Gradient Descent
In Algorithm(1), every update of the weights uses all the m examples of the dataset. We compute the errors Δ[l] of all the examples, and only then we take a single step. This is called batch gradient descent. Since one epoch is one pass over all the examples, as we noted before Algorithm(1), batch gradient descent makes only one update per epoch. When the number of examples m is large, this causes two problems:
Every single step needs a forward pass and a backward pass over the whole dataset, so the training is slow.
The matrices Z[l], A[l], and Δ[l] have m columns, and all of them must be stored in memory at the same time. For example, the dataset that we will use in Section(5) has m=60,000 examples.
The other extreme is to update the weights after every single example. This is called stochastic gradient descent (SGD). Each update is very cheap, but it also causes two problems. First, the gradient of a single example is noisy: it shows how to reduce the error of that example only, which may increase the errors of the other examples. Second, we lose the speed of the matrix multiplications, since we process one column at a time instead of many columns at once.
Mini-batch gradient descent is the middle ground between the two. We split the dataset into small groups of examples called mini-batches, and we update the weights after every mini-batch.
4.1 Splitting The Dataset into Mini-Batches
Let B be the mini-batch size, i.e., the number of examples in each mini-batch. Before splitting, we shuffle the columns of X and Y randomly, using the same random order for both matrices so that every example stays with its target values. Shuffling makes every mini-batch a random sample of the dataset. Without it, if the dataset is sorted by the labels (e.g., all the images of the digit 0 first), a mini-batch would contain the examples of a single class only, and its gradient would push the network towards that class.
After shuffling, we split the columns of X and Y into N mini-batches:
where X{t} and Y{t} are the features and the target values of the tth mini-batch, and mt is its number of examples. The number of mini-batches is:
N=⌈Bm⌉
(47) where ⌈⌉ rounds up to the nearest integer. All the mini-batches have mt=B examples, except the last one which has the remaining mN=m−(N−1)⋅B examples if m is not divisible by B. For example, if m=10 and B=4, then N=⌈10/4⌉=3 and the three mini-batches are:
i.e., m1=m2=4 and m3=10−2⋅4=2 (here the examples are numbered after shuffling).
4.2 The Cost and The Gradients of a Mini-Batch
The cost of the tth mini-batch is the average of the errors of its examples:
J{t}=mt1i∈{t}∑E(i)(48)
where i∈{t} means all the examples i that belong to the tth mini-batch. A mini-batch is simply a smaller dataset. Therefore, all the equations of Section(3.5) still hold if we replace X by X{t}, Y by Y{t}, and m by mt. The forward propagation in equation(43) becomes:
Note: the weights W[l] and the biases b[l] do not have the superscript {t}, since all the mini-batches use the same weights and biases. Only the data and the values computed from the data change from one mini-batch to another. Also, the dimensions of the gradients are still nl×nl−1 and nl×1, i.e., they do not depend on the mini-batch size mt.
4.3 Why Does It Work?
The mini-batches do not overlap, and together they contain all the m examples. Hence, we can split the sum in the cost function of equation(11) into one sum for every mini-batch:
J=m1i=1∑mE(i)=m1t=1∑Ni∈{t}∑E(i)
and from equation(48), we know that ∑i∈{t}E(i)=mt⋅J{t}, so:
J=t=1∑Nmmt⋅J{t}(52)
i.e., the cost of the whole dataset is a weighted average of the costs of the mini-batches, where each mini-batch is weighted by its size. Since the derivative of a sum is the sum of the derivatives, the same is true for the gradients:
∂W[l]∂J=t=1∑Nmmt⋅∂W[l]∂J{t}
Therefore, the gradient of a single mini-batch is an estimate of the gradient of the whole dataset. Since the mini-batches are random samples, the gradient of a mini-batch is equal to the full gradient on average. The larger the mini-batch size B is, the better the estimate is, but the more computation each update needs.
Note: equation(52) is exact only if all the mini-batches are evaluated with the same weights. In mini-batch gradient descent, the weights change after every mini-batch, so each J{t} is evaluated with different weights. This is another reason why the update of each mini-batch is only an estimate of the update of batch gradient descent.
The mini-batch size B controls which algorithm we get:
Mini-batch size
Updates per epoch
Algorithm
B=m
N=1
Batch gradient descent(Algorithm(1))
1<B<m
N=⌈m/B⌉
Mini-batch gradient descent(Algorithm(2))
B=1
N=m
Stochastic gradient descent (SGD)
Common values of B are 32, 64, 128, and 256. The code in Section(5) uses B=128.
4.4 The Mini-Batch Gradient Descent Algorithm
Algorithm(2) shows the full mini-batch gradient descent. The lines inside the inner loop over the mini-batches are the same lines of Algorithm(1), applied to X{t} and Y{t} instead of X and Y.
4.5 Changes Compared to Batch Gradient Descent
If we compare Algorithm(2) with Algorithm(1), we can see that the equations of the forward propagation, the backward propagation, and the update rule are exactly the same. Only the following things change:
A new parameter: the mini-batch size B in line 4 of Algorithm(2).
Shuffling and splitting (new lines 7–9): at the beginning of every epoch, we shuffle the columns of X and Y and split them into N mini-batches as in equation(47). Algorithm(1) does not need these lines.
A new inner loop (lines 10–33): the whole body of the epoch loop of Algorithm(1), i.e., lines 6–26, is moved inside a loop over the N mini-batches.
The data of a mini-batch: line 13 uses X{t} instead of X in line 7 of Algorithm(1), and line 20 uses Y{t} instead of Y in line 14. Hence, all the matrices Z[l]{t}, A[l]{t}, and Δ[l]{t} have mt columns instead of m columns.
The average over a mini-batch: lines 22 and 23 divide by the size of the mini-batch mt (computed in line 11) instead of dividing by m in lines 16 and 17. We use mt instead of B because the last mini-batch may be smaller than B.
The number of updates: the update (lines 28–32) is inside the loop over the mini-batches, so the weights are updated N times in every epoch instead of only one time.
Note: if we set B=m in Algorithm(2), we will get N=1 and m1=m, i.e., a single mini-batch that contains the whole dataset. In this case, Algorithm(2) is exactly the same as Algorithm(1), except for the shuffling, which has no effect since the sum over all the examples does not depend on their order.
Algorithm 2 Mini-Batch Gradient Descent with Backpropagation
1: W[l] = a randomly initialized matrix of size nl×nl−1, for l=1,…,L
2: b[l] = a vector of zeros of size nl×1, for l=1,…,L
3: α = the learning rate
4: B = the mini-batch size
5: T = the number of epochs
6: for e=1 to T do
7: // shuffle and split
8: shuffle the columns of X and Y with the same random order
9: split X and Y into N=⌈m/B⌉ mini-batches X{t} and Y{t}
10: for t=1 to N do
11: mt = the number of columns of X{t}
12: // forward propagation
13: A[0]{t}=X{t}
14: for l=1 to L do
15: Z[l]{t}=W[l]⋅A[l−1]{t}+b[l]⋅1T
16: A[l]{t}=σ(Z[l]{t})
17: end for
18: Y^{t}=A[L]{t}
19: // backward propagation
20: Δ[L]{t}=−(Y{t}−Y^{t})⊙σ′(Z[L]{t})
21: for l=L down to 1 do
22: ∇W[l]=mt1⋅Δ[l]{t}⋅A[l−1]{t}T
23: ∇b[l]=mt1⋅Δ[l]{t}⋅1
24: if l>1 then
25: Δ[l−1]{t}=(W[l]T⋅Δ[l]{t})⊙σ′(Z[l−1]{t})
26: end if
27: end for
28: // update
29: for l=1 to L do
30: W[l]←W[l]−α⋅∇W[l]
31: b[l]←b[l]−α⋅∇b[l]
32: end for
33: end for
34: end for
5 Implementation in NumPy
In this section, we will link every equation of this paper to its line in a NumPy implementation of the network [2]. We use the notebook simplest_neural_network.ipynb, which contains the minimal code of a network with 3 layers. For every part, we write the equation again with its number, and then we show the code that computes it. The line numbers of the code are the line numbers inside the cells of the notebook, so that the reader can find every line easily.
The network is trained on the AHDBase dataset of handwritten Arabic digits, which contains 60,000 training images and 10,000 test images. Each image has 8×8=64 pixels, and each label is one of the 10 digits written as a one-hot vector, i.e., a vector of 10 zeros with a single 1 in the position of the digit. Hence, the network has the following sizes:
L=3,n0=64,n1=32,n2=16,n3=10,m=60000
which is the same as our running example in Figure(1), but with more nodes in each layer.
5.1 The Variables
The following table shows the name of every variable of the paper in the code:
Paper
Code
Dimensions in the code
X,Y
X_train, y_train
64×60000,10×60000
A[0]
A0
64×m
W[1],W[2],W[3]
W1, W2, W3
32×64,16×32,10×16
b[1],b[2],b[3]
b1, b2, b3
32×1,16×1,10×1
Z[l],A[l]
Z1, A1, ..., Z3, A3
nl×m
Y^,Y
y_pred, y_true
10×m
Δ[l]
delta1, delta2, delta3
nl×m
∂W[l]∂J,∂b[l]∂J
dW1, ..., db3
same as W1, ..., b3
J
cost
1×1
α
alpha
1×1
m (or mt)
m
1×1
B
batch_size
1×1
and the following table shows the operations:
Operation
Paper
Code
Matrix product
W[1]⋅A[0]
W1.dot(A0)
Hadamard product
U⊙V
U * V
Transpose
W[3]T
W3.T
Sum of the columns
Δ[l]⋅1
delta1.sum(axis=1, keepdims=True)
5.2 The Examples as Columns
In Section(3.5), we stacked the examples as columns, so that X has the dimensions n0×m:
n0×mX=n0×m[x(1)∣x(2)∣⋯∣x(m)∣]
The dataset is loaded from a CSV file in which every example is a row, so the notebook takes the transpose of the data before training:
1# Take transpose since the neural network considers columns as examples and rows as features2# i.e. if m is the number of samples (images) and n is the number of features (image pixels), then3# n x m is the shape that is accepted by the network4 X_train = X_train.T
5 y_train = y_train.T
After this step, X_train has the dimensions 64×60000 and y_train has the dimensions 10×60000.
5.3 The Sigmoid Function and Its Derivative
The sigmoid function of equation(3):
σ(z)=1+e−z1
and its derivative of equation(4):
σ′(z)=σ(z)⋅(1−σ(z))
are implemented as follows:
1defsigmoid(Z):
2return1. / (1 + np.exp(-Z))
34defsigmoid_prime(A):
5return A * (1 - A)
Note: sigmoid_prime takes the output A of the layer, not the weighted sum Z. Since A[l]=σ(Z[l]) from equation(43), we can write equation(4) as:
σ′(Z[l])=σ(Z[l])⊙(1−σ(Z[l]))=A[l]⊙(1−A[l])
so we can reuse the outputs that we already computed in the forward propagation instead of computing the exponentials again. Hence, sigmoid_prime(A2) is σ′(Z[2]), and sigmoid_prime(y_pred) is σ′(Z[3]) since Y^=A[3]. Both functions work element-wise on matrices, as we explained in Section(2.1).
5.4 Initializing The Weights
Lines 1 and 2 of Algorithm(1) initialize the weights and the biases. The weights W[l] have the dimensions nl×nl−1 as we saw in Section(2.4):
The function np.random.random gives random numbers between 0 and 1. Multiplying them by 2 and subtracting 1 gives random numbers between -1 and 1. The weights are then divided by nl to make them small. Small weights keep the weighted sums Z[l] close to zero, where the sigmoid function is not flat and its derivative σ′ is not close to zero. If σ′ were close to zero, the errors Δ[l] in equation(44) would also be close to zero and the network would learn very slowly.
Note: the biases are stored as column-vectors of shape (nl,1), as we explained after equation(43). Also, the code initializes the biases randomly, while Algorithm(1) initializes them with zeros. Both choices work, since the random weights are already enough to make the nodes of each layer different from each other.
The loop over the layers in Algorithm(1) is written as three separate steps, since the network has only 3 layers. The term b[l]⋅1T is written as + b1, since NumPy broadcasts the bias vector to all the m columns, as we explained after equation(43).
The double sum goes over all the elements of the matrix (Y−Y^): the sum over j goes over its rows (the output nodes) and the sum over i goes over its columns (the examples). np.sum adds up all the elements of a matrix, so it computes both sums at once in line 32:
where ** 2 squares every element of the matrix. Line 31 only makes sure that y_true is a 2-D array. The cost is not needed to compute the gradients, but it is printed and saved to see whether the network is learning.
Line 35 is the error of the last layer with L=3, i.e., the loss derivative −(Y−Y^) multiplied element-wise by the activation's derivative σ′(Z[3]) as in equation(38). Lines 36 and 37 are the errors of the hidden layers with l=2 and l=1: the weighted propagated errors from the next layer W[l+1]T. Δ[l+1] multiplied element-wise by the activation's derivative as in equation(39). For example, line 36 is:
(lines 16 and 17 of Algorithm(1)) are computed in lines 39–45:
39 dW1 = delta1.dot(A0.T) / m
40 dW2 = delta2.dot(A1.T) / m
41 dW3 = delta3.dot(A2.T) / m
4243 db1 = delta1.sum(axis=1, keepdims=True) / m
44 db2 = delta2.sum(axis=1, keepdims=True) / m
45 db3 = delta3.sum(axis=1, keepdims=True) / m
Lines 39–41 are the sum of outer products that we wrote as a matrix multiplication in Section(3.5): the error of each layer multiplied by the transposed input of the same layer. For example, line 39 is:
32×64∂W[1]∂J=m1⋅32×mΔ[1]⋅m×64A[0]T
Lines 43–45 add up the m columns of each error with sum(axis=1), which is the same as Δ[l]⋅1. The option keepdims=True keeps the result as a column-vector of shape (nl,1) instead of a 1-D array of shape (nl,), so that it has the same shape as the bias.
Note: Algorithm(1) computes the gradients of each layer right after its error, while the code computes all the errors first and then all the gradients. Both orders give the same result, since the gradients are not used to compute the errors.
5.9 Checking The Dimensions
Throughout this paper, we showed the dimensions under each term. In particular, the gradients have the same dimensions as the weights and the biases, as in equations(40) and (41):
Line 1 gets the number of examples m, which is the number of columns of X. Line 2 sets the learning rate α, and line 5 sets the number of epochs T=20000. All the lines that we showed above (lines 16–62) are inside this loop, so the weights are updated once in every epoch.
Lines 8–12 shuffle the columns of X and Y with the same random order indices. As we noted at the end of Section(4.5), shuffling has no effect in batch gradient descent, since the gradient adds up all the examples and the sum does not depend on their order. It becomes important in the mini-batch version below.
5.12 The Mini-Batch Version
The notebook also contains the mini-batch gradient descent of Algorithm(2). The splitting into mini-batches of line 9 of Algorithm(2) and equation(47) is done by the following function:
defget_mini_batches(X, y, batch_size):
assert X.shape[1] == y.shape[1], 'Size Mismatch'
m = X.shape[1]
num_of_mini_batches = m // batch_size
for i inrange(num_of_mini_batches):
start = i * batch_size
end = start + batch_size
mini_batch_X = X[:, start:end]
mini_batch_y = y[:, start:end]
yield mini_batch_X, mini_batch_y
if m % batch_size != 0:
last_mini_batch_X = X[:, end:]
last_mini_batch_y = y[:, end:]
yield last_mini_batch_X, last_mini_batch_y
Line 4 computes the number of full mini-batches ⌊m/B⌋, where // is the integer division that rounds down. Lines 6–11 return the columns from start to end of each full mini-batch, i.e., X{t} and Y{t} with mt=B columns. If m is not divisible by B, lines 13–16 return the remaining columns as the last, smaller mini-batch with mN=m−(N−1)⋅B columns. Hence, the total number of mini-batches is N=⌈m/B⌉, as in equation(47). For our dataset, N=⌈60000/128⌉=469, where the first 468 mini-batches have 128 examples and the last one has 60000−468⋅128=96 examples.
The training loop of the mini-batch version is shown below. We only show the lines that differ from the batch version, since the forward propagation, the backward propagation, the gradients, and the update are the same as above with one more level of indentation:
alpha = 0.9
costs = []
batch_size = 128
tic = time.time()
for epoch in range(1000):
total_cost = 0
Shuffling
indices = np.arange(X_train.shape[1])
np.random.shuffle(indices)
Line 3 sets the mini-batch size B=128 (line 4 of Algorithm(2)).
Lines 10–14 shuffle the columns of X and Y at the beginning of every epoch (line 8). Here, the shuffling is important, since it gives different mini-batches in every epoch.
Line 18 is the new inner loop over the mini-batches (line 10), and get_mini_batches does the splitting (line 9).
Line 19 gets the size of the current mini-batch mt (line 11). The code keeps the variable name m, so all the lines / m of the gradients now divide by mt, as in equation(51). This is also correct for the last, smaller mini-batch.
Lines 20 and 21 use the mini-batch Y{t} and X{t} instead of the whole dataset (line 13).
The update of the weights (lines 60–67 of this cell) is inside the inner loop, so the weights are updated 469 times in every epoch instead of only one time.
Note: line 40 writes the loss derivative as (Y^−Y) instead of −(Y−Y^). The two are the same, since −(Y−Y^)=Y^−Y.
Note: the notebook also contains a stochastic gradient descent version, which is the special case B=1. It loops over the columns of X one by one and updates the weights after every example. Since mt=1, its gradients do not need to be divided by mt.
5.13 The Complete Implementation
Finally, the following code block shows the whole implementation in one place. It collects the cells of the notebook [2] in the same order as in this section: loading and preparing the data (Section(5)), the helper functions, the initialization of the weights, the mini-batch gradient descent of Algorithm(2), and the evaluation on the test set. We removed the cells that only display the data, and the notebook command %matplotlib inline, so that the code can also run as a normal Python script. The files AHDBase_TrainingSet.csv and AHDBase_TestingSet.csv from the repository must be in the same folder as the script.
Note: since the batch gradient descent and the stochastic gradient descent are special cases of the mini-batch gradient descent (Section(4)), we can get Algorithm(1) by setting batch_size = X_train.shape[1], i.e., B=m, and the stochastic gradient descent by setting batch_size = 1, i.e., B=1.
# ____________ imports ____________from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer
from sklearn.metrics import classification_report
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import time
# ____________ load the data ____________
data = pd.read_csv('AHDBase_TrainingSet.csv')
data_cols = list(data.columns)
data_cols.remove('Unnamed: 0')
train_data = data[data_cols]
data = pd.read_csv('AHDBase_TestingSet.csv')
data_cols = list(data.columns)
data_cols.remove('Unnamed: 0')
test_data = data[data_cols]
output = 'label'
``` features = list(train_data.columns)
features.remove(output)
# prepare the data# convert labels into one-hot encoding vectors
binarizer = LabelBinarizer()
one_hot-encoded_train_labels = binarizer.fit_transform(train_data[output])
X_train = train_data[features].values
y_train = one_hot-encoded_train_labels
X_test = test_data[features].values
y_test = binarizer.transform(test_data[output])
# Take transpose since the neural network considers columns as examples and rows as features# i.e. if m is the number of samples (images) and n is the number of features (image pixels), then# n x m is the shape that is accepted by the network
X_train = X_train.T
y_train = y_train.T
# helper functionsdefsigmoid(Z):
return1. / (1 + np.exp(-Z))
defsigmoid_prime(A):
return A * (1 - A)
defget_mini_batches(X, y, batch_size):
assert X.shape[1] == y.shape[1], 'Size Mismatch'
m = X.shape[1]
num_of_mini_batches = m // batch_size
for i inrange(num_of_mini_batches):
start = i * batch_size
end = start + batch_size
mini_bacth_X = X[:, start:end]
mini_bacth_y = y[:, start:end]
yield mini_bacth_X, mini_bacth_y
if m % batch_size != 0:
last_mini_bacth_X = X[:, end:]
last_mini_bacth_y = y[:, end:]
yield last_mini_bacth_X, last_mini_bacth_y
# initialize the weights randomly
W1 = 2*np.random.random((32, 64)) - 1
W1 /= 32
b1 = 2*np.random.random((32, 1)) - 1
W2 = 2*np.random.random((16, 32)) - 1
W2 /= 16
b2 = 2*np.random.random((16, 1)) - 1
W3 = 2*np.random.random((10, 16)) - 1
W3 /= 10
b3 = 2*np.random.random((10, 1)) - 1print(W1.shape, b1.shape)
print(W2.shape, b2.shape)
print(W3.shape, b3.shape)
# mini-batch gradient descent
alpha = 0.9
costs = []
batch_size = 128
tic = time.time()
for epoch inrange(1000):
total_cost = 0### Shuffling ###
indices = np.arange(X_train.shape[1])
np.random.shuffle(indices)
X_train = X_train[:, indices]
y_train = y_train[:, indices]
###############
j = 0for mini_bacth_X, mini_bacth_y in get_mini_batches(X_train, y_train, batch_size):
m = mini_bacth_y.shape[1]
y_true = mini_bacth_y
A0 = mini_bacth_X
# feedforward
Z1 = W1.dot(A0) + b1
A1 = sigmoid(Z1)
Z2 = W2.dot(A1) + b2
A2 = sigmoid(Z2)
Z3 = W3.dot(A2) + b3
A3 = sigmoid(Z3)
y_pred = A3
y_true = np.atleast_2d(y_true)
cost = 0.5 * np.sum((y_true - y_pred) ** 2) / m
total_cost += cost
# backpropagate error
delta3 = (y_pred - y_true) * sigmoid_prime(y_pred)
delta2 = W3.T.dot(delta3) * sigmoid_prime(A2)
delta1 = W2.T.dot(delta2) * sigmoid_prime(A1)
dW1 = delta1.dot(A0.T) / m
dW2 = delta2.dot(A1.T) / m
dW3 = delta3.dot(A2.T) / m
db1 = delta1.sum(axis=1, keepdims=True) / m
db2 = delta2.sum(axis=1, keepdims=True) / m
db3 = delta3.sum(axis=1, keepdims=True) / m
assert W1.shape == dW1.shape, 'Size Mismatch'assert W2.shape == dW2.shape, 'Size Mismatch'assert W3.shape == dW3.shape, 'Size Mismatch'assert b1.shape == db1.shape, 'Size Mismatch'assert b2.shape == db2.shape, 'Size Mismatch'assert b3.shape == db3.shape, 'Size Mismatch'# update weights
W1 = W1 - alpha*dW1
W2 = W2 - alpha*dW2
W3 = W3 - alpha*dW3
b1 = b1 - alpha*db1
b2 = b2 - alpha*db2
b3 = b3 - alpha*db3
j += 1
costs.append(cost)
if epoch % 10 == 0:
print(epoch, total_cost / j)
toc = time.time()
# evaluate on the test set
A0 = X_test.T
y_true = y_test.T
# feedforward
Z1 = W1.dot(A0) + b1
A1 = sigmoid(Z1)
Z2 = W2.dot(A1) + b2
A2 = sigmoid(Z2)
Z3 = W3.dot(A2) + b3
A3 = sigmoid(Z3)
y_pred = A3
my_labels_pred = binarizer.inverse_transform(y_pred.T)
print(classification_report(test_data[output], my_labels_pred))
plt.plot(costs)
## References
[1] F. A. Alasmary, “Detailed Derivation of The Linear Regression Model,” October 2019. [Online]. Available: https://www.researchgate.net/publication/340686790_Detailed_Derivation_of_The_Linear_Regressio_n_Model
[2] F. A. Alasmary, “Neural Network in Pure NumPy,” GitHub repository, notebook simplest_neural_network.ipynb. [Online]. Available: https://github.com/farisalasmary/neural-network-numpy/blob/master/Neural%20Network/simplest_neural_network.ipynb