Model Pipeline - Gradient access (.grad)
This pipeline shows how a simple model learns by calculating gradients using PyTorch's .grad attribute. Gradients tell the model how to change its weights to improve predictions.
This pipeline shows how a simple model learns by calculating gradients using PyTorch's .grad attribute. Gradients tell the model how to change its weights to improve predictions.
Loss
10.25 |*
8.00 | *
6.00 | *
4.00 | *
2.56 | *
1.00 | *
0.64 | *
0.16 | *
0.04 | *
----------------
1 2 3 4 5 Epochs| Epoch | Loss ↓ | Accuracy ↑ | Observation |
|---|---|---|---|
| 1 | 10.25 | N/A | Initial loss is high; gradients calculated for first update |
| 2 | 2.56 | N/A | Loss decreased after weight update using gradients |
| 3 | 0.64 | N/A | Loss continues to decrease; gradients guide learning |
| 4 | 0.16 | N/A | Model is learning well; gradients become smaller |
| 5 | 0.04 | N/A | Loss is low; model predictions close to targets |
.grad attribute of a PyTorch tensor represent?.grad in PyTorch.grad attribute stores the gradient of the tensor computed during backpropagation..grad..grad = gradient after backward() [OK]x after backpropagation?.grad attribute, accessed as x.grad.gradient() or get_grad() do not exist for tensors..grad attribute, not methods [OK].grad attribute, not functions [OK]import torch x = torch.tensor(2.0, requires_grad=True) y = x ** 3 z = y + 4 z.backward() print(x.grad)
print(x.grad)?z with respect to xy = x^3 and z = y + 4, the derivative is dz/dx = dy/dx = 3x^2.x=2.0x=2, 3 * (2)^2 = 3 * 4 = 12. So, x.grad will be tensor(12.).import torch x = torch.tensor(3.0, requires_grad=True) y = x ** 2 print(x.grad)
None. Why?backward() on the output tensor.requires_grad=True and missing backward()x has requires_grad=True, the missing step is calling y.backward().y.backward() to compute gradients -> Option Aimport torch x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True) y = (x ** 2).sum() y.backward() print(x.grad)
print(x.grad)?y = sum(x_i^2). The gradient of y with respect to x_i is dy/dx_i = 2x_i.x = [1, 2, 3], gradients are [2*1, 2*2, 2*3] = [2, 4, 6].Pass the test and this pattern moves unknown