plt.show()搭配plt.plot无图像显示?CNN模型训练结果可视化问题
解决Matplotlib绘图无显示问题的常见方案
检查Matplotlib后端配置
部分环境(如远程服务器、Jupyter Notebook)默认后端不支持交互式显示。可在代码开头添加配置:import matplotlib matplotlib.use('TkAgg') # 可选'Qt5Agg',根据环境适配 import matplotlib.pyplot as plt若使用Jupyter Notebook,添加魔法命令
%matplotlib inline(仅在Notebook环境生效)。验证
history数据有效性
绘图依赖history中的指标数据,若accuracies、train_losses或val_losses为空列表、全NaN,Matplotlib会生成空画布,看似无图像输出。可在函数内添加打印验证:def plot_accuracies(history): accuracies = [x['val_acc'] for x in history] print("验证集准确率数据:", accuracies) plt.plot(accuracies, '-x') plt.xlabel('epoch') plt.ylabel('accuracy') plt.title('Accuracy vs. No. of epochs');若数据为空,需确认模型训练时是否正确传入
validation_data参数(以Keras为例),否则不会生成val_acc、val_loss这类验证指标。避免绘图重叠覆盖
连续调用两个绘图函数却未新建画布,第二个图会覆盖第一个。在每个绘图函数开头添加plt.figure(),让两张图独立显示:def plot_accuracies(history): plt.figure() accuracies = [x['val_acc'] for x in history] plt.plot(accuracies, '-x') # 其余代码不变 def plot_losses(history): plt.figure() train_losses = [x.get('train_loss') for x in history] val_losses = [x['val_loss'] for x in history] plt.plot(train_losses, '-bx') # 其余代码不变确认
plt.show()的执行逻辑
确保plt.show()在所有绘图代码之后执行,且脚本未被提前终止。若在函数内部已调用过plt.show(),外部重复调用可能失效,但你的代码仅在最后调用一次,此点无需调整。
内容的提问来源于stack exchange,提问作者user23508862
相关产品推荐
相关产品推荐

