tensorflow - “KerasLayer”对象没有属性 'layers'

标签 tensorflow keras-layer tf.keras tensorflow-hub

我正在尝试自定义从 tf hub 获取的模型,但是 无法访问图层并出现以下错误'KerasLayer'对象没有属性'layers'

这是我的代码作为示例:

import tensorflow_hub as hub

from tensorflow.keras import layers

feature_extractor_url = "https://tfhub.dev/tensorflow/efficientnet/lite0/feature-vector/1" 

base_model = hub.KerasLayer(feature_extractor_url,
                                         input_shape=(224,224,3))

base_model.trainable = True


import tensorflow
from tensorflow.keras.models import Model

x =  base_model.layers[-10].output
x = tensorflow.keras.layers.Conv2D(4, (3, 3), padding="same", activation="relu")(x)
x = tensorflow.keras.layers.GlobalMaxPooling2D()(x)
x = tensorflow.keras.layers.Flatten()(x)
outputs = tensorflow.keras.layers.Activation('sigmoid', name="example_output")(x)

model = Model(base_model.input, outputs=outputs)

model.summary()

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-43-0501ec56d6c4> in <module>()
     14 from tensorflow.keras.models import Model
     15 
---> 16 x =  base_model.layers[-10].output
     17 x = tensorflow.keras.layers.Conv2D(4, (3, 3), padding="same", activation="relu")(x)
     18 x = tensorflow.keras.layers.GlobalMaxPooling2D()(x)

AttributeError: 'KerasLayer' object has no attribute 'layers'

我尝试过的: 我使用顺序 api 构建了模型:

model = tf.keras.Sequential([
  base_model,
  layers.Dense(image_data.num_classes)
])

model.summary()

但我仍然无法访问 base_model 内的层。

如何从 KerasLayer 访问图层?

谢谢!

最佳答案

您可以通过Hub模型的权重访问各层。

不幸的是,TF 文档中并未直接提及该主题。这是我到目前为止可以挖掘到的深度,希望它能为访问 Hub 上的图层提供一些启发。

以下测试使用了 TF 2.5.0 和 TF-Hub 0.12.0。

  1. KerasLayer 对象中的图层
>>> import tensorflow_hub as hub
>>> model = hub.KerasLayer("https://tfhub.dev/deepmind/ganeval-cifar10-convnet/1")
>>> model
<tensorflow_hub.keras_layer.KerasLayer object at 0x7f0c79372190>
>>> len(model.weights)
57
>>> model.weights[56]
<tf.Variable 'cifar10_convnet/linear/b:0' shape=(10,) dtype=float32, numpy=
array([-0.2734375 , -1.46875   ,  0.484375  ,  1.2265625 ,  0.53515625,
        0.96875   ,  0.3671875 ,  0.02282715, -0.7265625 , -1.078125  ],
      dtype=float32)>
>>> model.weights[56].name
'cifar10_convnet/linear/b:0'

注意上面的权重变量。 KerasLayer 也有一个 get_weights() 函数。输出的差异如下。基本上,前者是 TF-Variable 类型,后者是 numpy 数组。

>>> len(model.get_weights())
57
>>> model.get_weights()[56]
array([-0.2734375 , -1.46875   ,  0.484375  ,  1.2265625 ,  0.53515625,
        0.96875   ,  0.3671875 ,  0.02282715, -0.7265625 , -1.078125  ],
      dtype=float32)

例如,要获取所有层的名称,只需运行:

layers = model.weights
[ layers[i].name for i in range( len(layers) ) ]

我的输出提示:

'cifar10_convnet/conv_net_2d/conv_2d_0/w:0',

'cifar10_convnet/conv_net_2d/conv_2d_0/b:0',

'cifar10_convnet/conv_net_2d/batch_norm_0/moving_mean:0',

'cifar10_convnet/conv_net_2d/batch_norm_0/moving_variance:0'

请注意,权重、偏差、均值、方差等均在输出中作为层单独列出。


  • AutoTrackable 对象中的图层
  • 这适用于低级别 TF2 API 用户。

    >>> import tensorflow_hub as hub
    >>> model = hub.load("https://tfhub.dev/deepmind/ganeval-cifar10-convnet/1")
    >>> model
    <tensorflow.python.training.tracking.tracking.AutoTrackable object at 0x7f95943ec410>
    >>> len(model.variables)
    57
    >>> model.variables[56]
    <tf.Variable 'cifar10_convnet/linear/b:0' shape=(10,) dtype=float32, numpy=
    array([-0.2734375 , -1.46875   ,  0.484375  ,  1.2265625 ,  0.53515625,
            0.96875   ,  0.3671875 ,  0.02282715, -0.7265625 , -1.078125  ],
          dtype=float32)>
    

    在此 API 中使用“变量”而不是“权重”。

    关于tensorflow - “KerasLayer”对象没有属性 'layers',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60701178/

    相关文章:

    Tensorflow 2.0 Keras 模型子类化

    python - 在推理服务中使用 tf.Session 时它是线程安全的吗?

    python - Tensorflow:同一图像的不同激活值

    python - 从字符串列表创建 TfRecords 并在解码后在 tensorflow 中提供图形

    python - keras:使用get_weights函数提取权重

    machine-learning - Keras:引入批量标准化后 NaN 训练损失

    python-3.x - python tensorflow文本分类中的稀疏矩阵

    python - 获取 Keras 模型/层的输出

    python - tensorflow keras RandomForestModel get_config() 为空

    tensorflow - 在 keras.sequential 模型中使用 keras.layers.Add()