Python 使用外部参数实现自定义keras度量

Python 使用外部参数实现自定义keras度量,python,tensorflow,keras,Python,Tensorflow,Keras,我想实现一个自定义指标,使用训练集中未包含的值来评估预测,以每个历元为基础评估模型 我的度量标准的想法是: 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) """

我想实现一个自定义指标,使用训练集中未包含的值来评估预测,以每个历元为基础评估模型

我的度量标准的想法是:

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需要在每个历元编译,并且需要100倍的训练时间


有人有一个聪明的方法来实现这个技术吗?无论是在度量还是其他方法中?

答案是使用包装函数:

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