当其他文件中定义的类时,带有自定义对象的 Keras load_model 无法正常工作

问题描述 投票:0回答:2

我的自定义图层出现问题

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

问题

如何解决这个问题?

tensorflow2.0 keras-layer
2个回答
0
投票

您应该在类

get_config
中定义一个
L2Layer

阅读this了解更多详情。


0
投票

您可以暂时克服此错误并通过运行定义类的代码部分来加载模型。运行该部分,以便此类定义包含在内存中,然后尝试使用相同的代码加载模型。

© www.soinside.com 2019 - 2024. All rights reserved.