如何在Keras中使用TensorFlow指标

dav*_*hab 11 python keras tensorflow tensorflow-gpu keras-2

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

如何在keras模型中使用tensorflow度量函数?

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])
Run Code Online (Sandbox Code Playgroud)

此代码不会抛出任何错误,但mean_iou总是返回0.我相信这是因为不评估up_opt.我已经看到在TF 1.3之前,人们已经建议使用control_flow_ops.with_dependencies([up_opt],score)来实现这一点.这在TF 1.3中似乎不太可能.

总之,如何评估Keras 2.0.6中的TF 1.3指标?这似乎是一个非常重要的特征.

Ish*_*nal 11

你仍然可以使用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
Run Code Online (Sandbox Code Playgroud)