繁体   English   中英

如何在Keras中使用TensorFlow指标

[英]How to use TensorFlow metrics in Keras

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

如何在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])

此代码不会抛出任何错误,但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指标? 这似乎是一个非常重要的特征。

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

有两个关键让我这个工作。 第一个是使用

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(...)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM