如何删除某些层并将其保存为tensorflow中的新模型?
我有以下代码来删除tensorflow中的top-N层,并且它可以工作:
reconstructed_model = tf.keras.models.load_model(model_path)
embedding = Model(reconstructed_model.input,
reconstructed_model.layers[-4].output)但是,当我尝试使用这两种方法中的任何一种来保存它时:
tf.keras.models.save_model(model=embedding, model_path)
embedding.save(model_path)我遇到以下错误:
KeyError: "Failed to add concrete function 'b'__inference_model_3_layer_call_fn_286241'' to object-based SavedModel as it captures tensor <tf.Tensor: shape=(), dtype=resource, value=<Resource Tensor>> which is unsupported or not reachable from root. One reason could be that a stateful object or a variable that the function depends on is not assigned to an attribute of the serialized trackable object (see SaveTest.test_captures_unreachable_variable)."我使用的预训练模型是来自tensorflow applications api的微调efficientnetv2
from tensorflow.keras.applications import EfficientNetB0我可以在这里保存和重用它,只是不知道如何在重新加载后保存修改后的文件。
发布于 2021-11-23 12:04:54
我尝试使用EfficientNetB0,并构建了一个截断最后四层的模型,就像您所做的那样。
from tensorflow.keras.applications import EfficientNetB0
import tensorflow as tf
efficientnet = EfficientNetB0( include_top=False )
embedding = tf.keras.models.Model(
efficientnet.input ,
efficientnet.layers[ -4 ].output
)
embedding.summary()
embedding.save( 'embedding_model.h5' )然后使用tf.keras.models.load_model加载模型,
model = tf.keras.models.load_model( 'embedding_model.h5' )
model.summary()我可以毫无问题地加载模型。也许reconstructed_model有一些问题。
https://stackoverflow.com/questions/70080360
复制相似问题