What is autograd?
- Machine Learning course
- Advanced
- Lesson 19/78
- 5 min
Autograd automatically computes gradients of tensor operations.
What is autograd?
Training neural networks requires knowing the derivative (gradient) of the loss with respect to every parameter. Autograd records the operations performed on tensors and computes these derivatives automatically by applying the chain rule:
x = torch.tensor(3.0, requires_grad=True)
y = x ** 2 + 2 * x # y = x² + 2x
y.backward() # compute dy/dx
print(x.grad.item()) # 8.0 (2x + 2, x = 3)Writing derivatives by hand is impossible in networks with millions of parameters; autograd is the core tool that makes deep learning practical.
What does the gradient tell?
The gradient points in the direction in which the loss increases fastest. Moving the parameter a small step in the opposite direction of the gradient reduces the loss; this is the essence of gradient descent:
w = torch.tensor(5.0, requires_grad=True)
kayip = (w - 2) ** 2 # minimum at w = 2
kayip.backward()
print(w.grad.item()) # 6.0: positive, decrease w
with torch.no_grad():
w -= 0.1 * w.grad # w = 4.4, closer to 2When this loop is repeated thousands of times, the parameters move towards the values that minimise the loss.
Practice First derivative
For x = torch.tensor(2.0, requires_grad=True), compute y = x ** 3 - 4 * x and call backward(). Print y.item() and x.grad.item() on one line.
Starter code
import torch
# buraya yazSample solution
import torch
x = torch.tensor(2.0, requires_grad=True)
y = x ** 3 - 4 * x
y.backward()
print(y.item(), x.grad.item())Expected output
0.0 8.0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 For <code>y = 3 * x ** 2</code>, what is <code>x.grad</code> at x = 2?
- 6
- 24
- 3
- 12 Correct answer
Explanation: dy/dx = 6x; 12 at x = 2.
2 Have the derivatives computed.
kayip.____()
kayip.backward()
Explanation: backward() computes all gradients backwards from the loss.
3 Match the concepts.
| Term | Meaning |
|---|---|
requires_grad |
Its derivative is tracked |
backward() |
Compute gradients |
x.grad |
Computed derivative |
gradient descent |
Step in the opposite direction |