在PyTorch中,如何训练具有两个或多个输出的模型?

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

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注