1

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,

1 Answer 1

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

Works fine.

Sign up to request clarification or add additional context in comments.

3 Comments

The autograd.Variable API has been deprecated since version 0.4.0. To improve clarity I recommend x = torch.Tensor([1.0], requires_grad=True) instead.
Hello, thank you for your answer. I have a follow up question. can PyTorch do vector calculus? for example, computing a second derivative with respect to a vector? If yes, how can I compute a second derivative of a function with respect to a vector on Pytorch?
@IgorRivin thank you so much! This is very helpful! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.