是否可以在keras中实现动态类权重?

2024-06-02 06:48:14 发布

您现在位置:Python中文网/ 问答频道 /正文

keras支持class_weights特性,允许给不同的类赋予不同的权重,例如当样本数量不平衡时

我想做一些类似的事情,但是使用动态权重,基于每个批中的类不平衡。在

这可能吗?在


Tags: 数量动态特性事情classkeras权重样本
2条回答

选项1:

对时间段和批处理进行手动循环,使用方法train_on_batch,该方法也接受class_weight

for epoch in range(epochs):
    for batchX,batchY in batches: #adapt this loop to your way of creating/getting batches

        weights = calculateOrGetTheWeights(batch)
        model.train_on_batch(batchX,batchY,...,class_weight=weights)

选项2:

创建自定义损耗。可能更棘手,这取决于数据格式、类的数量、丢失函数的类型等

假设二维数据(样本、类)和多类问题:

^{pr2}$

假设只有二维(1)分类:

import keras.backend as K

def binaryCustomLoss(yTrue,yPred):

    positives = yTrue
    negatives = 1 - yTrue

    positiveRatio = K.mean(positives)
    negativeRatio = 1 - positiveRatio #or K.mean(negatives)

    weights = (positives / positiveRatio) + (negatives / negativeRatio)

    #you may need K.squeeze(weights) here

    return weights * K.some_loss_function(yTrue,yPred)

警告:如果任何类计数为零,两个loss函数都将返回Nan(或无穷大)。在

一种选择是使用样本权重,而不是使用class_weight

如果希望样本权重是动态的,则需要使用fit_generator而不是fit,这样就可以在运行过程中更改权重

伪代码:

def gen(x, y):
    while True:
        for x_batch, y_batch in make_batches(x, y):
            weights = make_weights(y_batch)
            yield x_batch, y_batch, weights
model.fit_generator(gen(x_train, y_train))

在这段代码中,make_weights应该返回一个与y_batch长度相同的数组。每个元素都是一个权重,将应用于相应的样本

如果您不确定class_weight和样本权重是否相同,noticekeras如何标准化类权重。在

所以类权重最终实际上转化为样本权重:)

相关问题 更多 >