Keras指标产生意外值 [英] Keras metric produces unexpected values

查看:127
本文介绍了Keras指标产生意外值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在上一个问题的帮助下,我设计了以下IoU实现:

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

这将产生〜0.02的值,这是随机初始化的值所期望的.但是,当我在keras模型中使用此度量标准时,该度量标准从第1个时期起返回1.0000,这显然是错误的.我不知道为什么会这样,任何帮助将不胜感激.

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.

推荐答案

只是更改了

np.argmax()

from keras import backend as K
K.argmax()

原因是当您使用np.argmax()计算时未创建张量,代码应使用张量语言. 您需要按照keras中的张量操作执行所有操作.

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.

用于keras测试.

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)

这篇关于Keras指标产生意外值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆