PyTorch中有关函数“ tensor.backward()”的简单但令人不安的问题

问题描述 投票:4回答:1

这些天我正在学习PyTorch,backward()功能确实让我感到困惑。让我们直接解决我的问题:

我定义了一些张量和操作:

```

import torch
x = torch.ones(2,5,requires_grad=True)
y = x + 2
z = x*x
Y = torch.mean(y)
Z = torch.mean(z)

```

如果我运行此命令:

y.backward(torch.ones(2,5))
z.backward(torch.ones(2,5))

未发生错误。

但是,如果我运行此:

Y.backward()
Z.backward()

我知道了:

    RuntimeError                              Traceback (most recent call last)
<ipython-input-7-732c4cd53ca7> in <module>()
      1 Y.backward()
----> 2 Z.backward()

E:\learningsoft\anadonda\lib\site-packages\torch\tensor.py in backward(self, gradient, retain_graph, create_graph)
     91                 products. Defaults to ``False``.
     92         """
---> 93         torch.autograd.backward(self, gradient, retain_graph, create_graph)
     94 
     95     def register_hook(self, hook):

E:\learningsoft\anadonda\lib\site-packages\torch\autograd\__init__.py in backward(tensors, grad_tensors, retain_graph, create_graph, grad_variables)
     88     Variable._execution_engine.run_backward(
     89         tensors, grad_tensors, retain_graph, create_graph,
---> 90         allow_unreachable=True)  # allow_unreachable flag
     91 
     92 

RuntimeError: Trying to backward through the graph a second time, but the buffers have already been freed. Specify retain_graph=True when calling backward the first time.

有人可以告诉我他们为什么会有不同的结果?


让我给我更多示例:example1(picture)

python deep-learning pytorch
1个回答
0
投票

这是您运行命令的顺序。

首先,您在yz上向后运行。然后,在YZ上运行它,but YZ基于yz-它们已经向后运行。

您需要在yz上向后运行,然后重置内核,然后重做计算并在YZ上向后运行。

x = torch.ones(2,5,requires_grad=True)
y = x + 2
z = x*x
Y = torch.mean(y)
Z = torch.mean(z)
y.backward(torch.ones(2,5))
z.backward(torch.ones(2,5))

然后重设。

x = torch.ones(2,5,requires_grad=True)
y = x + 2
z = x*x
Y = torch.mean(y)
Z = torch.mean(z)
Y.backward()
Z.backward()
© www.soinside.com 2019 - 2024. All rights reserved.