python - 如何访问生成器提供的 Keras 自定义损失函数中的样本权重?

标签 python tensorflow keras deep-learning loss-function

我有一个生成器函数,它无限循环某些图像目录并输出 3 元组的批处理形式

[img1, img2], label, weight

其中 img1img2batch_size x M x N x 3 张量,labelweight 是每个 batch_size x 1 张量。

在使用 Keras 训练模型时,我将此生成器提供给 fit_generator 函数。

对于这个模型,我有一个自定义的余弦对比损失函数,

def cosine_constrastive_loss(y_true, y_pred):
    cosine_distance = 1 - y_pred
    margin = 0.9
    cdist = y_true * y_pred + (1 - y_true) * keras.backend.maximum(margin - y_pred, 0.0)
    return keras.backend.mean(cdist)

从结构上讲,我的模型一切正常。没有错误,它正在按预期使用来自生成器的输入和标签。

但现在我正在寻求直接使用每个批处理的权重参数,并根据特定于样本的权重在 cosine_contrastive_loss 中执行一些自定义逻辑。

如何在执行损失函数时从一批样本的结构中访问这个参数?

请注意,由于它是一个无限循环的生成器,因此无法预先计算权重或即时计算它们以将权重套合到损失函数中或生成它们。

它们必须与正在生成的样本一致地生成,而且我的数据生成器中确实有自定义逻辑,可以根据 img1img2 的属性动态确定权重> 和 label 是为批处理生成的。

最佳答案

手动训练循环替代方案

我唯一能想到的就是手动训练循环,您可以自己获取权重。

有一个权重张量和一个非可变批量大小:

weights = K.variable(np.zeros((batch_size,)))

在您的自定义损失中使用它们:

def custom_loss(true, pred):
    return someCalculation(true, pred, weights)

对于“生成器”:

for e in range(epochs):
    for s in range(steps_per_epoch):
        x, y, w = next(generator) #or generator.next(), not sure
        K.set_value(weights, w)

        model.train_on_batch(x, y)

对于 keras.utils.Sequence:

for e in range(epochs):
    for s in range(len(generator)):
        x,y,w = generator[s]

        K.set_value(weights, w)
        model.train_on_batch(x,y)

我知道这个答案不是最优的,因为它不会像 fit_generator 那样并行化从生成器获取数据。但这是我能想到的最简单的解决方案。 Keras 没有公开权重,它们在一些隐藏的源代码中自动应用。


让模型计算权重替代方案

如果可以从xy 计算权重,您可以将此任务委托(delegate)给损失函数本身。

这有点 hacky,但可能有效:

input1 = Input(shape1)
input2 = Input(shape2)

# .... model creation .... #

model = Model([input1, input2], outputs)

让loss访问input1input2:

def custom_loss(y_true, y_pred):
    w = calculate_weights(input1, input2, y_pred)
    # .... rest of the loss .... #

这里的问题是您是否可以从输入中将权重计算为张量。

关于python - 如何访问生成器提供的 Keras 自定义损失函数中的样本权重?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57999225/

相关文章:

python - 嵌套类型提示不同的结果

python - 在具有急切执行的 TensorFlow 2.0 中,如何计算特定层的网络输出梯度?

tensorflow - 如何微调通用句子编码器 3 嵌入到自己的语料库

python - 我的 tensorflow keras 模型每次预测总是给出 1.0。它无法正常工作

python - 保存实时数据帧的最佳方法是什么?

python - 覆盖 "from <my_object> import <name>"功能?

Python 将日期字符串转换为日期时间

r - 使用 Keras 连接到多个层

python - CNN模型预测

image - Keras 实时增强添加噪声和对比度