首页 > 解决方案 > Python中随机梯度下降代码的分解

问题描述

在 Michael Nielson 的人工神经网络在线书籍http://neuralnetworksanddeeplearning.com中,他提供了以下代码:

    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)]

我无法理解带有 nabla_b 和 nabla_w 的部分。

如果delta_nabla_b并且delta_nabla_w是成本函数的梯度,那么我们为什么要在此处将它们添加到 nabla_b 和 nabla_w 的现有值中呢?

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)]

我们不应该直接定义

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

并更新权重和偏差矩阵?

我们是否因为我们想要对梯度进行平均,并且它们是梯度总和的矩阵nabla_bnabla_w

标签: machine-learningneural-networkdeep-learningbackpropagationgradient-descent

解决方案


我们制作 nabla_b 和 nabla_w 是因为我们想要对梯度进行平均并且它们是梯度和的矩阵吗?

是的,你的想法是对的。基本上,这段代码直接对应教程中step 3 Gradient descent中的公式。

公式本身有点误导,直观上更容易认为权重和偏差是针对小批量中的每个实例独立更新的。但是,如果您还记得总和的梯度是梯度的总和,那么很明显它实际上是相同的。在这两种情况下,所有梯度都以相同的方式对参数更新做出贡献。


推荐阅读