【问题标题】:Custom Metrics Keras [duplicate]自定义指标 Keras [重复]
【发布时间】:2020-03-04 02:29:39
【问题描述】:

我需要帮助才能在 keras 中创建自定义指标。我需要计算我的错误等于零的次数(y_pred - y_true = 0)。

我试过这个:

n_train = 1147 # Number of samples on training set
c = 0 # Variable to count
def our_metric(y_true, y_pred):
  if y_true-y_pred == 0:
    c += 1
  return c/n_train

但是我收到了这个错误:

OperatorNotAllowedInGraphError: 使用 tf.Tensor 作为 Python bool 在 Graph 执行中是不允许的。使用 Eager 执行或装饰 这个函数带有@tf.function。

编辑:使用此处提出的解决方案:

Creating custom conditional metric with Keras

我这样解决了我的问题:

c = tf.constant(0)
def our_metric(y_true, y_pred):
  mask = K.equal(y_pred, y_true) # TRUE if y_pred = y_true
  mask = K.cast(mask,K.floatx())
  s = K.sum(mask)
  return s/n_train

【问题讨论】:

标签: keras metrics


【解决方案1】:

您不能在普通的tensorflow 中运行 Python 比较(使用静态图)。

您必须启用eager mode,这是一个包装器,可以让您使用一些 Python 控制语句(如ifloop)。只需按照错误提示装饰您的函数或在脚本开头发出tf.enable_eager_execution()

您可能还想更新您的代码以使用tf2.0,它更直观并且默认开启了渴望模式。

【讨论】:

    【解决方案2】:

    有多种方法可以使用 Keras 后端函数来计算一个值等于零的次数。你只需要跳出框框思考一下。这是一个例子:

    diff = y_true - y_pred
    count = K.sum(K.cast(K.equal(diff, K.zeros_like(diff)), 'int8'))
    

    还可以使用tf.count_nonzero 操作,但混合使用 keras 和显式 tensorflow 可能会导致问题。

    【讨论】:

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