我们如何从先前保存的Keras模型中绘制准确性和损失图? [英] How can we plot accuracy and loss graphs from a Keras model saved earlier?

查看:507
本文介绍了我们如何从先前保存的Keras模型中绘制准确性和损失图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以从之前保存的CNN模型中绘制准确性和损失图? 还是只能在训练和评估模型期间绘制图形?

Is there a way to plot accuracy and loss graphs from the CNN model saved earlier? Or can we only plot graphs during training and evaluating the model?

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(_NUM_CLASSES, activation='softmax'))
model.compile(optimizer='rmsprop', loss='categorical_crossentropy',metrics= 
              ["accuracy"])
model.fit(x_train, y_train,
          batch_size=_BATCH_SIZE,
          epochs=_EPOCHS,
          verbose=1,
          validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
model.save('model.h5')

推荐答案

在Keras中保存模型的可用选项均未包含培训历史记录,这正是您在这里要的.为了使此历史记录可用,您必须对培训代码进行一些琐碎的修改,以便分别保存.这是一个基于Keras的可复制示例, MNIST示例并且只有3个训练时期:

None of the available options for saving models in Keras includes the training history, which is what exactly you are asking for here. To keep this history available, you have to do some trivial modifications to your training code so as to save it separately; here is a reproducible example based on the Keras MNIST example and only 3 training epochs:

hist = model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=3,
          verbose=1,
          validation_data=(x_test, y_test))

hist是Keras回调,它包含一个history词典,其中包含您要查找的指标:

hist is a Keras callback, and it includes a history dictionary, which contains the metrics you are looking for:

hist.history
# result:
{'acc': [0.9234666666348775, 0.9744000000317892, 0.9805999999682109],
 'loss': [0.249011807457606, 0.08651042315363884, 0.06568188704450925],
 'val_acc': [0.9799, 0.9843, 0.9876],
 'val_loss': [0.06219216037504375, 0.04431889447008725, 0.03649089169385843]}

即培训与培训每个训练时期(此处为3)的验证指标(此处为损失和准确性).

i.e. the training & validation metrics (here loss & accuracy) for each one of the training epochs (here 3).

现在使用 Pickle 保存该字典很简单,根据需要将其还原:

Now it is trivial to save this dictionary using Pickle, and to restore it as required:

import pickle

# save:
f = open('history.pckl', 'wb')
pickle.dump(hist.history, f)
f.close()

# retrieve:    
f = open('history.pckl', 'rb')
history = pickle.load(f)
f.close()

在此处进行简单检查即可确认原始变量和检索到的变量确实相同:

A simple check here confirms that the original and the retrieved variables are indeed identical:

hist.history == history
# True

这篇关于我们如何从先前保存的Keras模型中绘制准确性和损失图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆