xxxxxxxxxx
# Create a tensor of 1-D array which will be used for evaluating a function
x = torch.linspace(-10, 10, 10, requires_grad = True)
# Create a function to plot
Y = x ** 2
# Compute derivative
y = torch.sum(x ** 2) # Ensure that we have a scalar value for y
y.backward()
# Plot result
plt.plot(x.detach().numpy(), Y.detach().numpy(), label = 'function')
plt.plot(x.detach().numpy(), x.grad.detach().numpy(), label = 'derivative')
plt.xlabel('x')
plt.legend()
plt.show()