【问题标题】:Implementing custom keras metric with outside parameter使用外部参数实现自定义 keras 指标
【发布时间】:2021-07-17 05:11:11
【问题描述】:

我想实施一个自定义指标,以使用我的训练集中未包含的值来评估预测,从而在每个时期评估我的模型。

我的指标的想法:

def custom_metric(y_true, y_pred, other_values):
   """
   y_true is training data, binary value
   y_pred is predicted values 
   other_values is an inputted tensor, includes values in (0, 2) """

   Use K backend to return the proper value.
   ...

可能还有其他方法可以进行相同的计算,从而有效地解决相同的问题。其中之一是在每个时期检查模型并在训练完成后运行此分析。但是,我不希望这样做,因为我在 TPU 上进行训练并将权重复制到 CPU 需要在每个 epoch 进行编译,并且需要 100 倍的训练时间。

有人有实现这种技术的聪明方法吗?是采用指标还是其他方法?

【问题讨论】:

    标签: python tensorflow keras


    【解决方案1】:

    答案是使用包装函数:

    def custom_metric(my_variable):
       # 1. conversion of my_variable to tensor
       def metric_name(y_pred, y_true):
          # 2. return tensorflow backend metric, utilizing custom tensor
       return metric_name
    

    【讨论】:

      【解决方案2】:

      您可以继承 Keras Metric 基类,在 __init__ 中提供 other_values,并在 update_state 方法中提供 y_truey_pred

      from tensorflow.keras.metrics import Metric
      
      class CustomMetric(Metric):
          def __init__(self, other_values):
              self.other_values = other_values
              ''' perform any calculations that don't rely on a specific y_true or y_pred
              '''
      
          def update_state(self, y_true, y_pred):
              ''' calculate loss using previously stored self.other_values, etc.
              '''
      

      另一种选择是创建一个自定义层并使用add_metric API。如果您的 other_values 与层的架构相关,或者您需要在中间步骤上执行指标计算,这将特别有用。

      【讨论】:

        猜你喜欢
        • 2016-10-06
        • 2020-02-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多