系统信息Google Colab
当我运行官方的tensorflow基本文本分类提供的示例时,在模型保存之前,一切都会正常运行,但是当我加载模型时,它会给出这个错误。
RuntimeError:无法恢复类TextVectorization的层。类TextVectorization的层要求将类提供给模型加载代码,方法是在类def上注册使用@keras.utils.register_keras_serializable的类,并将该文件包含在程序中,或者将类传递到包装此负载调用的keras.utils.CustomObjectScope中。
预期行为:模型应成功加载并处理原始输入
示例链接:https://tensorflow.google.cn/tutorials/keras/text_classification
发布于 2021-03-15 10:12:46
在实现(并自定义)“基本文本分类”教程中的代码时,我还遇到了此错误消息(RuntimeError: Unable to restore a layer of class TextVectorization. [...])。
我没有在笔记本上运行代码,而是有两个脚本,一个用于构建、培训和保存模型,另一个用于加载和进行预测。(因此,这一错误似乎并不局限于Google )。
这是我必须做的(请参阅https://github.com/tensorflow/tensorflow/issues/45231):
首先,我在函数定义之前在第一个脚本中添加了这一行,并再次构建、训练和保存了模型:
@tf.keras.utils.register_keras_serializable()
def custom_standardization(input_data):
[...]
# Save model as SavedModel
export_model.save(model_path, save_format='tf')其次,我还必须在第二个脚本中添加相同的行和整个函数定义,以确保它在重新启动(!)时工作。ipython (我目前运行脚本的地方)并且只运行第二个脚本:
@tf.keras.utils.register_keras_serializable()
def custom_standardization(input_data):
lowercase = tf.strings.lower(input_data)
stripped_html = tf.strings.regex_replace(lowercase, '<br />', ' ')
return tf.strings.regex_replace(stripped_html,
'[%s]' % re.escape(string.punctuation),
'')
[...]
# Load model
reloaded_model = tf.keras.models.load_model(model_path)
# Make predictions
predictions = reloaded_model.predict(examples)注意:如果在运行第一个脚本后不重新启动ipython就运行第二个脚本,则会得到以下错误:
ValueError: Custom>custom_standardization has already been registered [...]或者,在构建模型时,只需在向量器层使用默认的标准化方法:
vectorize_layer = TextVectorization(
standardize="lower_and_strip_punctuation",
max_tokens=max_features,
output_mode='int',
output_sequence_length=sequence_length)发布于 2020-12-03 17:38:43
我想我找到了哈桑描述的有用的东西。不确定这是不是正确的方法,但它似乎对我有用.
见此处:https://github.com/OlivierLD/oliv-ai/tree/master/JupyterNotebooks/tf-tutorials/sentiment-analysis
https://stackoverflow.com/questions/65050132
复制相似问题