预训练 Keras Xception 和 InceptionV3 模型

cck*_*ck3 4 python deep-learning keras tensorflow

我正在尝试使用 Keras 及其预构建的 ImageNet CNN 架构来解决一个简单的二元分类问题。

对于 VGG16,我采用了以下方法,

vgg16_model = keras.application.vgg16.VGG16()

'''Rebuild the vgg16 using an empty sequential model'''
model = Sequential()
for layer in vgg16_model.layers:
    model.add(layer)

'''Since the problem is binary, I got rid of the output layer and added a more appropriate output layer.'''
model.pop()

'''Freeze other pre-trained weights'''
for layer in model.layers:
    layer.trainable = False

'''Add the modified final layer'''
model.add(Dense(2, activation = 'softmax'))
Run Code Online (Sandbox Code Playgroud)

与我定制的 CNN 相比,这非常有效,而且准确度更高。但是训练需要一段时间,我想使用 Xception 和 InceptionV3 采取类似的方法,因为它们是更轻的模型,具有更高的准确性。

xception_model = keras.applicaitons.xception.Xception()
model = Sequential()
for layer in xception_model.layers:
    model_xception.add(layer)
Run Code Online (Sandbox Code Playgroud)

当我运行上面的代码时,出现以下错误:

ValueError: Input 0 is incompatible with layer conv2d_193: expected axis -1 of input shape to have value 64 but got shape (None, None, None, 128)
Run Code Online (Sandbox Code Playgroud)

基本上,我想做与 VGG16 模型相同的事情;保持其他预训练权重不变,只需将输出层修改为二元分类输出,而不是具有 1000 个结果的输出层。我可以看到,与具有相对简单的卷积层结构的 VGG16 不同,Xception 和 InceptionV3 有一些我不是 100% 熟悉的时髦节点,我假设这些节点会导致问题。

Yu-*_*ang 5

您的代码失败是因为InceptionV3并且Xception不是Sequential模型(即,它们包含“分支”)。所以你不能只是将层添加到Sequential容器中。

现在由于两个的顶层InceptionV3Xception由一个的GlobalAveragePooling2D层和最终Dense(1000)层,

if include_top:
    x = GlobalAveragePooling2D(name='avg_pool')(x)
    x = Dense(classes, activation='softmax', name='predictions')(x)
Run Code Online (Sandbox Code Playgroud)

如果你想删除最后的密集层,你可以在创建这些模型时设置include_top=False加号pooling='avg'

base_model = InceptionV3(include_top=False, pooling='avg')
for layer in base_model.layers:
    layer.trainable = False
output = Dense(2, activation='softmax')(base_model.output)
model = Model(base_model.input, output)
Run Code Online (Sandbox Code Playgroud)