如何在Keras中使用TensorFlow指标

时间:2017-08-29 19:54:15

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

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

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指标?这似乎是一个非常重要的特征。

2 个答案:

答案 0 :(得分:8)

您仍然可以使用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

答案 1 :(得分:0)

有2个键可以使它对我有效。首先是使用

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

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

我发现的另一件事是op_update对象,它是我们从许多TF指标中作为元组的第二部分返回的。当Keras使用TF度量时,另一部分似乎为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(...)