首页 > 解决方案 > How to solve the exception " The layer has never been called and thus has no defined output shape" thrown by Keras layer.get_output_shape_at()?

问题描述

I try to repeat some code on kaggle. I use tensorflow 2.3.1, Below is my code:

input_shape = (size, size, 3)
in_lay = tf.keras.layers.Input(shape = input_shape)

in_lay = tf.keras.layers.Input(shape = input_shape)
base_pretrained_model = tf.keras.applications.VGG16(input_shape = input_shape,
include_top = False, weights = 'imagenet')
base_pretrained_model.trainable = False
pt_depth = base_pretrained_model.get_output_shape_at(0)[-1]
pt_features = base_pretrained_model(in_lay)
bn_features = tf.keras.layers.BatchNormalization()(pt_features)
……

I get the error at the line " pt_depth = base_pretrained_model.get_output_shape_at(0)[-1]". The error is:

pt_depth = base_pretrained_model.get_output_shape_at(0)[-1]
File "/home/xxxx/anaconda3/envs/py36/lib/python3.6/site-packages/tensorflow/python/keras/engine/base_layer.py", line 2030, in get_output_shape_at
'output shape')
File "/home/xxxx/anaconda3/envs/py36/lib/python3.6/site-packages/tensorflow/python/keras/engine/base_layer.py", line 2603, in _get_node_attribute_at_index
'and thus has no defined ' + attr_name + '.')
RuntimeError: The layer has never been called and thus has no defined output shape.

What's the cause?

Thanks

标签: pythontensorflowkerastf.keras

解决方案


Try this method instead:

pt_depth = model.layers[0].compute_output_shape(input_shape)

推荐阅读