Keras metric produces unexpected values

北慕城南 提交于 2019-12-08 12:18:32

问题


With some help from a previous question I devised the following implementation of IoU:

def iou(y_pred_batch, y_true_batch):
    intersection = tf.zeros(())
    union = tf.zeros(())
    y_pred_batch = np.argmax(y_pred_batch, axis=-1)
    y_true_batch = np.argmax(y_true_batch, axis=-1)
    for i in range(num_classes):
        iTensor = tf.to_int64(tf.fill(y_pred_batch.shape, i))
        intersection = tf.add(intersection, tf.to_float(tf.count_nonzero(tf.logical_and(K.equal(y_true_batch, y_pred_batch), K.equal(y_true_batch, iTensor)))))
        union = tf.add(union, tf.to_float(tf.count_nonzero(tf.logical_or(K.equal(y_true_batch, iTensor), K.equal(y_pred_batch, iTensor)))))
    return intersection/union

I use the following lines to test the code:

sess = tf.InteractiveSession()

y_true_batch = np.asarray([np.random.rand(imRows, imCols, num_classes) for i in range(2)])
y_pred_batch = np.asarray([np.random.rand(imRows, imCols, num_classes) for i in range(2)])

print (iou(y_true_batch, y_pred_batch).eval())
sess.close()

This produces a value of ~0.02, which is to be expected from randomly initialized values. However, when I use this metric in my keras model, the metric returns 1.0000 from epoch 1 onwards, which is obviously wrong. I have no idea why this is and any help would be appreciated.


回答1:


just changed the

np.argmax()

to

from keras import backend as K
K.argmax()

The reason being when you compute using np.argmax() no tensor is created ,the code should be in the language of tensors. you need to perform everything in terms of tensor operations in keras.

for keras testing.

y_true = np.asarray([np.random.rand(4,4, 4) for i in range(2)])
y_pred = np.asarray([np.random.rand(4, 4, 4) for i in range(2)])


iou_value = iou(
    K.variable(y_true),
    K.variable(y_pred),
).eval(session=K.get_session())
print('iou', iou)


来源:https://stackoverflow.com/questions/49865720/keras-metric-produces-unexpected-values

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