简体   繁体   English

用 PyTorch 绘制函数的导数?

[英]Plot the derivative of a function with PyTorch?

I have this code:我有这个代码:

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()

But, I got this error:但是,我收到了这个错误:

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

I think the main problem is that your dimensions do not match.我认为主要问题是您的尺寸不匹配。 Why do you wan't to use torch.sum ?你为什么不想使用torch.sum

This should work for you:这应该适合你:

# %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()

You get a nicer picture though with more steps, I also changed the interval a bit to torch.linspace(-2.5, 2.5, 50, requires_grad=True) .尽管通过更多步骤,您可以获得更好的图片,我还将间隔稍微更改为torch.linspace(-2.5, 2.5, 50, requires_grad=True)

Edit regarding comment:编辑评论:

This version plots you the gradients with torch.sum included:此版本为您绘制了包含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()

Output:输出:

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

Plot:阴谋:

在此处输入图片说明

I'm assuming you want to plot the graph of the derivative of x**2 .我假设您想绘制x**2的导数图。

Then, you need to plot the graph between x and x.grad NOT x and y ie然后,您需要绘制xx.grad NOT xy之间的图形,即

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM