[英]Plot the derivative of a function with 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,)
我认为主要问题是您的尺寸不匹配。 你为什么不想使用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(), y.detach().numpy(), label='x**2')
# gradients
plt.plot(x.detach().numpy(), x.grad.detach().numpy(), label='grad')
plt.legend()
尽管通过更多步骤,您可以获得更好的图片,我还将间隔稍微更改为torch.linspace(-2.5, 2.5, 50, requires_grad=True)
。
编辑评论:
此版本为您绘制了包含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])
阴谋:
我假设您想绘制x**2
的导数图。
然后,您需要绘制x
和x.grad
NOT x
和y
之间的图形,即
plt.plot(x.detach().numpy(), x.grad.detach().numpy(), label='function')
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.