Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 获取输出';相对于输入的s梯度_Python_Pytorch_Ode_Autograd - Fatal编程技术网

Python 获取输出';相对于输入的s梯度

Python 获取输出';相对于输入的s梯度,python,pytorch,ode,autograd,Python,Pytorch,Ode,Autograd,我目前正在尝试用Pytorch实现一个ODE解算器,我的解决方案需要计算每个输出wtr到其输入的梯度 y = model(x) for i in range(len(y)): #compute output grad wrt input y[i].backward(retain_graph=True) ydx=x.grad x = torch.Tensor([1, 2, 3]) x.requires_grad = True def model(x): return

我目前正在尝试用Pytorch实现一个ODE解算器,我的解决方案需要计算每个输出wtr到其输入的梯度

y = model(x)

for i in range(len(y)): #compute output grad wrt input
       y[i].backward(retain_graph=True)
    
ydx=x.grad 
x = torch.Tensor([1, 2, 3])
x.requires_grad = True

def model(x): return x ** 2

y = model(x)
我想知道是否有一种更优雅的方法来计算批处理中每个输出的梯度,因为高阶ODE和PDE的代码会变得混乱。 我尝试使用:

torch.autograd.backward(x,y,retain_graph=True)

没有太多成功。

您可以使用
torch.autograd.grad
函数直接获得渐变。一个问题是它要求输出(
y
)是标量。因为您的输出是一个数组,所以仍然需要循环遍历它的值

这个电话看起来像这样

[torch.autograd.grad(outputs=out, inputs=x, retain_graph=True)[0][i] 
    for i, out in enumerate(y)]
这是我的意思的一个例子。让我们考虑变量<代码> x>代码>值>代码> [1,2,3] 和一个只对其输入进行平方的模型。

y = model(x)

for i in range(len(y)): #compute output grad wrt input
       y[i].backward(retain_graph=True)
    
ydx=x.grad 
x = torch.Tensor([1, 2, 3])
x.requires_grad = True

def model(x): return x ** 2

y = model(x)
现在,如果您像我描述的那样调用
torch.autograd.grad
,您将得到:

[torch.autograd.grad(outputs=out, inputs=x, retain_graph=True)[0][i] 
    for i, out in enumerate(y)]

# [tensor(2.), tensor(4.), tensor(6.)]

这是wrt衍生产品列表。如果您的PyTorch版本实现了API,请尝试使用
torch.autograd.functional.jacobian
来获取
x
-
[ydx0,ydx1,ydx2

的值。我也在为汉堡方程式做同样的事情,并在同一主题上发布了以下帖子:

使用DL解决PDE是当前的热门话题