【问题标题】:How to use TensorFlow metrics in Keras如何在 Keras 中使用 TensorFlow 指标
【发布时间】:2018-02-07 09:31:38
【问题描述】:

似乎已经有几个线程/问题,但在我看来这并没有解决:

How can I use tensorflow metric function within keras models?

https://github.com/fchollet/keras/issues/6050

https://github.com/fchollet/keras/issues/3230

人们似乎在变量初始化或指标为 0 时遇到问题。

我需要计算不同的细分指标,并希望在我的 Keras 模型中包含 tf.metric.mean_iou。这是迄今为止我能想到的最好的:

def mean_iou(y_true, y_pred):
   score, up_opt = tf.metrics.mean_iou(y_true, y_pred, NUM_CLASSES)
   K.get_session().run(tf.local_variables_initializer())
   return score

model.compile(optimizer=adam, loss='categorical_crossentropy', metrics=[mean_iou])

此代码不会抛出任何错误,但 mean_iou 始终返回 0。我相信这是因为未评估 up_opt。我已经看到在 TF 1.3 people have suggested 之前使用类似于 control_flow_ops.with_dependencies([up_opt], score) 的东西来实现这一点。这在 TF 1.3 中似乎不再可能了。

总之,我如何评估 Keras 2.0.6 中的 TF 1.3 指标?这似乎是一个非常重要的功能。

【问题讨论】:

  • 你解决了吗?

标签: python tensorflow keras tensorflow-gpu keras-2


【解决方案1】:

你仍然可以使用control_dependencies

def mean_iou(y_true, y_pred):
   score, up_opt = tf.metrics.mean_iou(y_true, y_pred, NUM_CLASSES)
   K.get_session().run(tf.local_variables_initializer())
   with tf.control_dependencies([up_opt]):
       score = tf.identity(score)
   return score

【讨论】:

  • 这运行但非常慢(与不使用此附加指标编译模型相比慢约 10 倍)。我怀疑这是 score = tf.identity(score) 行的原因。有什么想法吗?
  • 这不是原因,tf.identity 的复杂性是恒定的 (1),它没有任何区别。原因是另一个指标的计算。
  • 这是mean_iou的另一个实现:stackoverflow.com/a/50266195/6897083
  • 如果我尝试这个,我会在get_shape() 上为我的y_pred 收到一个属性错误,因为它是一个 numpy 数组。我需要把它们改成什么吗?
  • 我已经设法在 Keras 中使用 every available metric in Tensorflow 并使用此解决方案将我的代码包装到 python 包 extra-keras-metrics 中。
【解决方案2】:

有 2 个关键可以让这个为我工作。第一个是使用

sess = tf.Session()
sess.run(tf.local_variables_initializer())

在使用 TF 函数(和编译)之后但在执行 model.fit() 之前初始化 TF 变量。您在最初的示例中已经做到了这一点,但大多数其他示例显示 tf.global_variables_initializer(),这对我不起作用。

我发现的另一件事是 op_update 对象,它作为来自许多 TF 指标的元组的第二部分返回,这正是我们想要的。当 TF 指标与 Keras 一起使用时,另一部分似乎为 0。因此,您的 IOU 指标应如下所示:

def mean_iou(y_true, y_pred):
   return tf.metrics.mean_iou(y_true, y_pred, NUM_CLASSES)[1]

from keras import backend as K

K.get_session().run(tf.local_variables_initializer())

model.fit(...)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    • 1970-01-01
    • 2020-07-02
    • 2017-12-12
    相关资源
    最近更新 更多