本文记录学习过程中遇到的问题、我的解决过程以及学习心得,如有错误之处,欢迎指正!
最近在学习莫烦pytorch教程时遇到错误:ValueError: max() arg is an empty sequence。
运行环境是pycharm2018.3.5,python版本是3.5,加载了anaconda的解释器。具体代码如下:
plt.ion() # 设置实时打印
# plt.show()
optimizer = torch.optim.SGD(net.parameters(), lr = 0.5) # SGD优化神经网络
loss_func = torch.nn.MSELoss() # 用均方差做损失函数
for t in range(200): # 训练200步
prediction = net(x) # 每一步的预测
loss = loss_func(prediction, y) # 调用损失函数需要预测值在前,真实值在后,否则会影响结果
optimizer.zero_grad() # 先将所有梯度设为0
loss.backward() # 反向传递过程,计算出每个节点的梯度
optimizer.step() # 以学习效率为0.5的参数优化梯度
# 每5步打印一次
if t % 5 == 0:
# 打印数据
plt.cla()
plt.scatter(x.data.numpy(), y.data.numpy())
plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw = 5)
plt.text(0.5, 0, 'Loss=%.4f' % loss.data.numpy(), fontdict={'size': 20, 'color': 'red'})
plt.pause(0.1)
plt.ioff()
plt.show()
完整的报错内容是:
Traceback (most recent call last):
File "D:/My_Projects/pytorch_Learning/activation_function_Learning.py", line 47, in
plt.cla()
File "D:\Anaconda3\lib\site-packages\matplotlib\pyplot.py", line 3546, in cla
ret = gca().cla()
File "D:\Anaconda3\lib\site-packages\matplotlib\pyplot.py", line 936, in gca
return gcf().gca(**kwargs)
File "D:\Anaconda3\lib\site-packages\matplotlib\pyplot.py", line 586, in gcf
return figure()
File "D:\Anaconda3\lib\site-packages\matplotlib\pyplot.py", line 557, in figure
draw_if_interactive()
File "D:\PyCharm 2018.3.5\helpers\pycharm_matplotlib_backend\backend_interagg.py", line 39, in draw_if_interactive
figManager.canvas.show()
File "D:\PyCharm 2018.3.5\helpers\pycharm_matplotlib_backend\backend_interagg.py", line 62, in show
self.figure.tight_layout()
File "D:\Anaconda3\lib\site-packages\matplotlib\figure.py", line 1752, in tight_layout
rect=rect)
File "D:\Anaconda3\lib\site-packages\matplotlib\tight_layout.py", line 322, in get_tight_layout_figure
max_nrows = max(nrows_list)
ValueError: max() arg is an empty sequence
跑了一下教程给的代码仍然有这个问题,根据索引找到了anaconda里的文件tight_layout.py中的出错地方
max_nrows = max(nrows_list)
max_ncols = max(ncols_list)
根据百度到的解决方案改成max((),default=0)仍然不能解决,并且修改项目目录之外的文件会引发更多的问题,所以放弃这个办法。
最后发现是pycharm设置的问题,在菜单栏File-Setting-Tools-Python Scientific中去除勾选Show plots in tool window即可解决问题。具体原因我猜想是pycharm的tool window里的图像显示不支持动态显示图像(因为之前直接使用plt.plot()都是正常的)