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)
选项1:
对时间段和批处理进行手动循环,使用方法
train_on_batch
,该方法也接受class_weight
:选项2:
创建自定义损耗。可能更棘手,这取决于数据格式、类的数量、丢失函数的类型等
假设二维数据(样本、类)和多类问题:
^{pr2}$假设只有二维(1)分类:
警告:如果任何类计数为零,两个loss函数都将返回Nan(或无穷大)。在
一种选择是使用样本权重,而不是使用
class_weight
如果希望样本权重是动态的,则需要使用
fit_generator
而不是fit
,这样就可以在运行过程中更改权重伪代码:
在这段代码中,
make_weights
应该返回一个与y_batch
长度相同的数组。每个元素都是一个权重,将应用于相应的样本如果您不确定
class_weight
和样本权重是否相同,noticekeras如何标准化类权重。在所以类权重最终实际上转化为样本权重:)
相关问题 更多 >
编程相关推荐