python - Pytorch - 如何区分两个参数

标签 python pytorch gradient tensor derivative

我对使用 Pytorch 的组合导数感兴趣:enter image description here

在下面实现的代码中,我已经尝试过,但是代码计算两个偏导数(例如,它首先计算 d'f/d'x,然后计算 d'f/d'y)。是否可以以某种方式修改代码,以便我们可以计算两个参数的导数?

import torch
def function(x,y):
    f = x**3+y**3
    return f

a =  torch.tensor([4., 5., 6.], requires_grad=True)
b =  torch.tensor([1., 2., 6.], requires_grad=True)
derivative = torch.autograd.functional.jacobian(function, (a,b))
print(derivative)

提前致谢!

最佳答案

您可以使用torch.autograd.functional.hessian得到组合导数。

>>> f = lambda x, y: (x**3 + y**3).mean()
>>> H = A.hessian(f, (a, b))

由于您有两个输入,因此结果将是一个包含 2 个元组元组

更准确地说,您将拥有

  • H[0][0]x 的二阶导数:d²z_i/dx_j*dx_j

  • H[0][1] x 和 y 的组合导数:d²z_i/dx_j*dy_j

  • H[0][1] yx 的组合导数:d²z_i/dy_j*dx_j

  • H[1][1]y 的二阶导数:d²z_i/dy_j*dy_j


>>> H
((tensor([[ 8.,  0.,  0.],
          [ 0., 10.,  0.],
          [ 0.,  0., 12.]], 
  tensor([[ 0.,  0.,  0.],
          [ 0.,  0.,  0.],
          [ 0.,  0.,  0.]]),
 (tensor([[ 0.,  0.,  0.],
          [ 0.,  0.,  0.],
          [ 0.,  0.,  0.]]))
  tensor([[ 2.,  0.,  0.],
          [ 0.,  4.,  0.],
          [ 0.,  0., 12.]])

确实,如果您查看组合导数:d²(x3+y3)/dxdy = d(3x2)/dy = 0,因此 H[0][1] code> 和 H[1][0] 是零矩阵。

另一方面,我们有 d2x3/d2x = 6x,因为 f 正在对这些值进行平均,所以它给出 6x/3 = 2x >。同样,您得到d²x³/d²y = 6y

结果,您会发现 H[0][0] = diag(2a)H[1][1] = diag(2b)

关于python - Pytorch - 如何区分两个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68949618/

相关文章:

python - 在 python 中使用 BS 抓取页面仅捕获 splitColumn 的第一列

html - CSS渐变创建两种不同的颜色设计

python - 如何在 Pipfile 中指定操作系统特定的 wheel 文件

css - 通过 CSS 重用 SVG 渐变

firefox - CSS3 background-size 属性在 ff5 中导致极端性能问题

python - Pandas 有条件地创建数据框列 : based on multiple conditions

python - 通过python使用条件运算符分割文本文件

python - 从任务栏隐藏窗口

python - 无法在 docker 中打开 jupyter notebook

python - 属性错误: 'tuple' object has no attribute 'size'