Search code examples
pythonpytorchderivative

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:

>>>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.)). How can I achieve this with PyTorch? or if I can't carry out this task with PyTorch, how can I do this type of task easily on Python?

Thank you,


Solution

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

    Works fine.