首页 > 解决方案 > TensorFlow/Keras:如何从 Keras 的应用程序模块中获取缺失的模型(ResNet101、ResNeXt 等)?

问题描述

我的(最新的)Keras 安装和 TensorFlow 1.10 Keras API 安装中缺少许多记录在案的Keras 应用程序。我按照建议导入 Keras 的应用程序模块并按如下方式使用它:

from keras import applications
resnet = applications.ResNeXt101(include_top=False, weights='imagenet', input_shape=(SCALED_HEIGHT, SCALED_WIDTH, 3), pooling=None)

我也试过

resnet = applications.resnext.ResNeXt101(include_top=False, weights='imagenet', input_shape=(SCALED_HEIGHT, SCALED_WIDTH, 3), pooling=None)

但在这两种情况下,我都会遇到相同类型的错误:

AttributeError: module 'keras.applications' has no attribute 'ResNeXt101'

印刷help(applications)产量:

Help on package keras.applications in keras:

NAME
    keras.applications

PACKAGE CONTENTS
    densenet
    imagenet_utils
    inception_resnet_v2
    inception_v3
    mobilenet
    mobilenet_v2
    mobilenetv2
    nasnet
    resnet50
    vgg16
    vgg19
    xception

FUNCTIONS
    DenseNet121 = wrapper(*args, **kwargs)
    DenseNet169 = wrapper(*args, **kwargs)
    DenseNet201 = wrapper(*args, **kwargs)
    InceptionResNetV2 = wrapper(*args, **kwargs)
    InceptionV3 = wrapper(*args, **kwargs)
    MobileNet = wrapper(*args, **kwargs)
    MobileNetV2 = wrapper(*args, **kwargs)
    NASNetLarge = wrapper(*args, **kwargs)
    NASNetMobile = wrapper(*args, **kwargs)
    ResNet50 = wrapper(*args, **kwargs)
    VGG16 = wrapper(*args, **kwargs)
    VGG19 = wrapper(*args, **kwargs)
    Xception = wrapper(*args, **kwargs)
    keras_modules_injection(base_fun)

这表明这些模型最初不存在于我的安装中。为什么不?它们也没有打包在 TensorFlow 的 Keras API 中。

我尝试从Keras 应用程序 GitHub 存储库中复制文件并将它们粘贴到 中site-packages/keras/applications/,但这会导致以下堆栈跟踪:

File "myscript.py", line 517, in get_fpn
    resnet = applications.resnext.ResNeXt101(include_top=False, weights='imagenet', input_shape=(SCALED_HEIGHT, SCALED_WIDTH, 3), pooling=None)
  File "site-packages/keras/applications/resnet_common.py", line 575, in ResNeXt101
    **kwargs)
  File "site-packages/keras/applications/resnet_common.py", line 348, in ResNet
    data_format=backend.image_data_format(),
AttributeError: 'NoneType' object has no attribute 'image_data_format'

有想法该怎么解决这个吗?为什么这些不包括在 Keras 或 TensorFlow 的默认安装中并在其中工作?为什么文档没有解释这一点?

标签: pythontensorflowkeraspython-module

解决方案


  • 问题原因:

backend对象None位于第 348 行。我猜你尝试过这样的事情:

>>> from keras_applications import resnext
>>> resnext.ResNeXt101(weights=None)

信息通过装饰器backend从 keras.applications 注入到 keras_applications keras_modules_injection

https://github.com/keras-team/keras/blob/c658993cf596fbd39cf800873bc457e69cfb0cdb/keras/applications/resnext.py#L17

  • 解决问题的步骤:

确保 keras 和 keras 应用程序版本如下:

>>pip list |grep Keras
Keras                  2.2.4
Keras-Applications     1.0.8

如果不是,请使用升级

>>pip install --upgrade keras keras-applications

将此拉取请求中的更改更新为https://github.com/keras-team/keras/pull/11203/filessite-packages/keras/applications

from keras import applications
resnext = applications.resnext.ResNeXt101(include_top=False, weights=None, input_shape=(299,299,3))
print(type(resnext))

推荐阅读