微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐