简体   繁体   English

图层未构建错误,即使在 tensorflow 2.0.0 中的 model.build() 之后

[英]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;我正在关注的参考资料: https ://www.tensorflow.org/api_docs/python/tf/keras/Model#save 我真的很想运行模型; 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? 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'

The fix was to use save_model(), not model.save().修复是使用 save_model(),而不是 model.save()。 Also needed to use save_format="h5" during save, not default format.还需要在保存期间使用 save_format="h5",而不是默认格式。 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.还需要使用 model_load() 而不是 saved_model.load() 从磁盘加载到内存。 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.这是张量流版本 2.0.0。

Hope this helps others.希望这对其他人有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM