【问题标题】:Extracting hidden features from Autoencoders using Pytorch使用 Pytorch 从自动编码器中提取隐藏特征
【发布时间】:2021-05-22 02:22:09
【问题描述】:

按照post 中的教程,我正在尝试训练自动编码器并从其隐藏层中提取特征。

所以这是我的问题:

  1. 在自动编码器类中,有一个“前进”功能。但是,我在代码中看不到调用此函数的任何地方。那么它是如何训练的呢?

  2. 我上面的问题是因为我觉得如果我想提取特征,我应该在自动编码器类中添加另一个函数(f“orward_hidden”):

     def forward(self, features):
         #print("in forward")
         #print(type(features))
         activation = self.encoder_hidden_layer(features)
         activation = torch.relu(activation)
         code = self.encoder_output_layer(activation)
         code = torch.relu(code)
         activation = self.decoder_hidden_layer(code)
         activation = torch.relu(activation)
         activation = self.decoder_output_layer(activation)
         reconstructed = torch.relu(activation)
         return reconstructed
    
     def forward_hidden(self, features):
         activation = self.encoder_hidden_layer(features)
         activation = torch.relu(activation)
         code = self.encoder_output_layer(activation)
         code = torch.relu(code)
         return code
    

那么,训练后,也就是主代码中这一行之后:

print("AE, epoch : {}/{}, loss = {:.6f}".format(epoch + 1, epochs_AE, loss))

我可以输入以下代码从隐藏层检索特征:

hidden_features = model_AE.forward_hidden(my_input)

这种方式正确吗?不过,我想知道“前进”功能是如何用于训练的。因为我在被调用的代码中的任何地方都看不到它。

【问题讨论】:

    标签: python deep-learning neural-network pytorch autoencoder


    【解决方案1】:

    forward 是模型的本质,实际上定义了模型的作用。

    在训练过程中使用model(input) 隐式调用。

    如果您在运行模型后询问如何提取中间特征,您可以像here 所述注册一个forward-hook,它将为您“捕获”这些值。

    【讨论】:

    • 非常感谢。所以你的意思是因为 Pytorch 的 nn 模块隐含地调用了“forward”? (某种属性?)这是否意味着我们不能添加其他任意函数?我还是有点迷茫。
    • forward() 是您必须实现的方法(在某些语言中,如 Java 中的接口)。这是 pytorch 框架实现者所期望的。除此之外,你可以添加你喜欢的东西,但它不会被 pytorch 使用。取而代之的是,实现者使用了钩子(或回调)模式来让你在模型类“外部”“钩子”你的函数
    • 您还有其他建议/示例来说明如何在 nn 模型中挂钩其他功能吗?
    猜你喜欢
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-31
    • 1970-01-01
    • 2020-03-12
    • 2020-04-10
    • 2017-12-20
    • 2020-01-23
    相关资源
    最近更新 更多