欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python matplotlib动画显示

程序员文章站 2022-02-16 19:22:44
...

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