Geoffrey Anderson
Geoffrey Anderson

Reputation: 1564

Layer not built error, even after model.build() in tensorflow 2.0.0

Reference I was following: https://www.tensorflow.org/api_docs/python/tf/keras/Model#save I really want to run the model; give it some inputs; grab some layer outputs coming from inside the model.

model = tf.keras.models.load_model('emb_movielens100k_all_cols_dec122019')
input_shape = (None, 10)
model.build(input_shape)

All good so far; no errors no warnings.

model.summary()

ValueError: You tried to call `count_params` on IL, but the layer isn't built. You can build it manually via: `IL.build(batch_input_shape)`

How to fix?

Following code does not fix it:

IL.build(input_shape) # no

model.layer-0.build(input_shape)  # no

This seems to work: But it's a long way from my goal of running the model and grabbing some layer outputs. Isn't there an easy way in TF 2.0.0?

layer1 = model.get_layer(index=1)

This throws an error:

model = tf.saved_model.load('emb_movielens100k_all_cols_dec122019')
input_shape = (None, 10)
model.build(input_shape) #AttributeError: '_UserObject' object has no attribute 'build'

Upvotes: 1

Views: 794

Answers (1)

Geoffrey Anderson
Geoffrey Anderson

Reputation: 1564

The fix was to use save_model(), not model.save(). Also needed to use save_format="h5" during save, not default format. Like this:

tf.keras.models.save_model(model, "h5_emb.hp5", save_format="h5")

Also needed to use model_load(), not saved_model.load(), to load to memory from disk. Like this:

model = tf.keras.models.load_model('h5_emb.hp5') 

The other tutorial and documentation ways of doing save and load returned a model that did not work right for predictions or summary.

This is tensorflow version 2.0.0.

Hope this helps others.

Upvotes: 1

Related Questions