Python matplotlib动画显示

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()
上一篇:html+css笔记12


下一篇:CSS文本超出隐藏、换行、显示三个点