tensorflow 模型包括预处理层,TextVectorization 在模型构建之前进行适配。尝试以“.h5”格式保存模型时,它显示错误:*NotImplementedError:保存或恢复不是
tf.Variable
实例的权重在h5中不受支持,请改用save_format='tf'
。接收到带有权重的模型或层 TextVectorization。
我用的是tensorflow 2.11.0,代码:
# vectorize
MAXTOKEN = 10000
OUTLENGTH = 100
vectorizer = tf.keras.layers.TextVectorization(max_tokens=MAXTOKEN, output_sequence_length=OUTLENGTH)
text_ds = train_ds.map(lambda x, y : x )
vectorizer.adapt(text_ds)
# functional API model
inputs = tf.keras.layers.Input(shape=(1,), dtype=tf.string)
x = vectorizer(inputs)
x = tf.keras.layers.Embedding(input_dim = MAXTOKEN, output_dim = OUTLENGTH)(x)
x = tf.keras.layers.LSTM(32)(x)
output = tf.keras.layers.Dense(1, activation='sigmoid')(x)
nlpmod = tf.keras.Model(inputs, output, name='nlp')
# compile
nlpmod.compile(loss=tf.keras.losses.BinaryCrossentropy(),
optimizer=tf.keras.optimizers.Adam(),
metrics=['accuracy'], run_eagerly=True)
# fit
hist = nlpmod.fit(train_ds, validation_data=test_ds, epochs=2)
# Trying to save - shows the error
nlpmod.save("nlpmod.h5")
我尝试使用降级的 tensorflow 版本 - 2.0 进行保存,但它不起作用。包括 tf.keras.layers.TextVectorization 作为模型中的层对我也不起作用。