如何解决 Keras layer.get_output_shape_at() 抛出的异常“The layer has never been called and thus has no defined output shape”?

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()?

我尝试在 kaggle 上重复一些代码。我使用 tensorflow 2.3.1,下面是我的代码:

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)
……

我在“pt_depth = base_pretrained_model.get_output_shape_at(0)[-1]”行收到错误。错误是:

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.

这是什么原因?

谢谢

试试这个方法:

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

我尝试了 Andrey 的修复,但在我的代码中的另一步失败了。所以它对我不起作用。

我从这个页面得到了解决方案:https://github.com/tensorflow/tensorflow/issues/44857。在获得外形之前,我们需要使用输入调用模型,如下所示:

in_lay = Input(t_x.shape[1:])
base_pretrained_model = VGG16(input_shape =  t_x.shape[1:], include_top = False, weights = 'imagenet')
base_pretrained_model.trainable = False
pt_features = base_pretrained_model(in_lay)
pt_depth = base_pretrained_model.get_output_shape_at(0)[-1]

然后我的程序就可以继续了。