我的自定义图层出现问题
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
问题
如何解决这个问题?
您可以暂时克服此错误并通过运行定义类的代码部分来加载模型。运行该部分,以便此类定义包含在内存中,然后尝试使用相同的代码加载模型。