[英]How to use the first layers of a pretrained model to extract features inside a Keras model (Functional API)
I would like to use the first layers of a pre-trained model --say in Xception up and including the add_5 layer to extract features from an input.我想在 Xception 中使用预训练的 model 的第一层,并包括 add_5 层从输入中提取特征。 Then pass the output of the add_5 layer to a dense layer that will be trainable.
然后将 add_5 层的 output 传递到可训练的密集层。
How can I implement this idea?我怎样才能实现这个想法?
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. 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. For example alexnet.py from https://github.com/FHainzl/Visualizing_Understanding_CNN_Implementation.git .
例如来自https://github.com/FHainzl/Visualizing_Understanding_CNN_Implementation.git的 alexnet.py。
They have他们有
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
and then they take this returned model, the desired intermediate layer and make a model that returns this layer's outputs:然后他们将返回的 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)
You will need similar thing,你会需要类似的东西,
highest_layer = self.base_model.get_layer('add_5')
then continue it like然后继续它
my_dense = Dense(... name=’my_dense’)(highest_layer.output)
…
and finish with并完成
return Model(inputs=self.base_model.input,
outputs=my_prediction)
Since highest_layer is a layer (graph node), not a connection, returning result (graph arc), you'll need to add .output
to highest_layer
.由于最高层是层(图形节点),而不是连接,返回结果(图形弧),您需要将
.output
添加到highest_layer
。
Not sure how exactly to combine models if the upper one is also ready.如果上面的模型也准备好了,不知道如何准确地组合模型。 Maybe something like
也许像
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.