KerasでAttributeError: The layer has never been called and thus has no defined input shape.

モデルをロードしてからpredictしようとしたら表題のエラー。

擬似コードはこんな感じ。

model = tf.keras.models.load_model
model.predict(image)

AttributeError: The layer has never been called and thus has no defined input shape.

layerがcallされてないと怒られた。

KerasのLayerについて調べてみる。

Keras documentation: Making new layers and models via subclassing
Keras documentation

The __call__() method of your layer will automatically run build the first time it is called. You now have a layer that’s lazy and thus easier to use:

# At instantiation, we don’t know on what inputs this is going to get called

linear_layer = Linear(32)

# The layer’s weights are created dynamically the first time the layer is called

y = linear_layer(x)

モデルを定義するだけでなく、実際に何かを入力しなければlayerはcallされないのかな?

とりあえず何かをモデルに入力してみる

input_shape = (224, 224, 3)
model = tf.keras.models.load_model
model(tf.keras.layers.Input(input_shape)
model.predict(image)

理由はわからないが、これでエラーは出なくなった。

参考

RuntimeError: The layer has never been called and thus has no defined output shape. · Issue #44857 · tensorflow/tensorflow
Please make sure that this is a bug. As per our GitHub Policy, we only address code/doc bugs, performance issues, feature requests and build/installation issues...
Keras documentation: Making new layers and models via subclassing
Keras documentation

コメント

タイトルとURLをコピーしました