gpt4 book ai didi

pytorch - 如何解决运行时错误 "Only Tensors created explicitly by the user (graph leaves) support the deepcopy protocol at the moment"

转载 作者:行者123 更新时间:2023-12-01 19:44:25 37 4
gpt4 key购买 nike

我想使用 NN 的输出变量作为另一个函数的输入,但遇到了这样的错误:“目前只有用户明确创建的张量(图叶)支持深度复制协议(protocol)”。输出变量需要梯度。

我尝试将输出变量更改为 numpy 值,但在这种情况下,反向传播不起作用,因为它将 numpy 值视为不需要梯度的变量。

output = model(SOC[13])

# Three output values of NN
Rs=output[0]
R1=output[1]
C1=output[2]

# Using these variables in another function

num1=[Rs*R1*C1,R1+Rs]
den1=[C1*R1,1]
G = control.tf(num,den)

它应该可以工作,但它给出了错误。

     14             num=[Rs*R1*C1,R1+Rs]
15 den=[C1*R1,1]
---> 16 G = control.tf(num,den)
~\Anaconda3\lib\site-packages\control\xferfcn.py in __init__(self, *args)
106
107 """
--> 108 args = deepcopy(args)
109 if len(args) == 2:
110 # The user provided a numerator and a denominator.
~\Anaconda3\lib\site-packages\torch\tensor.py in __deepcopy__(self, memo)
16 def __deepcopy__(self, memo):
17 if not self.is_leaf:
---> 18 raise RuntimeError("Only Tensors created explicitly by the user "
19 "(graph leaves) support the deepcopy protocol at the moment")
20 if id(self) in memo:

最佳答案

我曾经遇到过类似的问题。简单来说,这个错误是由deepcopy造成的,deepcopy不适合非叶子节点。可以打印Rs、R1、C1来检查它们是否是叶子节点。

如果它们是叶节点,则有“requires_grad=True”,而不是“grad_fn=SliceBackward”或“grad_fn=CopySlices”。我猜非叶子节点有grad_fn,它是用来传播梯度的。

#---------------------------------------------------------------------------------
>>>import torch
>>>q = torch.nn.Parameter(torch.Tensor(3,3))
>>>q
Parameter containing:
tensor([[8.7551e-37, 0.0000e+00, 0.0000e+00],
[0.0000e+00, 0.0000e+00, 0.0000e+00],
[0.0000e+00, 0.0000e+00, 0.0000e+00]], requires_grad=True)
#q is leaf node
>>>p = q[0,:]
>>>p
tensor([8.7551e-37, 0.0000e+00, 0.0000e+00], grad_fn=<SliceBackward>)
#p is non-leaf node
>>>q[0,0] = 0
>>>q
Parameter containing:
tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]], grad_fn=<CopySlices>)
#if slice operation is made on q, q becomes non-leaf node. The deepcopy is not suitable for q any more.
#-----------------------------------------------------------------------------

关于pytorch - 如何解决运行时错误 "Only Tensors created explicitly by the user (graph leaves) support the deepcopy protocol at the moment",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56590886/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com