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

查看:37
本文介绍了我们如何从之前保存的 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天全站免登陆