KeyError:在Keras中打印history.history.keys()时出现“ val_acc”

时间:2019-02-18 18:13:14

标签: tensorflow keras

model.compile(loss='categorical_crossentropy', optimizer=keras.optimizers.Adam(), metrics=['accuracy'])

history = model.fit_generator(train_generator, batch_size, epochs=epochs)

print(history.history.keys())

结果是:['acc','loss']

accuracy = history.history['acc']
val_accuracy = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(len(accuracy))

这会生成错误:KeyError:'val_acc'

为什么在history.history.keys()中看不到val_acc和val_loss?

2 个答案:

答案 0 :(得分:1)

您没有向model.fit()提供任何验证数据,因此没有验证数据可以计算val_acc。您需要将验证数据添加到您的训练循环中:

history = model.fit_generator(train_generator,
                              batch_size, 
                              epochs,
                              validation_data=validation_generator)

答案 1 :(得分:0)

model.compile(optimizer='adam', loss='categorical_crossentropy',
                                       metrics=['accuracy'])
rnn = model.fit(X_train, y_train, nb_epoch= nb_epoch, batch_size=batch_size, 
                               shuffle=True, validation_data=(X_test, y_test))
score = model.evaluate(X_test, y_test)
print("Test Loss: %.2f%%" % (score[0]*100))
print("Test Accuracy: %.2f%%" % (score[1]*100))