【发布时间】: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 吗?