TLDR:如何创建一个包含用于计算自定义度量的混淆矩阵的变量,在所有评估步骤中积累值?
我将在已实施管道中使用自定义度量,并将混淆矩阵作为它们的关键。我的目标是使这个混淆矩阵在多个评估步骤中持续存在,以便跟踪学习进度。
在变量作用域中使用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",
)您可以查看完整的示例这里。
我希望在评估过程中,这种混乱的矩阵会从头到尾持续存在,但我不需要在最终的SavedModel中使用它。你能告诉我怎么做到这一点吗?我是否需要将矩阵保存到外部文件,还是有更好的方法?
发布于 2019-08-07 21:20:28
您可以定义一个自定义度量:
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)如果您需要sum而不是meen,您可以从tf.metrics.mean_tensor实现中了解
https://stackoverflow.com/questions/57401924
复制相似问题