【问题标题】:Is there any solution for failing to load model in tensorflow2.3?在 tensorflow2.3 中加载模型失败有什么解决方案吗?
【发布时间】:2020-09-28 15:37:00
【问题描述】:

我尝试使用 tf.keras.models.load_model 在 tensorflow 2.3 中加载保存的模型。 但是,我遇到了同样的错误 https://github.com/tensorflow/tensorflow/issues/41535

这似乎是一个重要的功能。但是这个问题仍然没有解决。有谁知道是否有任何替代方法可以实现相同的结果?

【问题讨论】:

  • 我认为构建这样的模型是错误的方法。 train 不应该是模型类的方法......

标签: tensorflow tensorflow2.0


【解决方案1】:

我找到了一种在 tensorflow 2.3 中加载自定义模型的替代方法。您需要进行一些以下更改。我将通过一些代码快照来解释

  • 用于自定义模型的__init__()。之前,

    def __init__(self, mask_ratio=0.1, hyperparam=0.1, **kwargs):
        layers = []
        layer_configs = {}
        if 'layers' in kwargs.keys():
            layer_configs = kwargs['layers']
        for config in layer_configs:
            layer = tf.keras.layers.deserialize(config)
            layers.append(layer)
        super(custom_model, self).__init__(layers)  # custom_model is your custom model class
        self.mask_ratio = mask_ratio
        self.hyperparam = hyperparam
        ...
    

    之后,

    def __init__(self, mask_ratio=0.1, hyperparam=0.1, **kwargs):
        super(custom_model, self).__init__()  # custom_model is your custom model class
        self.mask_ratio = mask_ratio
        self.hyperparam = hyperparam
        ...
    
  • 在您的自定义模型类中定义两个函数

    def get_config(self):
        config = {
            'mask_ratio': self.mask_ratio,
            'hyperparam': self.hyperparam
        }
        base_config = super(custom_model, self).get_config()
        return dict(list(config.items()) + list(base_config.items()))
    @classmethod
    def from_config(cls, config):
        #config = cls().get_config()
        return cls(**config)
    
  • 训练完成后,使用'h5'格式保存模型

    model.save(file_path, save_format='h5')
    
  • 最后,加载模型如下代码,

    model = tf.keras.models.load_model(model_path, compile=False, custom_objects={'custom_model': custom_model})
    

【讨论】:

  • 很高兴看到您解决了您的问题,但请记住将代码本身而不是图像放在描述中。
  • @TimbusCalin 对不起图片,我尝试放代码,但我不知道为什么代码样式不起作用。
  • 好,只要遵守规则就可以了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-14
  • 1970-01-01
  • 2013-01-06
  • 2011-08-15
  • 1970-01-01
  • 2011-02-07
  • 1970-01-01
相关资源
最近更新 更多