如何创建在tf.estimator.train_and_evaluate评估步骤中持续存在的变量?

时间:2019-08-07 20:30:33

标签: python tensorflow tensorflow-estimator

TLDR:如何创建一个变量,该变量包含用于计算自定义指标的混淆矩阵,并在所有评估步骤中累加值?

have implemented个自定义指标要在tf.estimator.train_and_evaluation管道中使用,并且混淆矩阵作为所有指标的症结所在。我的目标是使这种混淆矩阵在多个评估步骤中持续存在,以便跟踪学习进度。

在变量作用域中使用get_variable无效,因为它没有将变量保存到检查点(或者看起来没有)。

这不起作用:

    @property
    def confusion_matrix(self):
        with tf.variable_scope(
            f"{self.name}-{self.metric_type}", reuse=tf.AUTO_REUSE
        ):
            confusion_matrix = tf.get_variable(
                name="confusion-matrix",
                initializer=tf.zeros(
                    [self.n_classes, self.n_classes],
                    dtype=tf.float32,
                    name=f"{self.name}/{self.metric_type}-confusion-matrix",
                ),
                aggregation=tf.VariableAggregation.SUM,
            )
        return confusion_matrix

仅将矩阵保存为类属性是可行的,但显然并不能在多个步骤中保持不变:

        self.confusion_matrix = tf.zeros(
            [self.n_classes, self.n_classes],
            dtype=tf.float32,
            name=f"{self.name}/{self.metric_type}-confusion-matrix",
        )

您可以查看完整的示例here

我希望这个混淆矩阵在评估期间从头到尾持续存在,但是我不需要在最终的SavedModel中使用它。你能告诉我我怎么能做到吗?我只需要将矩阵保存到外部文件中,还是有更好的方法?

1 个答案:

答案 0 :(得分:0)

您可以定义自定义指标:

def confusion_matrix(labels, predictions):
    matrix = ... # confusion matrix calculation
    mean, update_op = tf.metrics.mean_tensor(matrix)
    # do something with mean if needed
    return {'confusion_matrix': (mean, udpate_op)}

,然后将其添加到您的estimator

estimator = tf.estimator.add_metrics(estimator, confusion_matrix)

如果您需要总和而不是要花钱,则可以从tf.metrics.mean_tensor实施中获取见识

相关问题