预测结果展示-plt.pause()

需求:在预测时显示数据

背景:

在利用模型进行预测时,我们希望预测一个结果,可视化显示一个结果。可是,发现,只有当while(1)循环执行完后,再执行plt.show()才能够绘制所有图像。

不方便!!!

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

# plt.ion()
plt.figure()
plt.imshow(np.arange(256*256).reshape([256,-1]))
#plt.plot(x)
# plt.pause(0.001)
plt.figure()
plt.imshow(np.arange(256*256).reshape([256,-1]))
#plt.plot(x+1)
# plt.pause(0.001)

while(1):
    pass
# plt.ioff()
plt.show()

方法:

网上说plt.ion plt.pause() plt.ioff方法可以解决。验证了下,发现plt.pause直接可以解决。无需plt.ion() plt.ioff(),原理为什么暂时不重要,先能用就行!!!

#%%

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

# plt.ion()
plt.figure()
plt.imshow(np.arange(256*256).reshape([256,-1]))
#plt.plot(x)
plt.pause(0.001)
plt.figure()
plt.imshow(np.arange(256*256).reshape([256,-1]))
#plt.plot(x+1)
plt.pause(0.001)

while(1):
    pass
# plt.ioff()
plt.show()

上面也尝试了plt.plot(),可以使用

import torch import torch.nn as nn import numpy as np import matplotlib.pyplot as plt from torch import autograd """ 用神经网络模拟微分方程,f(x)'=f(x),初始条件f(0) = 1 """ class Net(nn.Module): def __init__(self, NL, NN): # NL n个l(线性,全连接)隐藏层, NN 输入数据的维数, # NL是有多少层隐藏层 # NN是每层的神经元数量 super(Net, self).__init__() self.input_layer = nn.Linear(1, NN) self.hidden_layer = nn.Linear(NN,int(NN/2)) ## 原文这里用NN,我这里用的下采样,经过实验验证,“等采样”更优。更多情况有待我实验验证。 self.output_layer = nn.Linear(int(NN/2), 1) def forward(self, x): out = torch.tanh(self.input_layer(x)) out = torch.tanh(self.hidden_layer(out)) out_final = self.output_layer(out) return out_final net=Net(4,20) # 4层 20个 mse_cost_function = torch.nn.MSELoss(reduction='mean') # Mean squared error 均方误差求 optimizer = torch.optim.Adam(net.parameters(),lr=1e-4) # 优化器 def ode_01(x,net): y=net(x) y_x = autograd.grad(y, x,grad_outputs=torch.ones_like(net(x)),create_graph=True)[0] return y-y_x # y-y' = 0 # requires_grad=True).unsqueeze(-1) plt.ion() # 动态图 iterations=200000 for epoch in range(iterations): optimizer.zero_grad() # 梯度归0 ## 求边界条件的损失函数 x_0 = torch.zeros(2000, 1) y_0 = net(x_0) mse_i = mse_cost_function(y_0, torch.ones(2000, 1)) # f(0) - 1 = 0 ## 方程的损失函数 x_in = np.random.uniform(low=0.0, high=2.0, size=(2000, 1)) pt_x_in = autograd.Variable(torch.from_numpy(x_in).float(), requires_grad=True) # x 随机数 pt_y_colection=ode_01(pt_x_in,net) pt_all_zeros= autograd.Variable(torch.from_numpy(np.zeros((2000,1))).float(), requires_grad=False) mse_f=mse_cost_function(pt_y_colection, pt_all_zeros) # y-y' = 0 loss = mse_i + mse_f loss.backward() # 反向传播 optimizer.step() # 优化下一步。This is equivalent to : theta_new = theta_old - alpha * derivative of J w.r.t theta if epoch%1000==0: y = torch.exp(pt_x_in) # y 真实值 y_train0 = net(pt_x_in) # y 预测值 print(epoch, "Traning Loss:", loss.data) print(f'times {epoch} - loss: {loss.item()} - y_0: {y_0}') plt.cla() plt.scatter(pt_x_in.detach().numpy(), y.detach().numpy()) plt.scatter(pt_x_in.detach().numpy(), y_train0.detach().numpy(),c='red') plt.pause(0.1)
02-15
import torch import torch.nn as nn import numpy as np import torch.nn.functional as F import matplotlib.pyplot as plt from torch.autograd import Variable x=torch.tensor(np.array([[i] for i in range(10)]),dtype=torch.float32) y=torch.tensor(np.array([[i**2] for i in range(10)]),dtype=torch.float32) #print(x,y) x,y=(Variable(x),Variable(y))#将tensor包装一个可求导的变量 net=torch.nn.Sequential( nn.Linear(1,10,dtype=torch.float32),#隐藏层线性输出 torch.nn.ReLU(),#激活函数 nn.Linear(10,20,dtype=torch.float32),#隐藏层线性输出 torch.nn.ReLU(),#激活函数 nn.Linear(20,1,dtype=torch.float32),#输出层线性输出 ) optimizer=torch.optim.SGD(net.parameters(),lr=0.05)#优化器(梯度下降) loss_func=torch.nn.MSELoss()#最小均方差 #神经网络训练过程 plt.ion() plt.show()#动态学习过程展示 for t in range(2000): prediction=torch.tensor(net(x)),#把数据输入神经网络,输出预测值 loss=loss_func(prediction, y)#计算二者误差,注意这两个数的顺序 optimizer.zero_grad()#清空上一步的更新参数值 loss.backward()#误差反向传播,计算新的更新参数值 optimizer.step()#将计算得到的更新值赋给net.parameters()D:\Anaconda\python.exe D:\py\text.py D:\py\text.py:26: UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor). prediction=torch.tensor(net(x)),#把数据输入神经网络,输出预测值 Traceback (most recent call last): File "D:\py\text.py", line 27, in <module> loss=loss_func(prediction, y)#计算二者误差,注意这两个数的顺序 File "D:\Anaconda\lib\site-packages\torch\nn\modules\module.py", line 1194, in _call_impl return forward_call(*input, **kwargs) File "D:\Anaconda\lib\site-packages\torch\nn\modules\loss.py", line 536, in forward return F.mse_loss(input, target, reduction=self.reduction) File "D:\Anaconda\lib\site-packages\torch\nn\functional.py", line 3281, in mse_loss if not (target.size() == input.size()): AttributeError: 'tuple' object has no attribute 'size'
05-31
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值