gpt4 book ai didi

python - 用 PyTorch 绘制函数的导数?

转载 作者:行者123 更新时间:2023-12-01 08:40:06 25 4
gpt4 key购买 nike

我有这个代码:

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, require_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])

剧情:

enter image description here

关于python - 用 PyTorch 绘制函数的导数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53546141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com