簡體   English   中英

在 pytorch 中,如何訓練具有兩個或更多輸出的 model?

[英]In pytorch, how to train a model with two or more outputs?

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).

然后,我真的很想知道我應該做什么來訓練具有 2 個或更多輸出的 model

pytorch(和其他 DL 框架)的整個前提是標量損失 function 的梯度的反向傳播。
在您的情況下,您有一個向量(dim=2)損失 function:

[cross_entropy_loss(output_1, target_1), cross_entropy_loss(output_2, target_2)]

您需要決定如何將這兩個損失組合成一個標量損失。
例如:

weight = 0.5  # relative weight
loss = weight * cross_entropy_loss(output_1, target_1) + (1. - weight) * cross_entropy_loss(output_2, target_2)
# now loss is a scalar
loss.backward()
optimizer.step()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM