如何在Keras中使用TensorFlow指标

问题描述 投票:9回答: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指标?这似乎是一个非常重要的特征。

python tensorflow keras tensorflow-gpu keras-2
2个回答
10
投票

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

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

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(...)
© www.soinside.com 2019 - 2024. All rights reserved.