簡體   English   中英

如何使用預訓練的 model 的第一層來提取 Keras model 內部的特征(功能 API)

[英]How to use the first layers of a pretrained model to extract features inside a Keras model (Functional API)

我想在 Xception 中使用預訓練的 model 的第一層,並包括 add_5 層從輸入中提取特征。 然后將 add_5 層的 output 傳遞到可訓練的密集層。

我怎樣才能實現這個想法?

Generally you need to reuse layers from one model, to pass them as an input to the rest layers and to create a Model object with input and output of the combined model specified. 例如來自https://github.com/FHainzl/Visualizing_Understanding_CNN_Implementation.git的 alexnet.py。

他們有

from keras.models import Model

from keras.layers.convolutional import Conv2D, MaxPooling2D, ZeroPadding2D

def alexnet_model():
    inputs = Input(shape=(3, 227, 227))
    conv_1 = Conv2D(96, 11, strides=4, activation='relu', name='conv_1')(inputs)
    …
    prediction = Activation("softmax", name="softmax")(dense_3)
    m = Model(input=inputs, output=prediction)
    return m

然后他們將返回的 model(所需的中間層)作為返回該層輸出的 model:

def _sub_model(self):
    highest_layer_name = 'conv_{}'.format(self.highest_layer_num)
    highest_layer = self.base_model.get_layer(highest_layer_name)
    return Model(inputs=self.base_model.input,
                 outputs=highest_layer.output)

你會需要類似的東西,

highest_layer = self.base_model.get_layer('add_5')

然后繼續它

my_dense = Dense(... name=’my_dense’)(highest_layer.output)
…

並完成

return Model(inputs=self.base_model.input,
             outputs=my_prediction)

由於最高層是層(圖形節點),而不是連接,返回結果(圖形弧),您需要將.output添加到highest_layer

如果上面的模型也准備好了,不知道如何准確地組合模型。 也許像

model_2_lowest_layer = model_2.get_layer(lowest_layer_name)
upper_part_model = Model(inputs= model_2_lowest_layer.input,
                         outputs=model_2.output)
upper_part = upper_part_model()(highest_layer.output)
return Model(inputs=self.base_model.input,
             outputs=upper_part)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM