簡體   English   中英

如何解決 Keras layer.get_output_shape_at() 拋出的異常“該層從未被調用過,因此沒有定義的輸出形狀”?

[英]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]

然后我的程序就可以繼續了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM