# Calculating gradients

xt = tensor([3.,4.,10.]).requires_grad_()
xt

---------------------------------
tensor([ 3.,  4., 10.], requires_grad=True)
1
2
3
4
5

The requires_grad_() method tells PyTorch to tag that variable at that value so that we can calculate its gradient at a later time.

def f(x): return x**2

yt = f(xt)
yt
_________________________________
tensor(9., grad_fn=<PowBackward0>)
1
2
3
4
5
6

# Calculate the gradient

yt.backward()
1

# View the gradient by accessing the grad property

xt.grad
1