使用 pytorch 绘制 sin(x) 的导数
我不确定为什么我的代码没有绘制 cos(x) (是的,我知道 pytorch 有 cos(x) 函数)
import math
import os
import torch
import numpy as np
import matplotlib.pyplot as plt
import random
x = torch.linspace(-math.pi, math.pi, 5000, requires_grad=True)
y = torch.sin(x)
y.backward(x)
x.grad == torch.cos(x) # assert x.grad same as cos(x)
plt.plot(x.detach().numpy(), y.detach().numpy(), label='sin(x)')
plt.plot(x.detach().numpy(), x.grad.detach().numpy(), label='cos(x)') # print derivative of sin(x)
Am unsure why my code does not plot cos(x) (yes, am aware pytorch has cos(x) function)
import math
import os
import torch
import numpy as np
import matplotlib.pyplot as plt
import random
x = torch.linspace(-math.pi, math.pi, 5000, requires_grad=True)
y = torch.sin(x)
y.backward(x)
x.grad == torch.cos(x) # assert x.grad same as cos(x)
plt.plot(x.detach().numpy(), y.detach().numpy(), label='sin(x)')
plt.plot(x.detach().numpy(), x.grad.detach().numpy(), label='cos(x)') # print derivative of sin(x)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要提供上游梯度(等于您案例中的所有梯度)而不是 x 作为 y.backward() 的输入。
因此
You need to feed the upstream gradient (equals to all ones in your case) instead of
x
as input toy.backward()
.Thus