Deep learning Pytorch二阶导数返回None

Deep learning Pytorch二阶导数返回None,deep-learning,pytorch,autograd,Deep Learning,Pytorch,Autograd,我不能对下面的函数求二阶导数。当我想要关于u_s的二阶导数时,它起作用,但是对于x_s它不起作用 有人知道我做错了什么吗 def cost(xt, x_goal, u, Q, R): return (xt - x_goal).matmul(Q).matmul((xt - x_goal).transpose(0,1)) + u.matmul(R).matmul(u) x_s = tr.tensor([ 0.0000, -1.0000, 0.0000], dtype=torch.

我不能对下面的函数求二阶导数。当我想要关于u_s的二阶导数时,它起作用,但是对于x_s它不起作用

有人知道我做错了什么吗

def cost(xt, x_goal, u, Q, R):
        return (xt - x_goal).matmul(Q).matmul((xt - x_goal).transpose(0,1)) + u.matmul(R).matmul(u)

x_s = tr.tensor([ 0.0000, -1.0000,  0.0000], dtype=torch.float64,  requires_grad=True)
u_s = tr.tensor([-0.2749], dtype=torch.float64, requires_grad=True)
c = cost(x_s, x_Goal, u_s, tr.tensor(Q), tr.tensor(R))

c
   output: 
   tensor([[4.0076]], dtype=torch.float64, grad_fn=<ThAddBackward>)

Cu = grad(c, u_s, create_graph=True)[0]
Cu
   output:
   tensor([-0.0550], dtype=torch.float64, grad_fn=<ThAddBackward>)

Cuu = grad(Cu, u_s, allow_unused=True)[0]
Cuu
   output:
   tensor([0.2000], dtype=torch.float64)

Cux = grad(Cu, x_s, allow_unused=True)
Cux
    output:
    (None,)
def成本(xt,x_目标,u,Q,R):
返回(xt-x_目标).matmul(Q).matmul((xt-x_目标).transpose(0,1))+u.matmul(R).matmul(u)
x_s=tr.tensor([0.0000,-1.0000,0.0000],dtype=torch.float64,需要_grad=True)
u_s=tr.tensor([-0.2749],dtype=torch.float64,需要_grad=True)
c=成本(x_s,x_目标,u_s,tr.tensor(Q),tr.tensor(R))
C
输出:
张量([[4.0076]],dtype=torch.float64,grad_fn=)
Cu=grad(c,u\s,create\u graph=True)[0]
铜
输出:
张量([-0.0550],dtype=torch.float64,grad_fn=)
Cuu=梯度(Cu,u_s,允许未使用=真)[0]
丘
输出:
张量([0.2000],dtype=torch.float64)
Cux=梯度(Cu,x_s,允许未使用=真)
库克斯
输出:
(无)

我猜Cu本身完全独立于x_s,但是导数至少应该是零,而不是零

你没有做错什么

假设我有变量
x
y
,和
z=f(y)
。如果我计算z.backward(),然后尝试询问相对于x的梯度,我得到
None
。比如说,

import torch

x = torch.randn(1,requires_grad=True)
y = torch.randn(1,requires_grad=True)

z = y**2
z.backward()
print(y.grad) # Outputs some non-zero tensor
print(x.grad) # None
那么,这与计算二阶导数Cux有什么关系呢?当您编写
create\u graph=True
时,PyTorch会跟踪计算
Cu
的导数计算中的所有操作,并且由于导数本身由基本操作组成,因此您可以像现在这样计算梯度的梯度。这里的问题是梯度
Cu
从未遇到变量
x_s
,因此有效地
Cu=f(u_s)
。这意味着当您执行
Cu.backward()
时,
Cu
的计算图永远看不到变量
x_s
,因此它的渐变类型仍然是
None
,就像上面的示例一样