Python Keras:如何在顺序模型中获取图层形状
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43743593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Keras: How to get layer shapes in a Sequential model
提问by Toke Faurby
I would like to access the layer size of all the layers in a Sequential
Keras model. My code:
我想访问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)))
Then I would like some code like the following to work
然后我想要一些像下面这样的代码来工作
for layer in model.layers:
print(layer.get_shape())
.. but it doesn't. I get the error: AttributeError: 'Conv2D' object has no attribute 'get_shape'
.. 但它没有。我收到错误:AttributeError: 'Conv2D' object has no attribute 'get_shape'
采纳答案by Dat Nguyen
According to official doc for Keras Layer, one can access layer output/input shape via layer.output_shape
or layer.input_shape
.
根据Keras Layer 的官方文档,可以通过layer.output_shape
或 访问层输出/输入形状layer.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)
回答by Toke Faurby
If you want the output printed in a fancy way:
如果您希望以奇特的方式打印输出:
model.summary()
If you want the sizes in an accessible form
如果您想以可访问的形式显示尺寸
for layer in model.layers:
print(layer.get_output_at(0).get_shape().as_list())
There are probably better ways to access the shapes than this. Thanks to Daniel for the inspiration.
可能有比这更好的访问形状的方法。感谢丹尼尔的灵感。
回答by Daniel M?ller
Just use model.summary()
, and it will print all layers with their output shapes.
只需使用model.summary()
,它将打印所有图层及其输出形状。
If you need them as arrays, tuples or etc, you can try:
如果您需要它们作为数组、元组等,您可以尝试:
for l in model.layers:
print (l.output_shape)
For layers that are used more than once, they contain "multiple inbound nodes", and you should get each output shape separately:
对于多次使用的图层,它们包含“多个入站节点”,您应该分别获取每个输出形状:
if isinstance(layer.outputs, list):
for out in layer.outputs:
print(K.int_shape(out))
for out in layer.outputs:
It will come as a (None, 62, 62, 32) for the first layer. The None
is related to the batch_size, and will be defined during training or predicting.
它将作为第一层的 (None, 62, 62, 32) 出现。该None
是有关的batch_size,并且将训练或预测期间定义。