Gradient with PyTorch
In this section, we discuss the derivatives and how they can be applied on PyTorch. So let starts
The gradient is used to find the derivatives of the function. In mathematical terms, derivatives mean differentiation of a function partially and finding the value.
Below is the diagram of how to calculate the derivative of a function.
The work which we have done above in the diagram will do the same in PyTorch with gradient. There is the following step to find the derivative of the function.
1. We have first to initialize the function (y=3x3 +5x2+7x+1) for which we will calculate the derivatives.
2. Next step is to set the value of the variable used in the function. The value of x is set in the following manner.
We typically require a gradient to find the derivative of the function.
3. Next is to compute the derivative of the function simply by using backward () method.
4. The last step is to access or print the value of the derivative using grad.
Let see an example of finding derivative
Output:
tensor(326.)
Another example
Output:
tensor(4.) tensor(48.)