我有此代码:
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,)
答案 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()
输出图:
您可以通过更多步骤获得更好的图像,我也将间隔更改为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])
图:
答案 1 :(得分:0)
我假设您想绘制x**2
的导数图。
然后,您需要在x
和x.grad
之间绘制图形不 x
和y
,即
plt.plot(x.detach().numpy(), x.grad.detach().numpy(), label='function')
。