A gradient collects derivatives into a vector, describing how a function changes with respect to each input or parameter. In training, the gradient of the loss tells us how sensitive the error is to each parameter. Updating parameters in the opposite direction can reduce the loss. section 5.4.2 section 5.2
For a linear model with weight w and bias b, the loss gradient has two entries: the derivative with respect to w and the derivative with respect to b. The chain rule connects each parameter to the loss through the model’s predictions. For a mean squared loss, the contribution from each prediction is averaged, and the contributions for each parameter are summed. section 5.4.2
Figure 5.6 Comparing numerical vs. analytical gradient calculation. The numerical approach (arrow through points) estimates the gradient using finite differences between discrete points, while the analytical approach (arrow along the curves) calculates the exact gradient at a specific point.
Finite differences estimate change between nearby points; an analytical derivative calculates change at a point. section 5.4.2
Calculate a gradient with PyTorch
This small linear model starts with w = 1 and b = 0. PyTorch tracks the parameters, computes the mean squared loss, and fills params.grad when backward() is called: import torch x = torch.tensor([1.0, 2.0]) target = torch.tensor([2.0, 4.0]) params = torch.tensor([1.0, 0.0], requires_grad=True) prediction = params[0] * x + params[1] loss = ((prediction - target) ** 2).mean() loss.backward() print(params.grad) # tensor([-5., -3.]) The entries are the loss derivatives for w and b, in that order. section 5.4.2 section 5.5.1
For repeated training steps, clear the previous gradients before calling backward() again. Then update the parameters using the gradient and a learning rate. A torch.no_grad() block keeps that manual update out of the tracked computation. section 5.5.1
# In[9]:
def training_loop(n_epochs, learning_rate, params, t_u, t_c):
for epoch in range(1, n_epochs + 1):
if params.grad is not None: #1
params.grad.zero_()
t_p = model(t_u, *params)
loss = loss_fn(t_p, t_c)
loss.backward()
with torch.no_grad(): #2
params -= learning_rate * params.grad
if epoch % 500 == 0:
print('Epoch %d, Loss %f' % (epoch, float(loss)))
return params
This training loop puts gradient clearing, backward calculation, and parameter updates together. section 5.5.1
The same idea extends to neural networks: after backward(), trainable parameters have gradients, and optimizer.step() updates them. Fixed operations such as tanh have no parameters to update. section 6.3.2



















