简体   繁体   English

使用 PyTorch 计算 function 的导数

[英]Using PyTorch for computing derivative of a function

When I execute the code below:当我执行下面的代码时:

import torch 

def g(x):
    return 4*x + 3
x=3.0
g_hat=torch.tensor(g(x), requires_grad= True)
g_hat.backward()

I get the following output:我得到以下 output:

>>>g_hat.grad
tensor(1.)

But this is not the result that I was expecting to get from my code above... what I want to do is, I want to find the value of dg/dx, at x = 3.0 (so in the example above, the correct output should be tensor(4.) ).但这不是我期望从上面的代码中得到的结果......我想做的是,我想在x = 3.0处找到 dg/dx 的值(所以在上面的示例中,正确output 应该是tensor(4.) )。 How can I achieve this with PyTorch?如何使用 PyTorch 实现这一目标? or if I can't carry out this task with PyTorch, how can I do this type of task easily on Python?或者如果我无法使用 PyTorch 执行此任务,如何在 Python 上轻松完成此类任务?

Thank you,谢谢,

x = torch.autograd.Variable(torch.Tensor([1.0]),requires_grad=True)
y = 4 * x + 3
y.backward()
x.grad

Works fine.工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM