【问题标题】:'BCEWithLogitsLoss' object has no attribute 'backward' error PyTorch“BCEWithLogitsLoss”对象没有属性“向后”错误 PyTorch
【发布时间】:2021-03-08 14:13:06
【问题描述】:

我正在尝试微调 Bert 模型,即用于文本分类任务的 bert-base-uncased。我在 loss 时调用backward() 时遇到一个奇怪的错误,如下所示

torch.nn.modules.module.ModuleAttributeError: 'BCEWithLogitsLoss' 对象没有属性 'backward'。

我找不到任何语法错误,还检查了损失函数的输入(输出和目标),即 nn.BCEWithLogitsLoss(outputs, targets),然后我发现格式正确。我不知道是什么导致了这个错误。如果你们中的任何人可以帮助我,我会很棒......在此先感谢:)

这里是代码

'''def train_loop_fn(data_loader, model, optimizer, device, scheduler = None): 模型.train() 对于 bi, d in enumerate(data_loader): ids = d["ids"] 掩码 = d[“掩码”] token_type_ids = d["token_type_ids"] 目标 = d[“目标”]

    ids = ids.to(device, dtype=torch.long)
    mask = mask.to(device, dtype=torch.long)
    token_type_ids = token_type_ids.to(device, dtype=torch.long)
    targets = targets.to(device, dtype=torch.float)

    optimizer.zero_grad()
    outputs = model(ids=ids, mask = mask, token_type_ids = token_type_ids)
    outputs = outputs.reshape(1)
    print("here is the outputs")
    print(outputs)
    print("here is the targets")
    print(targets)
    loss = nn.BCEWithLogitsLoss(outputs, targets)
    print("this is the loss")
    print(loss)
    loss.backward()
    optimizer.step()
    if scheduler is not None:
        scheduler.step()

'''

【问题讨论】:

    标签: pytorch text-classification loss-function backpropagation bert-language-model


    【解决方案1】:

    应该是:

    loss = nn.BCEWithLogitsLoss()(outputs, targets)
    

    这样更好:

    criterion = nn.BCEWithLogitsLoss()
    
    for epoch in range(epochs):
        for batch in dataloader:
            ...
            loss = criterion(outputs, targets)
            ...
    

    另外,请在发布问题之前查看文档。 PyTorch 文档提供了一个简单的使用示例。这是torch网站上的一个例子:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-11
      • 2021-06-11
      • 2020-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-21
      • 2021-10-26
      相关资源
      最近更新 更多