1. CrossEntropyLoss()中的加权损失 2. WeightedRandomSampler和subsampler的结合

1. Weighted Loss in CrossEntropyLoss() 2. Combination of WeightedRandomSampler and subsampler

我想对我的 3 class class 化问题实施 class 权重。

通过直接添加权重进行了尝试,这在将我的模型输出和标签传递给我的损失时出现错误

criterion = nn.CrossEntropyLoss(weight=torch.tensor([1,2,2]))

错误:

loss = criterion(out, labels)         
expected scalar type Float but found Long

所以我打印 dtypes 并将它们更改为 float 但它仍然给我同样的错误

labels = labels.float()
print("Labels Training", labels, labels.dtype)
print("Out Training ", out, out.dtype)
loss = criterion(out, labels) 

>>Labels Training tensor([2.]) torch.float32
>>Out Training  tensor([[ 0.0540, -0.1439, -0.0070]], grad_fn=<AddmmBackward0>) torch.float32
>>expected scalar type Float but found Long

我也试过改成float64(),结果告诉我tensor Object没有属性float64

  1. 问题:我还没有尝试过这个方法,但我发现更常用的方法是 RandomWeightedSampler。我的问题是我将 CV 与 K-Fold 一起使用,并为此使用了 SubSampler。是否可以同时使用两者?还没有找到任何与此相关的东西。

对于第一个问题,nn.CrossEntropyLoss 要求输出为 float 类型,label 为 long 类型,weight 为 float 类型。因此,您应该将 nn.CrossEntropyLoss "weight" 的可选参数更改为 float by:

criterion = nn.CrossEntropyLoss(weight=torch.tensor([1.0,2.0,2.0]))
loss = criterion(out, labels.long())