【问题标题】:Custom metrics with tf.estimator使用 tf.estimator 自定义指标
【发布时间】:2017-12-11 13:10:29
【问题描述】:

我希望 tensorflow 在评估我的估计器期间计算确定系数(R 平方)。根据官方指标的实现,我尝试通过以下方式松散地实现它:

def r_squared(labels, predictions, weights=None,
              metrics_collections=None,
              updates_collections=None,
              name=None):

    total_error = tf.reduce_sum(tf.square(labels - tf.reduce_mean(labels)))
    unexplained_error = tf.reduce_sum(tf.square(labels - predictions))
    r_sq = 1 - tf.div(unexplained_error, total_error)

    # update_rsq_op = ?

    if metrics_collections:
        ops.add_to_collections(metrics_collections, r_sq)

    # if updates_collections:
    #     ops.add_to_collections(updates_collections, update_rsq_op)

    return r_sq #, update_rsq_op

然后,我将此函数用作 EstimatorSpec 中的度量:

estim_specs = tf.estimator.EstimatorSpec(
    ...
    eval_metric_ops={
        'r_squared': r_squared(labels, predictions),
        ...
    })

但是,这失败了,因为我的 R squared 实现没有返回 update_op。

TypeError: Values of eval_metric_ops must be (metric_value, update_op) tuples, given: Tensor("sub_4:0", dtype=float64) for key: r_squared

现在我想知道,update_op 到底应该做什么?我是否真的需要实现 update_op 或者我可以以某种方式创建某种虚拟 update_op?如果有必要,我将如何实施?

【问题讨论】:

标签: python tensorflow tensorflow-estimator


【解决方案1】:

好的,所以我能够弄清楚。我可以将我的指标包装在一个平均指标中并使用它的 update_op。这似乎对我有用。

def r_squared(labels, predictions, weights=None,
              metrics_collections=None,
              updates_collections=None,
              name=None):

    total_error = tf.reduce_sum(tf.square(labels - tf.reduce_mean(labels)))
    unexplained_error = tf.reduce_sum(tf.square(labels - predictions))
    r_sq = 1 - tf.div(unexplained_error, total_error)

    m_r_sq, update_rsq_op = tf.metrics.mean(r_sq)

    if metrics_collections:
        ops.add_to_collections(metrics_collections, m_r_sq)

    if updates_collections:
        ops.add_to_collections(updates_collections, update_rsq_op)

    return m_r_sq, update_rsq_op

【讨论】:

  • 知道如何在不使用 tf.compat.v1 模块的情况下在 tensorflow 2 中执行此操作吗?
【解决方案2】:

我想我会提到你可以使用tensorflow_addons.metrics.RQsquare()。 Tensorflow Add Ons 是 on PyPi here,文档是 part of Tensorflow here。您所要做的就是将y_shape 设置为输出的形状,通常是(1,) 用于单个输出变量。

【讨论】:

    猜你喜欢
    • 2019-06-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    • 2019-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多