【问题标题】:Keras: How to get layer shapes in a Sequential modelKeras:如何在顺序模型中获取图层形状
【发布时间】:2017-09-30 07:32:12
【问题描述】:

我想访问Sequential Keras 模型中所有层的层大小。我的代码:

model = Sequential()
model.add(Conv2D(filters=32, 
               kernel_size=(3,3), 
               input_shape=(64,64,3)
        ))
model.add(MaxPooling2D(pool_size=(3,3), strides=(2,2)))

然后我想要一些类似下面的代码工作

for layer in model.layers:
    print(layer.get_shape())

.. 但事实并非如此。我得到错误:AttributeError: 'Conv2D' object has no attribute 'get_shape'

【问题讨论】:

    标签: python tensorflow deep-learning keras theano


    【解决方案1】:

    如果你想以花哨的方式打印输出:

    model.summary()
    

    如果您希望尺寸以可访问的形式显示

    for layer in model.layers:
        print(layer.get_output_at(0).get_shape().as_list())
    

    可能有比这更好的方法来访问这些形状。感谢 Daniel 的启发。

    【讨论】:

      【解决方案2】:

      根据Keras Layer 的官方文档,可以通过layer.output_shapelayer.input_shape 访问层输出/输入形状。

      from keras.models import Sequential
      from keras.layers import Conv2D, MaxPool2D
      
      
      model = Sequential(layers=[
          Conv2D(32, (3, 3), input_shape=(64, 64, 3)),
          MaxPool2D(pool_size=(3, 3), strides=(2, 2))
      ])
      
      for layer in model.layers:
          print(layer.output_shape)
      
      # Output
      # (None, 62, 62, 32)
      # (None, 30, 30, 32)
      

      【讨论】:

      • "AttributeError: 该层从未被调用,因此没有定义的输出形状"
      • @Adrian 确保正确定义第一层的inpute_shape。您可以先致电model.build() 进行检查。
      【解决方案3】:

      只需使用model.summary(),它就会打印所有图层及其输出形状。


      如果您需要它们作为数组、元组等,您可以尝试:

      for l in model.layers:
          print (l.output_shape)
      

      对于多次使用的层,它们包含“多个入站节点”,您应该分别获取每个输出形状:

      if isinstance(layer.outputs, list):
          for out in layer.outputs:
              print(K.int_shape(out))
      
              for out in layer.outputs:
      

      第一层将作为 (None, 62, 62, 32) 出现。 None 与 batch_size 有关,将在训练或预测期间定义。

      【讨论】:

      • model.summary() 在许多情况下是一个不错的选择,但理想情况下我希望将形状设为数组或张量
      • 我收到以下错误(更新后):AttributeError: The layer "max_pooling2d_1 has multiple inbound nodes, with different output shapes. Hence the notion of "output shape" is ill-defined for the layer. Use 'get_output_shape_at(node_index)' instead. 我认为您必须按照我的回答完成全部操作
      • 你可以K.int_shape(layer.get_output_at(node_index)),但你需要在许多索引处获得输出
      猜你喜欢
      • 2018-09-06
      • 2017-06-30
      • 2021-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-22
      相关资源
      最近更新 更多