【问题标题】:Error during compiling a Keras model with own loss function使用自己的损失函数编译 Keras 模型时出错
【发布时间】:2020-02-01 23:12:55
【问题描述】:

当我尝试在 Keras 中编译一个带有来自 here 的损失函数的模型时,我遇到了一个错误

ValueError:形状必须为 2 级,但对于输入形状为 [?]、[?] 的“loss/activation_10_loss/MatMul”(操作:“MatMul”)为 1 级。

我已尝试在this 回答后修复此错误。

def get_loss_function(weights):
    def loss(y_pred, y_true):
        return (y_pred - y_true) * weights # or whatever your loss function   should be
    return loss
 model.compile(loss=get_loss_function(conv_weights), optimizer=SGD(lr=0.1))

复制问题的最简单方法:

from segmentation_models.metrics import iou_score
from segmentation_models import Unet
import keras

class Losses:

    def __init__(self):
        pass
    @staticmethod
    def IoULoss(targets, inputs, smooth=1e-6):
        logger=logging.getLogger("Losses.IoULoss")
        logger.setLevel(Debug_param.debug_scope())
        # flatten label and prediction tensors
        # logger.critical(("targets.shape",targets.get_shape().as_list(), "inputs.shape",inputs.shape))
        inputs = K.flatten(inputs)
        targets = K.flatten(targets)
        logger.critical(("flatten", "targets.shape", targets.shape, "inputs.shape", inputs.shape))

        intersection = K.sum(K.dot(targets, inputs))
        total = K.sum(targets) + K.sum(inputs)
        union = total - intersection

        IoU = (intersection + smooth) / (union + smooth)
        return 1 - IoU

model = Unet("resnet34", backend=None, classes=1, activation='softmax')
opt = keras.optimizers.Adam(lr=config.lr)
model.compile(loss=Losses.IoULoss, optimizer=opt,
                      metrics=[iou_score, "accuracy"])

如何编译带有自定义损失函数的模型或如何防止错误?

Python 版本 3.7.4、keras 2.3.0、TF 1.14、分段模型 0.2.1

【问题讨论】:

    标签: python tensorflow keras semantic-segmentation


    【解决方案1】:

    当我重现您的错误时,我发现问题出现在函数 K.dot() 上。看起来 Keras 期望该函数有两个 2 阶张量(即矩阵或 2D 数组)。您正在使用K.flatten()inputstargets 转换为一维张量(向量)。下面是如何从数据中生成 2D 张量的示例:

    inputs = K.reshape(inputs, [1, -1]) # 1 row, as many columns as needed
    targets = K.reshape(targets, [-1, 1]) # 1 column, as many rows as needed
    
    

    【讨论】:

    • 谢谢!这解决了这个问题。没有这些转换,还有其他方法可以编写损失函数吗?
    • 我不完全确定,但是当我运行您的代码并将转换注释掉时,它编译得很好......
    猜你喜欢
    • 2020-09-07
    • 1970-01-01
    • 2020-09-08
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    • 2020-04-09
    • 2020-10-07
    • 2020-06-21
    相关资源
    最近更新 更多