【问题标题】:How to remove the input layer of pre-trained model in tf.keras and use different layer as input to the model?如何去除 tf.keras 中预训练模型的输入层,并使用不同的层作为模型的输入?
【发布时间】:2021-11-03 17:43:32
【问题描述】:

我正在尝试使用efficientNetB0 构建一个用于对灰度图像进行分类的网络。所以我的输入是单通道图像,并且由于任何预训练模型都不将单通道图像作为输入,因此我无法真正传递(256, 256, 1) 的输入形状。 所以我试着整理了一个脚本:

def build_generator(input_shape=(256,256,1)):
  effB0 = tf.keras.applications.EfficientNetB0(input_shape = (256,256,3),include_top=False)

  inputs = Input(shape=(256, 256, 1), name="model_input")
  initializer = tf.random_normal_initializer(0., 0.02)
  
  X = Conv2D(filters=3, kernel_size=1,
                  strides=1, padding='same',
                  kernel_initializer=initializer,
                  activation='relu', name='first_conv')(inputs) # (bs, 256, 256, 3)

  effB0.layers[0] = effB0.layers[0](X)


  model = Model(inputs = inputs, outputs = effB0.output)

  return model

generator = build_generator()

但我最终得到了一个不连贯的图表,

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-19-e5dd265b0536> in <module>()
----> 1 generator = build_generator()
      2 
      3 tf.keras.utils.plot_model(
      4     generator,
      5     to_file = 'generator.png',

5 frames
/usr/local/lib/python3.7/dist-packages/keras/engine/functional.py in _map_graph_network(inputs, outputs)
    982                              'The following previous layers '
    983                              'were accessed without issue: ' +
--> 984                              str(layers_with_complete_input))
    985         for x in tf.nest.flatten(node.outputs):
    986           computable_tensors.add(id(x))

ValueError: Graph disconnected: cannot obtain value for tensor KerasTensor(type_spec=TensorSpec(shape=(None, 256, 256, 3), 
dtype=tf.float32, name='input_12'), name='input_12', 
description="created by layer 'input_12'") at layer "rescaling_9". 
The following previous layers were accessed without issue: []

有什么想法吗?我不想剪辑和编辑中间网络层,所以我不想使用这种方法,

X = effB0(X)

model = Model(inputs = inputs, outputs = X)

【问题讨论】:

    标签: python machine-learning deep-learning tensorflow2.0 tf.keras


    【解决方案1】:

    试试这个:

    def build_generator(input_shape=(256, 256, 1)):
      inputs = Input(shape=(256, 256, 1), name="model_input")
      outputs = tf.keras.applications.EfficientNetB0(include_top=False, weights=None)(inputs)
      model = Model(inputs, outputs)
    
      return model
    
    generator = build_generator()
    

    【讨论】:

      猜你喜欢
      • 2021-08-04
      • 1970-01-01
      • 1970-01-01
      • 2018-12-12
      • 1970-01-01
      • 1970-01-01
      • 2018-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多