maz*_*bas 11 python-2.5 pytorch
我想使用 NN 的输出变量作为另一个函数的输入,但遇到了这样的错误“目前只有用户(图叶)明确创建的张量支持深度复制协议”。输出变量需要梯度。
我尝试将输出变量更改为 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)
Run Code Online (Sandbox Code Playgroud)
它应该可以工作,但它会出错。
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:
Run Code Online (Sandbox Code Playgroud)
小智 1
我曾经遇到过类似的问题。简单来说,这个错误是由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.
#-----------------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5968 次 |
最近记录: |