这几天我在学Pythorch,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)
```
如果我运行这个:
^{pr2}$没有发生错误。在
但是,如果我运行这个:
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)
这是你运行命令的顺序。在
首先在}是基于{}和{}的,它们已经在它们上反向运行过了。在
y
和z
上向后运行。然后在Y
和Z
,上运行它,但是Y
和{您需要在
^{pr2}$y
和z
上向后运行,然后重置内核,然后重新进行计算并在Y
和Z
上向后运行。在然后复位。在
相关问题 更多 >
编程相关推荐