【问题标题】:Access loss and model in a custom callback在自定义回调中访问丢失和模型
【发布时间】:2020-12-15 08:01:19
【问题描述】:

我阅读了这个https://www.tensorflow.org/guide/keras/custom_callback,但我不知道如何获取所有其他参数。

这是我的代码

 (hits, ndcgs) = evaluate_model(model, testRatings, testNegatives, topK, evaluation_threads)
  hr, ndcg, loss = np.array(hits).mean(), np.array(ndcgs).mean(), hist.history['loss'][0]
  print('Iteration %d [%.1f s]: HR = %.4f, NDCG = %.4f, loss = %.4f [%.1f s]' 
                  % (epoch,  t2-t1, hr, ndcg, loss, time()-t2))
 if hr > best_hr:
     best_hr, best_ndcg, best_iter = hr, ndcg, epoch
 if args.out > 0:
     model.save(model_out_file, overwrite=True)

如您所见,我需要 modelhistmodel.save。 有没有办法在自定义回调中使用这三个参数? 这样我就可以将所有这些写入自定义回调中。

class CustomCallback(keras.callbacks.Callback):

   def on_epoch_end(self, logs=None):
       keys = list(logs.keys())
       print("Stop training; got log keys: {}".format(keys))

【问题讨论】:

    标签: python tensorflow keras callback


    【解决方案1】:

    模型是attribute of tf.keras.callbacks.Callback,因此您可以直接使用self.model 访问它。要访问损失的值,您可以使用传递给methods of tf.keras.callbacks.Callback 的“logs”对象,该对象将包含一个名为“loss”的键。

    如果您需要访问其他变量(在训练期间不会更改),那么您可以将它们设置为回调的实例变量,并通过定义 __init__ 函数在构造回调时添加它们.

    class CustomCallback(keras.callbacks.Callback):
       def __init__(self, testRatings, testNegatives, topK, evaluation_threads):
           super().__init__()
           self.testRatings = testRatings
           self.testNegatives = testNegatives
           self.topK = topK
           self.evaluation_threads = evaluation_threads
    
       def on_epoch_end(self, epoch, logs=None):
           logs = logs or {}
           current_loss = logs.get("loss")
           if current_loss:
               print("my_loss: ", current_loss)
           print("my_model", self.model)
           # the attributes are accessble with self
           print("my topK atributes", self.topK)
    
    # you can then create the callback by passing the correct attributes
    my_callback = CustomCallback(testRatings, testNegatives, topK, evaluation_threads)
    

    注意:如果您要做的是在每个时期之间评估模型,并在模型获得最佳指标时保存模型,我建议您看一下:

    【讨论】:

    • 非常感谢!那么selfmodel 吗?我还可以保存 model 并获取 model 吗?我很抱歉,代码应该在每个时代结束时都这样做。
    • 您可以定义on_epoch_end 方法在每个时期执行此操作。 self 是引用对象的关键字,参见python documentation,因此在这种情况下,它引用回调对象。如果要保存模型,可以通过属性访问模型,self.model.save("/path/to/saved_model") 就可以了。
    • 非常感谢您的回答!是否还有将参数传递给回调的选项?例如,我在这里使用testRatings, testNegatives, topK, evaluation_threads。这可以传递给回调吗?
    • 是的,您可以在回调的 __init__ 函数(构造函数)中传递它。它们可以作为“实例变量”访问,您可以在 python documentation 中了解更多信息
    • 谢谢,我读到了。不幸的是,我不明白。你能给我看一个代码示例吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-20
    • 2021-01-15
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    相关资源
    最近更新 更多