关于函数的简单而令人不安的问题张量向后()“在Pythorch

2024-10-01 19:22:08 发布

您现在位置:Python中文网/ 问答频道 /正文

这几天我在学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)


Tags: theinselftruecreatetorchmeangraph
1条回答
网友
1楼 · 发布于 2024-10-01 19:22:08

这是你运行命令的顺序。在

首先在yz上向后运行。然后在YZ上运行它,但是Y和{}是基于{}和{}的,它们已经在它们上反向运行过了。在

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

x = torch.ones(2,5,requires_grad=True)
y = x + 2
z = x*x
Y = torch.mean(y)
Z = torch.mean(z)
^{pr2}$

然后复位。在

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()

相关问题 更多 >

    热门问题