output_1, output_2 = model(x)loss = cross_entropy_loss(output_1, target_1)loss.backward()optimizer.step()loss = cross_entropy_loss(output_2, target_2)loss.backward()optimizer.step()
然而,当我运行这段代码时,我得到了以下错误:
RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [1, 4]], which is output 0 of TBackward, is at version 2; expected version 1 instead. Hint: enable anomaly detection to find the operation that failed to compute its gradient, with torch.autograd.set_detect_anomaly(True).
那么,我想知道如何正确地训练一个具有两个或多个输出的模型
回答:
PyTorch(以及其他深度学习框架)的基础是基于标量损失函数的梯度反向传播。
在你的例子中,你有一个维度为2的向量损失函数:
[cross_entropy_loss(output_1, target_1), cross_entropy_loss(output_2, target_2)]
你需要决定如何将这两个损失合并为一个单一的标量损失。
例如:
weight = 0.5 # 相对权重loss = weight * cross_entropy_loss(output_1, target_1) + (1. - weight) * cross_entropy_loss(output_2, target_2)# 现在loss是一个标量loss.backward()optimizer.step()