Before you start
Get PyTorch to compute a derivative for you.
For f(x) = 3x^2 + 2x, return df/dx at each value in x_values, using
autograd rather than the derivative you can do in your head.
The mechanics:
x = torch.tensor(x_values, dtype=torch.float32, requires_grad=True)
y = 3 * x ** 2 + 2 * x
y.sum().backward()
x.grad
requires_grad=True is what makes torch record the operations. backward()
walks that recording in reverse and accumulates the result into x.grad.
Calling backward() needs a scalar, because a gradient is only defined
against one number. Summing first is the usual trick: each element of x
affects exactly one element of y, so d(sum)/dx_i is dy_i/dx_i, which is
what you wanted.
Return a tensor of shape (n,). You have already written this derivative by
hand in the calculus problems; the point here is to see the same answer arrive
without you deriving it.
def grad_of_quadratic(x_values):
Input
grad_of_quadratic([0.0, 1.0, 2.0])
Output
tensor([ 2., 8., 14.])
Reasoning
df/dx = 6x + 2, which gives 2, 8 and 14 at 0, 1 and 2. Autograd finds the same values without you writing the derivative.
backward() on a scalar, so sum y first.(n,).Run it in Colab
Google Colab runs real PyTorch without a local installation. Get a code, open the notebook, and paste the code into its first cell. Grading happens there and the result comes back here.
If no runtime is available, save a copy in Drive and retry later, or choose Your machine. These exercises work on CPU; a GPU is optional. Connection help ↗
Run PyTorch on your machine?
In Colab, the grading cell is your Submit. It runs the hidden cases there, and the result shows here on its own.
⇧↵run cell