【问题标题】:Custom Keras Metric throwing error自定义 Keras Metric 抛出错误
【发布时间】:2018-04-16 13:13:05
【问题描述】:

在尝试实现 Intersection over Union (IoU) 时,我遇到了一个似乎无法放置的 python/keras 错误。 在一个单独的文件中,我定义了以下指标:

def computeIoU(y_pred_batch, y_true_batch):
    print y_true_batch.shape[0]
    return np.mean(np.asarray([imageIoU(y_pred_batch[i], y_true_batch[i]) for i in range(y_true_batch.shape[0])]))

def imageIoU(y_pred, y_true):
    y_pred = np.argmax(y_pred, axis=2)
    y_true = np.argmax(y_true, axis=2)
    inter = 0
    union = 0
    for x in range(imCols):
        for y in range(imRows):
            for i in range(num_classes):
                inter += (y_pred[y][x] == y_true[y][x] == i)
                union += (y_pred[y][x] == i or y_true[y][x] == i)
    print inter
    print union
    return float(inter)/union

在主文件中,我已导入函数并使用如下度量:

fcn32_model.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=['accuracy', computeIoU])

抛出的错误是

TypeError: __int__ should return int object

在使用此处的答案中建议的 Keras/tf 语法实施上述算法后,在另一个问题上,代码更改为:

def iou(y_pred_batch, y_true_batch):
    intersection = tf.zeros(())
    union = tf.zeros(())
    y_pred_batch = K.argmax(y_pred_batch, axis=-1)
    y_true_batch = K.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

【问题讨论】:

    标签: python keras metric


    【解决方案1】:

    问题似乎是您尝试以纯整数计算,而不是使用 keras 变量。

    intersection = K.sum(K.abs(y_true * y_pred), axis=-1)
    union_sum = K.sum(K.abs(y_true) + K.abs(y_pred), axis=-1)
    IOU = (intersection) / (union_sum- intersection)
    

    【讨论】:

    • 我看不出它如何产生与我的初始函数相同的结果。大小仍然是二维的,而不是单个值,并且考虑了所有类的值,而不是在某个像素处占主导地位的类。你能详细说明一下这些事情吗?
    • @Kroshtan 请记住,损失函数是直接在计算图中计算的,因此代码应该使用张量的语言。您有问题的代码计算 python 整数,它在计算图之外。这可能是 Keras/Tensorflow 最烦人的限制——你需要用张量运算来表达一切!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-31
    相关资源
    最近更新 更多