如何提取隐藏向量(第三层编码器后ReLU的输出)作为图像表示

How to extract the hidden vector (the output of the ReLU after the third encoder layer) as the image representation

我正在使用 Fashion Mnsit 数据集实现自动编码器。编码器的代码-

class MNISTClassifier(Model):
    def __init__(self):
        super(MNISTClassifier, self).__init__()
        self.encoder = Sequential([
            layers.Dense(128, activation = "relu"),
            layers.Dense(64, activation = "relu"),
            layers.Dense(32, activation = "relu")
        ])
        
        self.decoder = Sequential([
            layers.Dense(64, activation = "relu"), 
            layers.Dense(128, activation= "relu"),
            layers.Dense(784, activation= "relu")
        ])
        
    def call(self, x):
        encoded = self.encoder(x)
        decoded = self.decoder(encoded)
        return decoded
    
autoencoder = MNISTClassifier()

现在我想在从上述自动编码器均值中提取的图像表示上训练 SVM 分类器 一旦上面的全连接自动编码器被训练好,对于每个图像,我想提取 32- 维隐藏向量(第三个编码器层后 ReLU 的输出)作为 图像表示,然后基于 32- 维度特征。

如何提取输出 32- 维隐藏向量??

提前致谢!!!!!!!!!!!!

我建议使用 Functional API 来定义模型的多个输出,因为代码更清晰。但是,您可以使用 Sequential 模型执行此操作,方法是获取所需任何层的输出并将其添加到模型的输出中。

打印您的 model.summary() 并检查您的图层以找到您要分支的图层。您可以通过 model.layers[index].output .

的索引访问每一层的输出

然后您可以创建所需层的多输出模型,如下所示:

 third_layer = model.layers[2]
 last_layer = model.layers[-1]
 my_model = Model(inputs=model.input, outputs=(third_layer.output, last_layer.output))

然后,您可以访问您定义的两个层的输出:

third_layer_predict, last_layer_predict = my_model.predict(X_test)