用PyTorch绘制函数的导数?

时间:2018-11-29 19:21:39

标签: python pytorch

我有此代码:

import torch
import matplotlib.pyplot as plt  
x=torch.linspace(-10, 10, 10, requires_grad=True)
y = torch.sum(x**2)
y.backward()
plt.plot(x.detach().numpy(), y.detach().numpy(), label='function')
plt.legend()

但是,我得到了这个错误:

ValueError: x and y must have same first dimension, but have shapes (10,) and (1,)

2 个答案:

答案 0 :(得分:1)

我认为主要问题是您的尺寸不匹配。为什么不使用torch.sum

这应该对您有用:

# %matplotlib inline added this line only for jupiter notebook
import torch
import matplotlib.pyplot as plt  
x = torch.linspace(-10, 10, 10, requires_grad=True)

y = x**2      # removed the sum to stay with the same dimensions
y.backward(x) # handing over the parameter x, as y isn't a scalar anymore
# your function
plt.plot(x.detach().numpy(), x.detach().numpy(), label='x**2')
# gradients
plt.plot(x.detach().numpy(), x.grad.detach().numpy(), label='grad')
plt.legend()

输出图:

enter image description here

您可以通过更多步骤获得更好的图像,我也将间隔更改为torch.linspace(-2.5, 2.5, 50, requires_grad=True)

enter image description here

编辑评论:

此版本可绘制包含torch.sum的渐变:

# %matplotlib inline added this line only for jupiter notebook
import torch
import matplotlib.pyplot as plt  
x = torch.linspace(-10, 10, 10, requires_grad=True)

y = torch.sum(x**2) 
y.backward() 
print(x.grad)
plt.plot(x.detach().numpy(), x.grad.detach().numpy(), label='grad')
plt.legend()

输出:

tensor([-20.0000, -15.5556, -11.1111,  -6.6667,  -2.2222,   2.2222,
      6.6667,  11.1111,  15.5556,  20.0000])

图:

enter image description here

答案 1 :(得分:0)

我假设您想绘制x**2的导数图。

然后,您需要在xx.grad之间绘制图形 xy,即

plt.plot(x.detach().numpy(), x.grad.detach().numpy(), label='function')