Python 更新Newton'的PyTorch实现步骤;s法

Python 更新Newton'的PyTorch实现步骤;s法,python,mathematical-optimization,pytorch,newtons-method,automatic-differentiation,Python,Mathematical Optimization,Pytorch,Newtons Method,Automatic Differentiation,我试图通过实现牛顿解x=cos(x)的方法来了解PyTorch是如何工作的。以下是一个有效的版本: x = Variable(DoubleTensor([1]), requires_grad=True) for i in range(5): y = x - torch.cos(x) y.backward() x = Variable(x.data - y.data/x.grad.data, requires_grad=True) print(x.data) # te

我试图通过实现牛顿解x=cos(x)的方法来了解PyTorch是如何工作的。以下是一个有效的版本:

x =  Variable(DoubleTensor([1]), requires_grad=True)

for i in range(5):
    y = x - torch.cos(x)
    y.backward()
    x = Variable(x.data - y.data/x.grad.data, requires_grad=True)

print(x.data) # tensor([0.7390851332151607], dtype=torch.float64) (correct)
这段代码对我来说似乎不雅观(低效?),因为它在
for
循环的每个步骤中都在重新创建整个计算图(对吗?)。我试图通过简单地更新每个变量所持有的数据而不是重新创建它们来避免这种情况:

x =  Variable(DoubleTensor([1]), requires_grad=True)
y = x - torch.cos(x)
y.backward(retain_graph=True)

for i in range(5):
    x.data = x.data - y.data/x.grad.data
    y.data = x.data - torch.cos(x.data)
    y.backward(retain_graph=True)

print(x.data) # tensor([0.7417889255761136], dtype=torch.float64) (wrong)
似乎,对于双张量,我携带了足够的精度数字来排除舍入误差。那么错误来自哪里呢

可能相关:如果
for
循环,则上述代码段在每个步骤都没有设置
retain\u graph=True
标志的情况下中断。如果我在循环中省略了它,但将其保留在第3行,则得到的错误消息是:
RuntimeError:第二次尝试向后遍历图形,但缓冲区已被释放。第一次向后调用时指定retain_graph=True。这似乎是我误解了什么的证据…

我认为您的第一个版本的代码是最佳的,这意味着它不会在每次运行时创建计算图

# initial guess
guess = torch.tensor([1], dtype=torch.float64, requires_grad = True) 

# function to optimize
def my_func(x): 
    return x - torch.cos(x)

def newton(func, guess, runs=5): 
    for _ in range(runs): 
        # evaluate our function with current value of `guess`
        value = my_func(guess)
        value.backward()
        # update our `guess` based on the gradient
        guess.data -= (value / guess.grad).data
        # zero out current gradient to hold new gradients in next iteration 
        guess.grad.data.zero_() 
    return guess.data # return our final `guess` after 5 updates

# call starts
result = newton(my_func, guess)

# output of `result`
tensor([0.7391], dtype=torch.float64)
在每次运行中,定义计算图的函数
my_func()
,将使用当前的
guess
值进行计算。返回结果后,我们计算梯度(使用
value.backward()
call)。有了这个渐变,我们现在更新我们的
猜测
并将渐变归零,以便下次调用
value.backward()
(即,它停止累积梯度;如果不将梯度归零,它将默认开始累积梯度。但是,我们希望避免这种行为)