【问题标题】:How can we plot accuracy and loss graphs from a Keras model saved earlier?我们如何从之前保存的 Keras 模型中绘制准确率和损失图?
【发布时间】:2018-06-25 20:30:15
【问题描述】:

有没有办法从之前保存的 CNN 模型中绘制准确率和损失图? 还是只能在训练和评估模型时绘制图表?

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')

【问题讨论】:

    标签: python-3.x keras


    【解决方案1】:

    在 Keras 中保存模型的可用选项都不包括 训练历史,这正是您在这里所要求的。为了保持这个历史可用,你必须对你的训练代码做一些简单的修改,以便单独保存它;这是一个基于 Keras MNIST example 且只有 3 个训练时期的可重现示例:

    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.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)的训练和验证指标(此处为损失和准确性)。

    现在使用Pickle 保存此字典并根据需要恢复它是微不足道的:

    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()
    

    这里的简单检查确认原始变量和检索到的变量确实相同:

    hist.history == history
    # True
    

    【讨论】:

      【解决方案2】:

      这取决于您保存模型的方式。

      一般来说有两种情况,第一种是保存和加载整个模型(包括架构和权重):

      from keras.models import load_model
      
      model.save('my_model.h5')  # creates a HDF5 file 'my_model.h5'
      ...
      model = load_model('my_model.h5')
      

      第二个是只保存权重:

      def create_model():
         model = Sequential() 
         # ... creating the model exactly as it was defined in the training time
      
      # You must create the model since loading only the weights
      model = create_model()
      model.load_weights('my_model_weights.h5')
      

      更多详情请阅读Keras documentation

      【讨论】:

      • 我使用了 model.save('model.h5') 来保存整个模型。现在,如何从这个保存的模型中生成准确率和损失曲线?
      • 加载模型后,使用model.evaluate()。您将获得准确度和损失值,而不是曲线。
      • 您应该考虑将您的最后一条评论添加到您的答案中,因为这实际上解释了如何获得准确度/损失值。
      猜你喜欢
      • 2018-01-03
      • 1970-01-01
      • 2019-03-07
      • 1970-01-01
      • 1970-01-01
      • 2021-06-13
      • 2017-11-13
      • 2017-07-16
      • 2021-05-05
      相关资源
      最近更新 更多