Shrey Joshi
Shrey Joshi

Reputation: 1206

Breakdown of Stochastic Gradient Descent Code in Python

In Michael Nielson's Online book on Artificial Neural Networks, http://neuralnetworksanddeeplearning.com, he provides the following code:

    def update_mini_batch(self, mini_batch, eta):
    """Update the network's weights and biases by applying
    gradient descent using backpropagation to a single mini batch.
    The ``mini_batch`` is a list of tuples ``(x, y)``, and ``eta``
    is the learning rate."""
    nabla_b = [np.zeros(b.shape) for b in self.biases]
    nabla_w = [np.zeros(w.shape) for w in self.weights]
    for x, y in mini_batch:
        delta_nabla_b, delta_nabla_w = self.backprop(x, y)
        nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)]
        nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)]
    self.weights = [w-(eta/len(mini_batch))*nw
                    for w, nw in zip(self.weights, nabla_w)]
    self.biases = [b-(eta/len(mini_batch))*nb
                   for b, nb in zip(self.biases, nabla_b)]

I am having trouble understanding the parts with nabla_b and nabla_w.

If delta_nabla_b and delta_nabla_w are the gradients of the cost function then why do we add them to the existing values of nabla_b and nabla_w here?

nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)]
nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)]

Shouldn't we just directly define

nabla_b, nabla_w = self.backprop(x, y)

and update the weight and bias matrices?

Do we make nabla_b and nabla_w because we want to do an average over the gradients and they are the matrices of the sums of the gradients?

Upvotes: 4

Views: 536

Answers (1)

Maxim
Maxim

Reputation: 53758

Do we make nabla_b and nabla_w because we want to do an average over the gradients and they are the matrices of the sums of the gradients?

Yes, your thinking is right. Basically, this code directly corresponds to the formula in the step 3 Gradient descent in the tutorial.

The formula itself is a bit misleading, and intuitively it's easier to think that the weights and biases are updated independently for each instance in a mini-batch. But if you recall that the gradient of the sum is the sum of the gradients it becomes clear that it's actually the same. In both cases, all gradients contribute in the same way into the parameters update.

Upvotes: 4

Related Questions