liveBook · Manning

Gradient

As explained in Deep Learning with PyTorch, Second Edition

A vector of derivatives describing a function’s change with respect to its inputs or parameters.

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.
figure

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

How Deep Learning with PyTorch, Second Edition covers it

How deep it goes
Derives a linear model’s loss gradient with the chain rule, then implements automatic differentiation and training updates.
Examples
Works through thermometer calibration with a linear model and inspects gradients in a sequential neural network.
What you can do after
Apply gradients via PyTorch autograd and an optimizer to train differentiable models.
How it connects
Connects gradients to loss functions, the chain rule, computation graphs, gradient descent, and neural network parameters.

Also explained in

Compare how 20 books explain gradient →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Deep Learning with PyTorch, Second Edition. The section links point to the parts of the book it draws on.