Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用Pytorch提取自动编码器隐藏层的特征_Python_Pytorch_Feature Extraction_Autoencoder_Encoder Decoder - Fatal编程技术网

Python 用Pytorch提取自动编码器隐藏层的特征

Python 用Pytorch提取自动编码器隐藏层的特征,python,pytorch,feature-extraction,autoencoder,encoder-decoder,Python,Pytorch,Feature Extraction,Autoencoder,Encoder Decoder,我跟随训练一个自动编码器 训练进行得很顺利。接下来,我感兴趣的是从隐藏层(编码器和解码器之间)提取特征 我该怎么做呢?最干净、最直接的方法是添加创建部分输出的方法——这甚至可以在经过训练的模型上事后完成 from torch import Tensor class AE(nn.Module): def __init__(self, **kwargs): ... def encode(self, features: Tensor) -> Tensor:

我跟随训练一个自动编码器

训练进行得很顺利。接下来,我感兴趣的是从隐藏层(编码器和解码器之间)提取特征


我该怎么做呢?

最干净、最直接的方法是添加创建部分输出的方法——这甚至可以在经过训练的模型上事后完成

from torch import Tensor

class AE(nn.Module):
    def __init__(self, **kwargs):
        ...

    def encode(self, features: Tensor) -> Tensor:
        h = torch.relu(self.encoder_hidden_layer(features))
        return torch.relu(self.encoder_output_layer(h))

    def decode(self, encoded: Tensor) -> Tensor:
        h = torch.relu(self.decoder_hidden_layer(encoded))
        return torch.relu(self.decoder_output_layer(h))

    def forward(self, features: Tensor) -> Tensor:
        encoded = self.encode(features)
        return self.decode(encoded)
现在,只需使用相应的输入张量调用encode,就可以查询编码器隐藏状态的模型

如果您不想向基类添加任何方法(我不明白为什么),您也可以编写一个外部函数:

def get_encoder_state(model: AE, features: Tensor) -> Tensor:
   return torch.relu(model.encoder_output_layer(torch.relu(model.encoder_hidden_layer(features))))


非常感谢你。因此,在类:def encode(self,features):activation=self.encoder\u hidden\u layer(features)activation=torch.relu(activation)code=self.encoder\u output\u layer(activation)code=torch.relu(code)return code中添加此函数正确吗,培训结束后,如何调用我的函数和经过培训的模型来提取特征?这是正确的:隐藏的特征=模型。编码(我的输入)
输出=模型(批处理特征)
保持原样(它仍然提供重构的输入)。对于隐藏功能,
hidden_features=model.encode(input)
应该可以工作!