【问题标题】:Augmented assignment unexpected behavior in PythonPython中的增强赋值意外行为
【发布时间】:2021-04-19 11:21:17
【问题描述】:

在以下示例中,有人可以向我解释在 Python 的 for 循环中执行增强赋值时的意外行为吗:

  • 以下代码正在执行n_epochs 迭代,试图获得参数theta 的最优值。奇怪的是,即使它正确地完成了工作并成功收敛,列表 theta_list 也充满了循环最后一次迭代中 thetan_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。

【问题讨论】:

标签: python list for-loop augmented-assignment


【解决方案1】:

出于效率原因,Numpy 数组支持(广播)就地增强分配。

您的第一个示例修改了名称 theta 所指向的变量。

第二个计算theta - eta * loss_grad(theta, x, y),。然后将其分配给名称theta

【讨论】:

    猜你喜欢
    • 2011-01-17
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-20
    • 2011-07-11
    • 2019-03-01
    • 1970-01-01
    相关资源
    最近更新 更多