
修正数1是使用
Custom_Objects同时
loading的
Saved Model,即,更换代码,
new_model = tf.keras.models.load_model('model.h5')与
new_model = tf.keras.models.load_model('model.h5', custom_objects={'CustomLayer': CustomLayer})由于我们使用
Custom Layers到
build了
Model之前
Saving的话,我们应该使用
CustomObjects,同时
Loading它。
更正数字2是在自定义图层
**kwargs的
__init__功能中添加
def __init__(self, k, name=None, **kwargs): super(CustomLayer, self).__init__(name=name) self.k = k super(CustomLayer, self).__init__(**kwargs)
完整的工作代码如下所示:
import tensorflow as tfclass CustomLayer(tf.keras.layers.Layer): def __init__(self, k, name=None, **kwargs): super(CustomLayer, self).__init__(name=name) self.k = k super(CustomLayer, self).__init__(**kwargs) def get_config(self): config = super(CustomLayer, self).get_config() config.update({"k": self.k}) return config def call(self, input): return tf.multiply(input, 2)model = tf.keras.models.Sequential([ tf.keras.Input(name='input_layer', shape=(10,)), CustomLayer(10, name='custom_layer'), tf.keras.layers.Dense(1, activation='sigmoid', name='output_layer')])tf.keras.models.save_model(model, 'model.h5')new_model = tf.keras.models.load_model('model.h5', custom_objects={'CustomLayer': CustomLayer})print(new_model.summary())上面代码的输出如下所示:
WARNING:tensorflow:No training configuration found in the save file, so the model was *not* compiled. Compile it manually.Model: "sequential_1"_________________________________________________________________Layer (type) Output Shape Param # =================================================================custom_layer_1 (CustomLayer) (None, 10) 0 _________________________________________________________________output_layer (Dense) (None, 1) 11 =================================================================Total params: 11Trainable params: 11Non-trainable params: 0
希望这可以帮助。学习愉快!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)