【炼丹保姆】如何给损失函数加权重 【拓展篇 提问】
-
前言
前文分析了如何给损失函数加权重,主要针对的是不均衡数据的分类问题。如果我们想要给每个样本做加权呢?
代码
# 对于损失函数部分的修改如下 # N: batch size # C: the number of class # input.size() : [N, C] # target.size() : [N] loss = nn.CrossEntropyLoss(reduction='none') output = loss(input, target) # 由于reduction选择了none, 此时output输出的是每个样本的损失值 # 即 output shape: [N] # 此时如果我们有每个样本的权重w # w.size(): [N] # 加权平均后的最终损失值为 final_loss = (w*output).sum()/w.sum()
问题
那么问题来了,当我们用DataLoader封装数据以后,对每个batch的数据集,我们如何才能得到原始的sample index从而获得每个sample对应的weights呢?
-
173****7719