我也遇到了这个错误消息(RuntimeError: Unable to restore a layer of class TextVectorization. [...]
)当我实现(并定制)“基本文本分类”教程中的代码时。
我没有在笔记本中运行代码,而是有两个脚本,一个用于构建、训练和保存模型,另一个用于加载模型并进行预测。 (因此,该错误似乎并不局限于Google Colab)。
这就是我必须做的(参见https://github.com/tensorflow/tensorflow/issues/45231 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)