使用自定义图层保存Keras模型

使用自定义图层保存Keras模型,第1张

使用自定义图层保存Keras模型

修正数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

希望这可以帮助。学习愉快!



欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/zaji/5661920.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存