为什么plt.show()与plt.plot不工作?(显示模型训练和测试结果时)
我训练了一个卷积神经网络(CNN)模型,现在想要展示结果。但是,尽管下面的代码没有错误(这是我用matplotlib显示图形的那部分代码),却没有任何图形显示出来。我看了很多教程,但都没有解决我的问题。
以下是代码:
def plot_accuracies(history):
""" Plot the history of accuracies"""
accuracies = [x['val_acc'] for x in history]
plt.plot(accuracies, '-x')
plt.xlabel('epoch')
plt.ylabel('accuracy')
plt.title('Accuracy vs. No. of epochs');
plot_accuracies(history)
def plot_losses(history):
""" Plot the losses in each epoch"""
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.plot(val_losses, '-rx')
plt.xlabel('epoch')
plt.ylabel('loss')
plt.legend(['Training', 'Validation'])
plt.title('Loss vs. No. of epochs');
plot_losses(history)
plt.show()
1 个回答
0
为了更好地控制使用pyplot处理图形的过程,明确地定义对象会比让pyplot在后台处理它们要更有帮助。我建议你尝试将ax和figure对象定义为全局变量,然后在显示之前添加不同的图表。可以这样做:
def plot_losses(history):
""" Plot the losses in each epoch"""
train_losses = [x.get('train_loss') for x in history]
val_losses = [x['val_loss'] for x in history]
ax.plot(train_losses, '-bx') # plot the same way but in the ax object
ax.plot(val_losses, '-rx')
ax.set_xlabel('epoch') # when using ax, most method get "set_"
ax.set_ylabel('loss')
ax.legend(['Training', 'Validation'])
ax.set_title('Loss vs. No. of epochs');
fig,ax = plt.subplots() # define the objects
plot_losses(history)
fig.savefig("losses.pdf") # save figure locally
fig.show() # show figure
你也可以对其他函数做同样的事情。如果你想同时保留两个图表,可以给ax
和fig
对象起不同的名字。