keras inceptionV3 错误“base_model.get_layer('custom')” ValueError: No such layer: custom

Rim*_*wal 1 python classification keras tensorflow

我正在尝试使用 inceptionV3 预训练模型(来自 keras 应用程序)提取特征。我的代码有以下块:

 base_model = InceptionV3(include_top=include_top, weights=weights, input_tensor=Input(shape=(299,299,3)))
 model = Model(input=base_model.input, output=base_model.get_layer('custom').output)
 image_size = (299, 299)
Run Code Online (Sandbox Code Playgroud)

当我运行它时,它会出现以下错误:

ValueError                                Traceback (most recent call last)
<ipython-input-24-fa1f85b62b84> in <module>()
     20 elif model_name == "inceptionv3":
     21   base_model = InceptionV3(include_top=include_top, weights=weights, input_tensor=Input(shape=(299,299,3)))
---> 22   model = Model(input=base_model.input, output=base_model.get_layer('custom').output)
     23   image_size = (299, 299)
     24 elif model_name == "inceptionresnetv2":

~\Anaconda3\lib\site-packages\keras\engine\network.py in get_layer(self, name, index)
    362         """Retrieves the model's updates.
    363 
--> 364         Will only include updates that are either
    365         unconditional, or conditional on inputs to this model
    366         (e.g. will not include updates that depend on tensors

ValueError: No such layer: custom
Run Code Online (Sandbox Code Playgroud)

我已经尝试完全卸载并重新安装 Keras。我还在某处读到在 inceptionV3.py 文件中包含以下内容(在 keras 应用程序文件夹中):

from ..layers import Flatten
Run Code Online (Sandbox Code Playgroud)

我在进口中添加了这个。仍然没有运气。任何人都可以帮我解决这个问题吗?我是 Keras 的新手。

Dan*_*ler 5

好的...我认为您正在学习本教程,在我看来,它的作者并不是真正最伟大的 Keras 用户。

引用的自定义层是由教程在更改 keras 源代码时创建的(请不要这样做,这不是一种安全的工作方式,会在您以后的项目中造成麻烦

在教程的这一部分中创建了自定义层:

`Add in "<model>.py"


...
...
if include_top:
    # Classification block
    x = GlobalAveragePooling2D(name='avg_pool')(x)
    x = Dense(classes, activation='softmax', name='predictions')(x)
else:
    if pooling == 'avg':
        x = GlobalAveragePooling2D()(x)
    elif pooling == 'max':
        x = GlobalMaxPooling2D()(x)
    x = Flatten(name='custom')(x)
...
Run Code Online (Sandbox Code Playgroud)

注释:

  • 这是完全没有必要的。全局池的输出已经扁平化。
  • 这对您未来的项目很危险,因为您正在更改 keras 源代码。

您可以通过简单地获取模型的最后一层来执行完全相同的操作,而无需创建此展平层:

lastLayer = base_model.layers[-1]
Run Code Online (Sandbox Code Playgroud)

甚至更多:如果目标层是最后一层,则不需要任何这些。只需按base_model原样使用即可。

如果你想要一个带有Dense层的完整模型,只需使用include_top=True.

如果您想要自定义数量的类,请告诉模型构造函数。

如果你想要一个真正的中间层,通过调用找到层的名称model.summary()