访问每个输入图像的中间层输出,并将其作为输入馈送到另一个模型

2024-04-26 00:49:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用模型子类化方法创建了多个模型。现在,我需要得到模型1的中间层输出,并将其作为另一个模型(模型2)的输入

我的Model1代码如下所示:

    class Cmodel(keras.Model):
       
        def __init__(self):
            super(Cmodel,self).__init__(name = "CustomMod")
            self.conv1 = Conv2D(16, 3 , padding = 'same', activation = 'relu')
            self.conv2 = Conv2D(16, 3 , padding = 'same', activation = 'relu')
            #Intilizing other layers
        
       def call(self,input_):   
            conv1 = self.conv1(input_)
            conv2 = self.conv2(conv1) # I need the output of this layer
            #Other layers
            classifier = self.dense(x)  #last layer
            return classifier

Model1 = CModel()
Model1.compile(loss = categorical_focal_loss(), optimizer = 'adam', metrics=['accuracy'])
history  = Model1.fit(train_generator, epochs = 1, validation_data = validation_generator)

我需要得到每个输入图像的conv2输出。然后,将对提取的输出进行处理,并将其作为输入提供给Model2

我尝试了两种方法来获得中间层的输出,但都没有达到预期效果。这些方法是:

  1. 不太好。使用Model1.input和Model1.get_layer(layername).output,使用keras.Model将它们包装起来。这返回了一个错误

Model1_output_layer = Model1.get_layer("feature_maps").output

m = keras.Model(inputs = Model1.input, outputs=Model1_output_layer)

AttributeError                            Traceback (most recent call last)
<ipython-input-14-cbc543941051> in <module>
      1 Model1_output_layer = Model1.get_layer("feature_maps").output
----> 2 m =  keras.Model(inputs = Model1.input, outputs=Model1_output_layer)

~\Anaconda3\lib\site-packages\tensorflow\python\keras\engine\base_layer.py in input(self)
   2042     """
   2043     if not self._inbound_nodes:
-> 2044       raise AttributeError('Layer ' + self.name +
   2045                            ' is not connected, no input to return.')
   2046     return self._get_node_attribute_at_index(0, 'input_tensors', 'input')

AttributeError: Layer CustomMod is not connected, no input to return.
  1. 我尝试存储中间层输出的另一种方法是使用类CModel的变量存储,即在模型子类本身的调用函数内部。这存储了中间层输出,但仅用于一个批次

请提供一些方法来存储每个列车输入图像的模型中间层输出