【问题标题】:Adding custom weights to training data in PyTorch在 PyTorch 中为训练数据添加自定义权重
【发布时间】:2021-05-28 04:17:04
【问题描述】:

是否可以在 PyTorch 中为训练实例添加自定义权重?更明确地说,我想为我的数据集中的每一行添加一个自定义权重。默认情况下,权重为 1,这意味着每个数据对我的模型同样重要。

【问题讨论】:

  • 您可以查看 torch.nn.init here。你也许可以做torch.nn.init(layer.weight, a)。我不知道这是不是你的意思
  • @DwightFoster 这似乎是关于初始化模型权重。所以不相关,很遗憾。
  • 什么意思?如果你想惩罚损失函数,你可以在那里直接指定权重。 pytorch.org/docs/stable/generated/…
  • @JohnStud 乘以损失函数与称重实例的效果相同,因此应该可以。但是,我不能通过修改我的训练数据集来做到这一点,而不是在每次训练时指定权重吗?
  • 您可以编辑您的问题并更明确地说明您想要的结果吗?

标签: python machine-learning deep-learning pytorch


【解决方案1】:

损失函数支持类别权重而不是样本权重。对于样本权重,您可以执行以下操作(内联注释):

import torch

x = torch.rand(8, 4)
# Ground truth
y = torch.randint(2, (8,))
# Weights per sample 
weights = torch.rand(8, 1) 

# Add weights as a columns, so that it will be passed trough
# dataloaders in case you want to use one
x = torch.cat((x, weights), dim=1)

model = torch.nn.Linear(4, 2)

loss_fn = torch.nn.CrossEntropyLoss(reduction='none')
def weighted_loss(y, y_hat, w):
  return (loss_fn(y, y_hat)*w).mean()

loss = weighted_loss(model(x[:, :-1]), y, x[:, -1])
print (loss)

【讨论】:

  • 这看起来合乎逻辑。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-30
  • 1970-01-01
  • 2020-11-09
  • 1970-01-01
  • 2021-03-28
  • 2019-11-17
相关资源
最近更新 更多