How to use TensorFlow metrics in Keras

爷,独闯天下 提交于 2019-11-27 14:46:39

you can still usecontrol_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

There were 2 keys to getting this working for me. The first was using

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

To initialize TF variables after using the TF functions (and compiling), but before doing model.fit(). You've got that in your initial example, but most other examples show tf.global_variables_initializer(), which didn't work for me.

The other thing I discovered is the op_update object, which is returned as the second part of the tuple from many TF metrics, is what we want. The other portion seems to be 0 when TF metrics are used with Keras. So your IOU metric should look like:

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(...)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!