赞
踩
在分类问题中,当遇到样本不均衡时,可以对各类别设置不同的权重,如下:
batch_size = 10
nb_classes = 2
model = nn.Linear(10, nb_classes)
weight = torch.empty(nb_classes).uniform_(0, 1)
# 初始化CrossEntropy函数时传入各个class的权重
criterion = nn.CrossEntropyLoss(weight=weight)
ce = nn.CrossEntropyLoss(ignore_index=255, weight=weight_CE)
loss = ce(inputs,outputs)
但有时候,我们不仅每个类别有权重,而且每个样本的权重也不相同。这时候需要更精细的控制了,可通过两步来达到此目的:
batch_size = 10
nb_classes = 2
model = nn.Linear(10, nb_classes)
weight = torch.empty(nb_classes).uniform_(0, 1)
# 初始化CrossEntropy函数时传入各个class的权重,
# 且设置reduction为None表示不进行聚合,返回一个loss数组
criterion = nn.CrossEntropyLoss(weight=weight, reduction='none')
# This would be returned from your DataLoader
x = torch.randn(batch_size, 10)
target = torch.empty(batch_size, dtype=torch.long).random_(nb_classes)
sample_weight = torch.empty(batch_size).uniform_(0, 1)
output = model(x)
loss = criterion(output, target)
# 各个样本乘以其权重,然后求均值
loss = loss * sample_weight
loss.mean().backward()
此外,还可以对每个样本的loss进行归一化,使得所有batch的loss大小范围较为相近:
loss =(loss * sample_weight / sample_weight.sum()).sum()
此步非必须,因为我们给定各个样本不同权重其实就是要使得各个样本的loss有区别的。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。