将预先训练的模型与TF中的自定义模型相结合



我有一个简单的网络,我想通过将其与InceptionV3等预先训练的模型相结合来增加其复杂性。然而,一旦我用以下命令将它们连接在一起:

snn_model = Model(inputs=baseModel.input, outputs=model, name = 'snn')

我面临这个错误:

ValueError: Output tensors of a Functional model must be the output of a TensorFlow `Layer` (thus holding past layer metadata). Found: <tensorflow.python.keras.engine.functional.Functional object at 0x7f82d1804c10>

我的网络如下:

def build_siamese_model(inputShape, embeddingDim=48):
# increase model complexity by adding Inception
# make the network itself generate the embediings
# specify the inputs for the feature extractor network
inputs = Input(inputShape)
# define the first set of CONV => RELU => POOL => DROPOUT layers
x = Conv2D(64,(2,2), padding='same', activation='relu')(inputs)
x = MaxPooling2D(pool_size=2)(x)
x = Dropout(0.3)(x)
# second set of CONV => RELU => POOL => DROPOUT layers
x = Conv2D(64,(2,2), padding='same', activation='relu')(x)
x = MaxPooling2D(pool_size=2)(x)
x = Dropout(0.3)(x)
# prepare the final outputs
pooledOutput = GlobalAveragePooling2D()(x)
outputs = Dense(embeddingDim)(pooledOutput)
# build the model
model = Model(inputs, outputs)
# return the model to the calling function
return model

我将我的网络与InceptionV3组合如下:

baseModel = InceptionV3(weights="imagenet", include_top=False, input_shape=(160, 160,3), input_tensor=Input(shape=(160, 160,3)))
snn_model = Model(inputs=baseModel.input, outputs=model, name = 'snn')

即使我试图通过将InceptionV3输出作为自定义网络的输入来在这些模型之间切换,我也会遇到另一个错误:

ValueError: Negative dimension size caused by subtracting 2 from 1 for '{{node max_pooling2d_62/MaxPool}} = MaxPool[T=DT_FLOAT, data_format="NHWC", explicit_paddings=[], ksize=[1, 2, 2, 1], padding="VALID", strides=[1, 2, 2, 1]](Placeholder)' with input shapes: [?,1,1,64].

因此,我的想法是将自定义模型与预先训练的模型相结合,以增加复杂性并获得更好的性能。

在谷歌上搜索迁移学习,第一个结果是迁移学习和微调。我建议你先读一下,因为它正是你想要做的

基本上,您将使用InceptionV3,就像在返回整个模型的build_siamese_model函数中使用普通层一样。这样的东西就可以了:

# specify the inputs for the feature extractor network
inputs = Input(inputShape)
# define the first set of CONV => RELU => POOL => DROPOUT layers
x = baseModel(inputs) # initialized from InceptionV3
x = Conv2D(64,(2,2), padding='same', activation='relu')(x)
x = MaxPooling2D(pool_size=2)(x)
x = Dropout(0.3)(x)
# the rest of your code ...

同样,您应该阅读文档以了解如何正确实例化预先训练的模型并处理批处理规范化层

第一个错误是由于指定输出不正确。您应该定义模型的输出,即图层的输出。所以为了解决第一个错误,修改后的代码应该是这样的:

snn_model = Model(inputs=baseModel.input, outputs=model.output, name = 'snn')

第二个错误表明,您正在通过模型层收缩输入张量,直到它达到(1,1)大小。然后它就不能再进一步了,因为每个Conv2DMaxPooling层都会使输入大小变小,并且在中间层的某个地方会变负。因此,尝试删除一些层或架构,或者尝试提供更大的输入大小,以避免在中间层中达到(1,1)张量。您可以使用model.summary()来查看每个层的输出形状,以便了解输入张量在整个层中的历程。

最新更新