pytorch TypeError:CrossEntropyLoss.forward()获得意外的关键字参数“weight”

c3frrgcw  于 2022-12-29  发布在  其他
关注(0)|答案(1)|浏览(278)

我收到此错误:

File "/nitorch/trainer.py", line 110, in __init__
    nn.CrossEntropyLoss(outputs, labels, weight = weights)
  File "/home/gonzalo/miniconda3/envs/cnn2/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1110, in _call_impl
    return forward_call(*input, **kwargs)
TypeError: CrossEntropyLoss.forward() got an unexpected keyword argument 'weight'

我尝试使用torch手动重新调整每个类的权重来获得损失。nn.交叉熵损失:loss = nn.CrossEntropyLoss(outputs, labels, weight = weights)其中weights是具有与输出和标签相同长度的权重的Tensor。
torch的文档nn.CrossEntropyLoss表示它接受权重来重新缩放类https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html
会发生什么事?

sy5wg1nm

sy5wg1nm1#

首先需要使用类权重创建nn.CrossEntropyLoss的示例,然后使用输出和标签调用它:

loss = nn.CrossEntropyLoss(weight=weights)
output = loss(outputs, labels)

所有pytorch docs在底部都包含示例。

相关问题