【问题标题】:How to define the loss function using the output of intermediate layers?如何使用中间层的输出定义损失函数?
【发布时间】:2020-10-12 20:00:53
【问题描述】:
class Model(nn.Module):
def __init__(self):
    super(Model, self).__init__()
    self.encoder = nn.Linear(300, 100)
    self.dense1 = nn.Sequential(nn.Linear(100, 10),nn.ReLU())
    self.dense2 = nn.Sequential(nn.Linear(10, 5),nn.ReLU())
    self.dense3 = nn.Sequential(nn.Linear(5, 1))
def forward(self, x):
    x = self.encoder(x)
    x = self.dense1(x)
    x = self.dense2(x)
    x = self.dense3(x)
    return x

我正在研究一个回归问题,我需要使用dense2层的输出来计算损失。

dense2 层的输出是 5 维 (5x1)。

我正在使用 PyTorch。

数据集:假设我正在使用 300 个特征并且我需要预测一些分数(一个浮动值)。 输入:300 个特征 输出:一些浮动值

【问题讨论】:

    标签: python deep-learning pytorch


    【解决方案1】:

    一般来说,您的nn.Module 可以返回任意数量的元素。此外,您不必在任何地方使用它们——没有任何机制可以检查。 Pytorch 的理念是在运行中计算计算图。

    class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.encoder = nn.Linear(300, 100)
        self.dense1 = nn.Sequential(nn.Linear(100, 10),nn.ReLU())
        self.dense2 = nn.Sequential(nn.Linear(10, 5),nn.ReLU())
        self.dense3 = nn.Sequential(nn.Linear(5, 1))
    
    def forward(self, x):
        enc_output = self.encoder(x)
        dense1_output = self.dense1(enc_output)
        dense2_output = self.dense2(dense1_output)
        dense3_output = self.dense3(dense2_output)
        return dense3_output, dense2_output
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-14
      • 1970-01-01
      • 2018-06-28
      • 1970-01-01
      • 2018-07-22
      • 1970-01-01
      • 1970-01-01
      • 2019-01-27
      相关资源
      最近更新 更多