在 Michael Nielsen 的神经网络教程中,他有以下代码:
def update_mini_batch(self, mini_batch, eta):
"""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)]
我了解元组和列表是什么,也了解 zip 函数在做什么,但我不明白变量 nb、dnb、nw 和 dnw 如何在这两行代码上更新:
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)]
谁能帮忙解释一下这两行中发生的魔法吗?
最佳答案
这两行是Python的典型例子list comprehensions .
本质上,对于您的第一个列表:
nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)]
这意味着:
- 从
zip(nabla_b, delta_nabla_b)中获取第一对
;将它们命名为nb
和dnb
- 添加它们 (
nb+dnb
) - 将结果作为新列表的第一个元素
nabla_b
- 转到第二对的第一步,依此类推,将结果附加到
nabla_b
,直到zip(nabla_b, delta_nabla_b)
中的所有对都已用尽
作为一个简单的例子,下面的列表理解:
squares = [x**2 for x in range(10)]
print(squares)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
相当于下面的for
循环:
squares = []
for x in range(10):
squares.append(x**2)
print(squares)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
参见here了解更多示例和快速介绍。
关于python - 更新列表中的 Python for 循环是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54692894/