【问题标题】:Keras load_model with custom objects doesn't work properly when class defined in other file当在其他文件中定义类时,带有自定义对象的 Keras load_model 无法正常工作
【发布时间】:2020-12-09 18:54:00
【问题描述】:

我的自定义图层有问题

class L2Layer(tf.keras.layers.Layer):
    def __init__(self, **kwargs):
        super(L2Layer, self).__init__(**kwargs)

    def build(self, input_shape):
        # Create a trainable weight variable for this layer.
            self._x = self.add_weight(name='alpha_l2', 
                                    shape=(1,),
                                    initializer='ones',
                                    trainable=True)
        super(L2Layer, self).build(input_shape)  # Be sure to call this at the end

    def call(self, x):
        return self._x * tf.divide(x, tf.norm(x, ord='euclidean'))

    def compute_output_shape(self, input_shape):
        return input_shape[0]

保存在不同的 .py 文件中,例如:models.py。

当我尝试通过加载模型时

loaded_model = tf.keras.models.load_model('outputs/test.hdf5', custom_objects={'L2Layer': L2Layer})

我收到了错误:

NameError: name 'L2Layer' is not defined

问题

我该如何解决这个问题?

【问题讨论】:

  • 在类文件中,第一行以下的所有行都应该缩进。这能解决什么问题吗?
  • 尝试使用tf类型保存模型
  • 谢谢,@user1321988。我已经缩进了我的文件。在 StackOverflow 中粘贴时我丢失了缩进。还是不行
  • @DachuanZhao 我正在使用 tf.keras.callbacks.ModelCheckpoint 保存我的模型,但仍然无法正常工作。
  • @EmmanuelOvalle,你能给你的代码提供一个 google colab 吗?

标签: tensorflow2.0 keras-layer


【解决方案1】:

您应该在 L2Layer 类中定义一个 get_config。

阅读this了解更多详情。

【讨论】:

    猜你喜欢
    • 2019-08-08
    • 2018-06-10
    • 2010-11-04
    • 1970-01-01
    • 2018-07-18
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    相关资源
    最近更新 更多