您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python matplotlib动画显示

5b51 2022/1/14 8:16:19 python 字数 3759 阅读 325 来源 www.jb51.cc/python

Pythonmatplotlib动画显示flyfish主要是plt.ion()打开交互plt.ioff()关闭交互plt.pause(0.05)更新和显示当前活动画布,替代了plt.show。importtorchimporttorch.nn.functionalasFimportmatplotlib.pyplotaspltx=torch.unsqueeze(torch.linspace(-1,1,

概述

Python matplotlib动画显示

flyfish

主要是
plt.ion() 打开交互
plt.ioff() 关闭交互
plt.pause(0.05) 更新和显示当前活动画布,替代了plt.show。

import torch
import torch.nn.functional as F
import matplotlib.pyplot as plt

x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1)
y =  x + 0.1 * torch.rand(x.size())

print(x.shape)
print(y.shape)

plt.scatter(x.data.numpy(), y.data.numpy())
plt.show()


class Net(torch.nn.Module):
    def __init__(self, n_feature, n_hidden, n_output):
        super(Net, self).__init__()
        self.hidden = torch.nn.Linear(n_feature, n_hidden)
        self.predict = torch.nn.Linear(n_hidden, n_output)

    def forward(self, x):
        x = F.relu(self.hidden(x))
        x = self.predict(x)
        return x

net = Net(n_feature=1, n_hidden=10, n_output=1)     # define the network
optimizer = torch.optim.SGD(net.parameters(), lr=0.2)
criterion = torch.nn.MSELoss()

plt.ion()#打开交互

for t in range(50):
    model = net(x)
    loss = criterion(model, y)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    if t % 1 == 0:

        plt.cla() # clear the current axes.  clf: clear the entire current figure.
        plt.scatter(x.data.numpy(), y.data.numpy())
        plt.plot(x.data.numpy(), model.data.numpy(), 'r-', lw=5)
        plt.text(0.5, 0, '%d:Loss=%.2f' % (t+1,loss.data.numpy()), fontdict={
  'size': 20, 'color':  'green'})
        plt.pause(0.05) #更新和显示当前活动画布

plt.ioff()#交互关闭不加ioff一闪而过
plt.show()

总结

以上是编程之家为你收集整理的Python matplotlib动画显示全部内容,希望文章能够帮你解决Python matplotlib动画显示所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶