【发布时间】: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