为什么 plt.show() 不能与 plt.plot 一起使用? (展示模型训练和测试结果时)

问题描述 投票:0回答:1

我已经训练了一个 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()
python matplotlib keras
1个回答
0
投票

为了在使用 pyplot 操作图形时获得更多控制,显式定义对象而不是让 pyplot 在后台处理它们是有用的。我建议您尝试全局定义斧头和图形对象,然后在显示之前添加不同的绘图。像这样的东西:


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
对象。

© www.soinside.com 2019 - 2024. All rights reserved.