machine-learning - 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_b
?nabla_w
解决方案
我们制作 nabla_b 和 nabla_w 是因为我们想要对梯度进行平均并且它们是梯度和的矩阵吗?
是的,你的想法是对的。基本上,这段代码直接对应教程中step 3 Gradient descent中的公式。
公式本身有点误导,直观上更容易认为权重和偏差是针对小批量中的每个实例独立更新的。但是,如果您还记得总和的梯度是梯度的总和,那么很明显它实际上是相同的。在这两种情况下,所有梯度都以相同的方式对参数更新做出贡献。
推荐阅读
- python - 防止 Python 中的 for 循环用于求和函数
- arrays - 解析复杂的 JSON Flutter
- c++ - 关于使用 || 的 if/else 代码的问题 和 &&
- r - 结合 {stringr} 和 mutate() 在大型数据集中一次操作多个列?
- java - 如何找到至少吃 P 个苹果所需的最短时间?请帮我优化这个问题的代码
- google-apps-script - 通过 AppScript 从 Google Drive 上传到 BOX
- c# - 切换分配给键的内容和分配给值的内容是否会对 KeyValuePair 集合产生影响?
- javascript - 如何重用代码并避免重复代码 Nodejs
- java - C++ 中的 Java 迭代器
- python - 更改标记大小时标记样式发生变化