Python 在 keras 中绘制学习曲线给出 KeyError: 'val_acc'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39883331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:52:06  来源:igfitidea点击:

Plotting learning curve in keras gives KeyError: 'val_acc'

pythonmachine-learningclassificationpattern-recognition

提问by Data Pagla

I was trying to plot train and test learning curve in keras, however, the following code produces KeyError: 'val_acc error.

我试图在 keras 中绘制训练和测试学习曲线,但是,以下代码生成KeyError: 'val_acc error.

The official document <https://keras.io/callbacks/>states that in order to use 'val_acc'I need to enable validation and accuracy monitoring which I dont understand and dont know how to use in my code.

官方文档<https://keras.io/callbacks/>指出,为了使用'val_acc'我需要启用验证和准确性监控,我不理解也不知道如何在我的代码中使用。

Any help would be much appreciated. Thanks.

任何帮助将非常感激。谢谢。

seed = 7
np.random.seed(seed)

dataframe = pandas.read_csv("iris.csv", header=None)
dataset = dataframe.values
X = dataset[:,0:4].astype(float)
Y = dataset[:,4]

encoder = LabelEncoder()
encoder.fit(Y)
encoded_Y = encoder.transform(Y)
dummy_y = np_utils.to_categorical(encoded_Y)

kfold = StratifiedKFold(y=Y, n_folds=10, shuffle=True, random_state=seed)
cvscores = []

for i, (train, test) in enumerate(kfold):

    model = Sequential()
    model.add(Dense(12, input_dim=4, init='uniform', activation='relu'))
    model.add(Dense(3, init='uniform', activation='sigmoid'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    history=model.fit(X[train], dummy_y[train], nb_epoch=200, batch_size=5, verbose=0)
    scores = model.evaluate(X[test], dummy_y[test], verbose=0)
    print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
    cvscores.append(scores[1] * 100)

print( "%.2f%% (+/- %.2f%%)" % (np.mean(cvscores), np.std(cvscores))) 


print(history.history.keys())
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()

回答by driedler

Looks like in Keras + Tensorflow 2.0 val_accwas renamed to val_accuracy

看起来在 Keras + Tensorflow 2.0 中val_acc被重命名为val_accuracy

回答by thanvaf

You may need to enable the validation split of your trainset. Usually, the validation happens in 1/3 of the trainset. In your code, make the change as given below:

您可能需要启用训练集的验证拆分。通常,验证发生在训练集的 1/3 中。在您的代码中,进行如下更改:

history=model.fit(X[train], dummy_y[train],validation_split=0.33,nb_epoch=200, batch_size=5, verbose=0) 

It works!

有用!

回答by user11992433

history_dict = history.history
print(history_dict.keys())

if u print keys of history_dict, you will get like this dict_keys(['loss', 'acc', 'val_loss', 'val_acc']).

如果你打印 history_dict 的键,你会得到这样的dict_keys(['loss', 'acc', 'val_loss', 'val_acc'])

and edit a code like this

并编辑这样的代码

acc = history_dict['acc']
val_acc = history_dict['val_acc']
loss = history_dict['loss']
val_loss = history_dict['val_loss']

Keys and error

键和错误

回答by Mohammad Nur Nobi

If you upgrade keras older version (e.g. 2.2.5) to 2.3.0 (or newer) which is compatible with Tensorflow 2.0, you might have such error (e.g. KeyError: 'acc'). Both accand val_acchas been renamed to accuracyand val_accuracyrespectively. Renaming them in script will solve the issue.

如果您将 keras 旧版本(例如 2.2.5)升级到与 Tensorflow 2.0 兼容的 2.3.0(或更新版本),您可能会遇到这样的错误(例如 KeyError: 'acc')。无论ACCval_acc已更名为准确性val_accuracy分别。在脚本中重命名它们将解决问题。

回答by sajid

The main point everyone misses to mention is that this Key Erroris related to the naming of metrics during model.compile(...). You need to be consistent with the way you name your accuracy metric inside model.compile(....,metrics=['<metric name>']). Your history callback object will receive the dictionary containing key-value pairs as defined in metrics.

每个人都没有提到的要点是,这个关键错误model.compile(...). 你需要与你在里面命名你的准确度指标的方式保持一致model.compile(....,metrics=['<metric name>'])。您的历史回调对象将接收包含指标中定义的键值对的字典。

So, if your metric is metrics=['acc'], you can access them in history object with history.history['acc']but if you define metric as metrics=['accuracy'], you need to change to history.history['accuracy']to access the value, in order to avoid Key Error. I hope it helps.

因此,如果您的指标是metrics=['acc'],您可以在历史对象中访问它们,history.history['acc']但如果您将指标定义为metrics=['accuracy'],则需要更改为history.history['accuracy']来访问该值,以避免Key Error。我希望它有帮助。

N.B. Here's a link to the metricsyou can use in Keras.

注意这是您可以在 Keras 中使用的指标链接

回答by Elior B.Y.

to get any val_* data (val_acc, val_loss, ...), you need to first set the validation.

要获取任何 val_* 数据 ( val_acc, val_loss, ...),您需要先设置验证。

first method (will validate from what you give it):

第一种方法(将根据您提供的内容进行验证):

model.fit(validation_data=(X_test, Y_test))

second method (will validate from a part of the training data):

第二种方法(将从训练数据的一部分进行验证):

model.fit(validation_split=0.5) 

回答by Tshilidzi Mudau

This error also happens when you specify the validation_data=(X_test, Y_test)and your X_testand/or Y_testare empty. To check this, print the shape of X_testand Y_testrespectively. In this case, the model.fit(validation_data=(X_test, Y_test), ...)method ran but because the validation set was empty, it didn't create a dictionary key for val_lossin the history.historydictionary.

当您指定validation_data=(X_test, Y_test)and your X_testand/orY_test为空时,也会发生此错误。要对此进行检查,打印的形状X_testY_test分别。在这种情况下,该model.fit(validation_data=(X_test, Y_test), ...)方法运行,但因为验证组是空的,它并没有为创建辞典键val_losshistory.history辞典。