簡體   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