出现KeyError问题:'val_acc'

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

这是一个很普遍的错误,但是根据我的设置,我找不到正确的答案。我找到了本教程代码,但是在运行时出现此错误:

val_acc = history.history['val_acc'] 
KeyError: 'val_acc'

fit_generator()函数与fit()不同,不允许进行验证拆分。那么如何解决呢?

这里是代码:

def plot_training(history):
    print (history.history.keys())
    acc = history.history['acc']
    val_acc = history.history['val_acc']
    loss = history.history['loss']
    val_loss = history.history['val_loss']
    epochs = range(len(acc))

    plt.plot(epochs, acc, 'r.')
    plt.plot(epochs, val_acc, 'r')
    plt.title('Training and validation accuracy')

    # plt.figure()
    # plt.plot(epochs, loss, 'r.')
    # plt.plot(epochs, val_loss, 'r-')
    # plt.title('Training and validation loss')
    plt.show()
    plt.savefig('acc_vs_epochs.png')
#....
finetune_model = build_finetune_model(base_model, dropout=dropout, fc_layers=FC_LAYERS, num_classes=len(class_list))
adam = Adam(lr=0.00001)
finetune_model.compile(adam, loss='categorical_crossentropy', metrics=['accuracy'])
filepath="./checkpoints/" + "ResNet50" + "_model_weights.h5"
checkpoint = ModelCheckpoint(filepath, monitor=["acc"], verbose=1, mode='max')
callbacks_list = [checkpoint]

history = finetune_model.fit_generator(train_generator, epochs=NUM_EPOCHS, workers=8, 
                                       steps_per_epoch=steps_per_epoch, 
                                       shuffle=True, callbacks=callbacks_list)

plot_training(history)
python keras deep-learning
1个回答
0
投票

你好,在这里写我的建议,因为我还不能发表评论,

您是正确的fit_generator()功能没有验证拆分属性。因此,您需要创建自己的验证数据集,并通过validation_data=(val_X, val_y)将其提供给拟合生成器,例如::

history = finetune_model.fit_generator(train_generator, epochs=NUM_EPOCHS, workers=8, validation_data=(val_X, val_y),
                                   steps_per_epoch=steps_per_epoch, 
                                   shuffle=True, callbacks=callbacks_list)

希望这会有所帮助。

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