【问题标题】:w -= dw vs w = w - dw in torchw -= dw 与 w = w - dw 在火炬中
【发布时间】:2022-01-25 17:28:26
【问题描述】:

今天偶然发现了一个torch行为,w = w - dw不严格等于w -= dw,下面附上简单的例子:

x_input_, y_gt_ = datasets.make_regression(n_samples=100, n_features=1)
    # Model
    x_input = torch.from_numpy(x_input_)
    w = torch.tensor(1, requires_grad=True, dtype=torch.float32)

    x_input = torch.from_numpy(x_input_)
    y_gt = torch.unsqueeze(torch.from_numpy(y_gt_), dim=1)

    lr = 0.01
    for iter in range(3):
        y_pred = w * x_input
        loss = ((y_gt - y_pred) ** 2).mean()
        loss.backward()
        with torch.no_grad():
            dw = w.grad * lr
            print(w)
            w -= dw
            print(w)

哪个输出(预期)

tensor(1., requires_grad=True)
tensor(1.0413, requires_grad=True)
tensor(1.0413, requires_grad=True)
tensor(1.1230, requires_grad=True)
tensor(1.1230, requires_grad=True)
tensor(1.2431, requires_grad=True)

但是,如果我将 w -= dw 替换为 w = w - dw,则会说不再附加渐变

tensor(1., requires_grad=True)
tensor(3.1186)

我很好奇这可能是什么原因造成的?

【问题讨论】:

  • -= 更新现有对象,而= 将其替换为新对象。

标签: python torch


【解决方案1】:

表达式w -= dw 调用w 上的一个特殊函数,允许它修改自己。

表达式w - dw 创建一个新对象,w = 分配该新对象来代替旧对象。

【讨论】:

    猜你喜欢
    • 2020-05-24
    • 2010-10-16
    • 2015-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    相关资源
    最近更新 更多