【发布时间】:2021-04-19 11:21:17
【问题描述】:
在以下示例中,有人可以向我解释在 Python 的 for 循环中执行增强赋值时的意外行为吗:
- 以下代码正在执行
n_epochs迭代,试图获得参数theta的最优值。奇怪的是,即使它正确地完成了工作并成功收敛,列表theta_list也充满了循环最后一次迭代中theta的n_epochs + 1值。
eta = 0.1
n_epochs = 5
theta = np.random.rand(2, 1)
loss_list = []
theta_list = []
theta_list.append(theta)
for epoch in range(n_epochs):
theta -= eta * loss_grad(theta, x, y)
theta_list.append(theta)
loss_list.append(loss(theta, np.c_[np.ones_like(x), x], y))
print(theta_list)
In [1]: %run proto.py
[array([[3.6315498 ],
[3.40173314]]), array([[3.6315498 ],
[3.40173314]]), array([[3.6315498 ],
[3.40173314]]), array([[3.6315498 ],
[3.40173314]]), array([[3.6315498 ],
[3.40173314]]), array([[3.6315498 ],
[3.40173314]])]
- 在上一个示例中更改单行后,从
theta -= eta * loss_grad(theta, x, y)
到
theta = theta - eta * loss_grad(theta, x, y)
输出看起来如预期:
In [5]: %run proto.py
[array([[0.00686239],
[0.06257885]]), array([[1.50998752],
[1.80281404]]), array([[2.35777388],
[2.7475853 ]]), array([[2.84342938],
[3.25403032]]), array([[3.12872463],
[3.51915101]]), array([[3.30292104],
[3.65160945]])]
我没有在 stackoverflow 或其他任何在线网站上注意到有人遇到过类似的问题。 我正在使用通过 Anaconda3 安装的 Windows 10 和 Python 3.8.5。
【问题讨论】:
-
这能回答你的问题吗? Why does += behave unexpectedly on lists?
标签: python list for-loop augmented-assignment